en_USEnglish

JavaScript basics



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 a curious beginner or a seasoned developer looking to brush up on your knowledge, this comprehensive guide is designed to give you a solid understanding of key JavaScript concepts. From basic syntax to control structures, from 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

Declaration of variables

When working with JavaScript, we need to declare variables to store data. Declaring a variable is done using 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, which are 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 and immutable 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 operator +.

The numbers

In JavaScript, numbers are used to represent numeric values. They can be integers or decimals. For example, 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, that is, 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 provides several arithmetic operators to perform 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 if two values are equal.
  • Different (!=): Checks if two values are different.
  • Strictly equal (===): Checks if two values are equal in terms of type and value.
  • Strictly different (!==): Checks if two values are different in terms of type and value.
  • Greater than (>): Checks if one value is greater than another.
  • Less than (<): Checks if one value is less than another.
  • Greater than or equal (>=): Checks if one value is greater than or equal to another.
  • Less than or equal (<=): Checks if one value is less than or equal to another.
Read also  10 reasons why your startup needs a mobile app

Logical operators

Logical operators are used to combine conditional expressions and return a Boolean value based 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: Performs different actions based on 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 while 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 statements are used to perform different actions based 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: Performs different actions based on different possible values.

Jump control instructions

Jump control statements are used to modify the flow of execution of a program. The most commonly used jump control statements in JavaScript are:

  • break: stops the execution of a loop or conditional statement.
  • continue: interrupts one iteration of a loop and moves on to the next iteration.
  • return: Returns a value from a function and stops the function from executing.

The functions

Definition of functions

Functions are used to group a set of instructions and execute them when needed. 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 must call it using its name followed by the parentheses containing the arguments. For example, to call the function calculateSum that we defined previously, 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.

Read also  What is the Lightning Network?

Value feedback

Functions can return a value using the keyword return. When a function reaches a return, it returns the specified value and stops the 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 separating the values with commas. For example, var fruits = ['apple', 'banana', 'orange'];.

Access to elements

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 the array fruitwe would use fruits[0];.

Editing elements

To change the value of a specific element of an array, we use its index and the assignment operator (=). For example, to modify the second element of the array fruit at kiwiwe 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(): removes the last element from the array.
  • shift() : removes 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 removing elements.

Objects

Creating objects

Objects are used to group related properties and methods. An object is defined using curly braces ({}) and specifying the corresponding properties and values. For example, var car = { make: 'Toyota', model: 'Corolla', year: 2020 };.

Access to properties

To access a specific property of an object, we use dot notation (.) followed by the property name. For example, to access the property brand object carwe would use car.make;.

Editing properties

To change the value of a specific property of an object, we use dot notation (.) and the assignment operator (=). For example, to change the value of the property model object car at Camrywe 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, var person = { name: 'John', age: 30, direBonjour: function() { console.log('Bonjour!'); } };. To call a method of an object, we use the dot notation (.) followed by the method name. For example, person.sayHello();.

The scope of variables

Global scope

Global scope refers to all variables, functions, and objects that are defined outside of any function. Variables declared in global scope are accessible 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 are only accessible within that function.

Scope of functions

When a function is defined inside another function, the scope of the inner function is limited to the outer function. Variables declared inside the outer function are accessible to both the outer and inner functions, but variables declared inside the inner function are accessible only to the inner function.

Read also  Discover the key concepts for creating web/mobile applications

DOM manipulation

Selection of elements

The DOM (Document Object Model) is a tree-like representation of all the elements in an HTML document. To select a specific element from the DOM, we use methods such as getElementByIdgetElementsByClassName or getElementsByTagName. For example, var title = document.getElementById('title');.

Content editing

Once we have selected a DOM element, we can modify its contents 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 change 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 on 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, 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 template. 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,

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  direBonjour() {
    console.log('Hello!');
  }
}

Heritage and prototypes

Inheritance allows one 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,

class Student extends Person { constructor(name, age, level) { super(name, age); this.level = level; } sayHello() { super.sayHello(); console.log('I am a student!'); } }

Errors and exception handling

Error types

JavaScript can encounter several types of errors 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 correct JavaScript syntax.
  • Reference errors: Occur when code tries to access a variable or method that does not exist.
  • Generic errors: Occur when code throws an exception that was not 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 the code that might throw an exception, while the catch block is used to handle the exception by executing a specific block of code. For example,

try { // Code that might throw an exception } catch (error) { // Code to handle the exception }

Exception handling

Exception handling is the process of taking appropriate action in response to an exception. The actions taken can vary depending on the type of error encountered. For example, we can display an error message to the user or retry the operation that generated the exception. Exception handling allows us to handle errors gracefully and keep our program running smoothly.