Discover the fundamentals of JavaScript. A comprehensive guide to key concepts, from basic syntax to control structures, arrays and objects.
In this article, we will explore the fundamentals of programming language JavaScript. Whether you're an inquisitive beginner or a seasoned developer looking to brush up on your skills, this comprehensive guide is designed to give you a solid understanding of JavaScript's key concepts. From basic syntax to control structures, arrays and objects to functions and events, we'll guide you through this exciting learning journey. So get ready to dive into the fascinating world of JavaScript and discover everything this powerful language has to offer.
Variables and data types
Variable declaration
When working with JavaScript, we need to declare variables in order to store data. To declare a variable, use the keyword var
followed by the name of the variable we want to use. For example, to declare a variable called age
we would write var age;
.
Primitive data types
JavaScript offers several primitive data types, i.e. basic data types that are not objects. The most commonly used primitive data types are :
- String: used to represent text.
- Number: used to represent numbers.
- Boolean: used to represent a truth value (true or false).
- Undefined: used to represent a variable that has not yet been assigned a value.
- Null: used to represent the absence of a value.
- Symbol: used to create unique, unchangeable identifiers.
Character strings
Strings are used to represent text in JavaScript. A string is defined by surrounding the text with single quotes ( ") or double quotes (" "). For example, var name = 'John';
or var message = "Hello everyone";
. Strings can be concatenated using the +
.
The numbers
In JavaScript, numbers are used to represent numerical values. They can be integers or decimals. For example, numbers can be integers or decimals, var numberInteger = 10;
or var decimalnumber = 3.14;
. Numbers can be used in arithmetic operations such as addition, subtraction, multiplication and division.
Booleans
Booleans are used to represent truth values, i.e. values that can be either true or false. Booleans are often used in conditional expressions to make decisions. For example, var isTrue = true;
or var isFalse = false;
.
Operators and expressions
Arithmetic operators
JavaScript offers a number of arithmetic operators for performing mathematical calculations. The most commonly used arithmetic operators are :
- Addition (+): used to add two values.
- Subtraction (-): used to subtract one value from another.
- Multiplication (*): used to multiply two values.
- Division (/): used to divide one value by another.
- Modulo (%): used to obtain the remainder of the division of two numbers.
Comparison operators
The operators of comparison are used to compare values and return a Boolean value (true or false) depending on the result of the comparison. The most commonly used comparison operators are :
- Equal (==): checks whether two values are equal.
- Different (!=): checks whether two values are different.
- Strictly equal (===): checks whether two values are equal in terms of type and value.
- Strictly different (!==): checks whether two values are different in terms of type and value.
- Superior (>): checks whether one value is superior to another.
- Lower (<): checks whether one value is lower than another.
- Greater than or equal to (>=): checks whether one value is greater than or equal to another.
- Less than or equal to (<=): checks whether one value is less than or equal to another.
Logic operators
Logical operators are used to combine conditional expressions and return a Boolean value depending on the result of the combination. The most commonly used logical operators are :
- AND (&&): returns true if all expressions are true, otherwise false.
- OR (||): returns true if one of the expressions is true, otherwise false.
- NO (!): inverts the value of an expression (true becomes false and vice versa).
Conditional expressions
Conditional expressions, also known as conditional statements, are used to make decisions based on a condition. The most commonly used conditional expressions are :
- if: executes a block of code if a condition is true.
- else: executes a block of code if a condition is false.
- else if: allows you to check several different conditions.
- switch: executes different actions according to different possible values.
Control structures
Loops
Loops are used to repeat a series of instructions until a specific condition is met. The most commonly used loops in JavaScript are :
- for: repeats a block of code a specified number of times.
- while: repeats a block of code as long as a specified condition is true.
- do...while: repeats a block of code once, then repeats the block as long as a specified condition remains true.
Conditional instructions
Conditional instructions are used to execute different actions depending on a specific condition. The most commonly used conditional statements in JavaScript are :
- if...else: executes a block of code if a condition is true, otherwise executes another block of code.
- switch...case: executes different actions according to different possible values.
Jump control instructions
Jump control instructions are used to modify the execution flow of a program. The most commonly used jump control instructions in JavaScript are :
- break: stops the execution of a loop or conditional instruction.
- continuous: interrupts an iteration of a loop and moves on to the next iteration.
- return: returns a value from a function and stops execution of the function.
The functions
Defining functions
Functions are used to group together a set of instructions and execute them when required. A function is defined using the keyword function
followed by the function name and parentheses containing the function parameters. For example, to define a function called calculateSum
we would write function calculateSum(a, b) { ... }
.
Calling up functions
To execute a function, we need to call it using its name followed by the parentheses containing the arguments. For example, to call the function calculateSum
which we defined earlier, we would write calculateSum(5, 10);
.
Passing parameters
Parameters are used to pass values to a function. When we define a function, we can specify the parameters we need. When we call the function, we pass the corresponding values to the parameters. For example, in the function calculateSum(a, b)
, a
and b
are parameters.
Value feedback
Functions can return a value using the keyword return
. When a function reaches a return
returns the specified value and stops execution of the function. For example, in the function calculateSum(a, b)
we could use return a + b;
to return the sum of the two numbers.
Paintings
Declaration of tables
Arrays are used to store multiple values in a single variable. An array is declared using square brackets ([]
) and separate the values with commas. For example, var fruits = ['apple', 'banana', 'orange'];
.
Element access
To access a specific element of an array, we use its index. The first element of an array has an index of 0, the second has an index of 1, and so on. For example, to access the first element of an array fruit
we would use fruits[0];
.
Modifying elements
To modify the value of a specific element in an array, we use its index and the assignment operator (=
). For example, to modify the second element of the table fruit
at kiwi
we would use fruits[1] = 'kiwi';
.
Useful methods
JavaScript offers several built-in methods for working with arrays. Here are some of the most commonly used methods:
- push(): adds an element to the end of the array.
- pop(): deletes the last element of the array.
- shift(): deletes the first element of the array.
- unshift(): adds an element to the beginning of the array.
- slice(): returns a partial copy of the array.
- splice(): modifies the contents of the array by adding or deleting elements.
Objects
Object creation
Objects are used to group together properties and associated methods. An object is defined using braces ({}
) and specifying the corresponding properties and values. For example, you can var car = { make: 'Toyota', model: 'Corolla', year: 2020 };
.
Property access
To access a specific property of an object, we use the dotted notation (.
) followed by the property name. For example, to access the brand
object car
we would use car.make;
.
Property modification
To modify the value of a specific property of an object, we use the dotted notation (.
) and the assignment operator (=
). For example, to modify the value of the model
object car
at Camry
we would use car.model = 'Camry';
.
Object methods
An object can also contain methods, which are functions associated with the object. Methods are defined in the same way as functions, but inside the object. For example, a method can be var person = { name: 'John', age: 30, direBonjour: function() { console.log('Bonjour!'); } };
. To call an object's method, we use the dotted notation (.
) followed by the method name. For example, person.sayHello();
.
The scope of variables
Global reach
Global scope refers to all variables, functions and objects that are defined outside any function. Variables declared in the global scope can be accessed anywhere in the code.
Local scope
Local scope refers to variables, functions and objects that are defined inside a function. Variables declared inside a function can only be accessed within that function.
Scope of functions
When a function is defined inside another function, the scope of the internal function is limited to the external function. Variables declared inside the external function are accessible to both the external and internal functions, but variables declared inside the internal function are accessible only to the internal function.
DOM manipulation
Element selection
The DOM (Document Object Model) is a tree-like representation of all the elements in an HTML document. To select a specific DOM element, we use methods such as getElementById
, getElementsByClassName
or getElementsByTagName
. For example, var title = document.getElementById('title');
.
Content editing
Once we've selected a DOM element, we can modify its content using the appropriate properties. For example, to modify the text of an element, we use textContent
or innerHTML
. For example, title.textContent = 'New title';
.
Style editing
We can also modify the styles of a DOM element by using the appropriate style properties. For example, to change the background color of an element, we use backgroundColor
. For example, title.style.backgroundColor = 'blue';
.
Event management
Events are actions that occur within a web page, such as clicking a button or hovering over an image. We can add event listeners to DOM elements to execute code in response to these events. For example, we can add event listeners to DOM elements to execute code in response to these events, button.addEventListener('click', myFunction);
will call myFunction
when the button is clicked.
Classes and prototypes
Creating classes
Classes are used to create objects based on a common model. A class is defined using the keyword class
followed by the class name. We can then define the class's properties and methods inside its body. For example, we can define
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
direBonjour() {
console.log('Hello!');
}
}
Heritage and prototypes
Inheritance allows a class to inherit properties and methods from another class. In JavaScript, inheritance is achieved using prototypes. Prototypes are objects that act as templates for creating new objects. For example, a
class Student extends Person {
constructor(name, age, level) {
super(name, age);
this.level = level;
}
direBonjour() {
super.direBonjour();
console.log('I'm a student!');
}
}
Errors and exception handling
Error types
JavaScript can encounter several types of error during code execution. The most common errors are syntax errors, reference errors and generic errors.
- Syntax errors: occur when code is poorly written and does not follow the correct JavaScript syntax.
- Reference errors: occur when code tries to access a variable or method that does not exist.
- Generic errors: occur when the code generates an exception that has not been specifically handled.
Using the try-catch block
To handle errors and exceptions, we can use the try-catch block. The try block is used to surround code likely to generate an exception, while the catch block is used to handle the exception by executing a specific block of code. For example, a
try {
// Code likely to generate an exception
} catch (error) {
// Code to handle the exception
}
Exception handling
Visit management exceptions is to take measures in response to an exception. The action taken may vary according to the type of error encountered. For example, we may display an error message to the user or retry the operation that generated the exception. Exception handling allows us to handle errors elegantly and keep our program running smoothly.