A Beginner's Guide 🎉
Where Do We Use JS
operations
History of JavaScript
Variables & Constants
Conditions and loops
What is JS?
Arrays
And more....
# What is JS?
The Magic Behind Interactive Web Pages! 🌟
JavaScript is a high-level, interpreted programming language primarily used for creating dynamic, interactive web applications.
# What is JS?
# What is HTML?
# Basic Structure
In 1995, a programmer named Brendan Eich had a mission:
To create a language for the web. But guess what?
⏳ He only had 10 days to do it!
Thus, JavaScript was born — even though it has nothing to do with Java!
🎥 Imagine Netflix with no autoplay previews or Gmail without real-time updates.
From those humble beginnings, JavaScript grew into a powerhouse that developers (like you!) still use every day.
# VSC Interface Overview
# CHAPTER 2
# CHAPTER 2
JavaScript originally ran in your browser, bringing interactivity to websites.
Examples:
In 2009, Node.js changed the game:
JavaScript could now run on servers, powering backends and APIs.
Why It’s Big:
# Essential Extensions
# VSC Interface Overview
var <var_name>;
// -Declarations
// var X
var name;
var anotherName;
var Name3;
var 4thName; // wrong declaration
var diffrent_name;
var §erfez; // wrong declaration
var $name;
var _name;
Variables are Containers for storing data that might change during the program’s exe.
// Numbers
var num = 5, negNum = -55, float = 6.3;
Number.isNaN(num) // false
Number.isNaN("5") // false
Number.isNaN("hello"); // true
Number.islnteger(num); // true
Number.islnteger(float); // false
Number.isFinite(Infinity); // false
Number.isFinite(100); // true
Numbers between -(2^53 − 1)
and 2^53 − 1 (
9007199254740991)
the number type has three symbolic values: +Infinity, -Infinity, and NaN ("Not a Number").
# VSC Interface Overview
# VSC Interface Overview
var text = "message",
text2 = 'message2';
String type is used to represent textual data. It is a set of "elements" of 16-bit unsigned integer values. Each element in the String occupies a position in the String. The first element is at index 0, the next at index 1, and so on.
# VSC Interface Overview
// bool
var conditionT = true;
var conditionF = false;
a Boolean is a logical data type that can have only the values true or false
# VSC Interface Overview
var empty1= null;
Null expresses a lack of identification, indicating that a variable points to no object.
var x; //undefined
A variable that has not been assigned a value is of type undefined.
# VSC Interface Overview
const <const_name> : <value>;
// Constants
const Trainer= "Fatima BENAZZOU";
const Students= 8;
Trainer = "Someone Else" /* Uncaught TypeError: Assignment
* to constant variable.*/
const Assistant; /* Uncaught SyntaxError: Missing initializer
* in const declaration*/
Constants are Fixed values that don’t change during the program’s execution.
# VSC Interface Overview
# Attributes
const userInput = prompt("Enter a value :");
console.log("You have entered :", userInput);
# VSC Interface Overview
Practice:
- Ask the user for their name and display a welcome message in the console
// Arithmetic operations
x = 5 + 6; // addition
y = 7 - 3; // minus
z = 4 * 4; // multiplication
a = 7 / 2; // division
b = 4 ** 2; // power
b = b % 2; // Modulus
a++; // Increment
b--; // Decrement
x=x+2 //<=> x+=2;
# VSC Interface Overview
// String manipulation
var name = "Fatima";
var text = "Hello new user : " + name;
// **Template Literals** (ES6): backticks for cleaner syntax:
var message= `From ${name} : ${text}`
# VSC Interface Overview
// Logical operations
c = (x >= y); // ( x > y )
d = (y <= z); // ( y < z )
e = (z == x);
f = (5 == "5");
g = (5 === "5");
h = (5 !== "5");
i = (name == text);
j = (!g);
k = (c && e);
l = (c || e);
# VSC Interface Overview
# VSC Interface Overview
# Customize Your VSCode
// Conditions
if (/* condition1 */) {
/* Instractions 1 */
} else if (/* condition2 */) { // optional
/* Instractions 2 */
} else { // optional
/* Instractions 3 */
}
# VSC Interface Overview
let bool1=true, bool2=true;
if (bool1) {
console. log( "hello! i 'm the 1st if ^.^");
} else if (!bool2) {
console.log("hell! i 'm the 2nd if");
} else {
console.log("the unique else uwu");
}
// question mark operation (ternary)
let max = a>b ? a : b;
// question mark operation (ternary)
( condition ) ? (true Result) : (false Result)
# VSC Interface Overview
switch ( <var_name> ) {
case <value_1 / var_name_1> : <instructions_1> break;
case <value_2 / var_name_2> : <instructions_2> break;
…
Case <value_n / var_name_n> : <instructions_n> break;
Default: <instructions> break;
}
# VSC Interface Overview
const pet = "dog";
switch (pet) {
case "cat":
console. log( "I own a cat");
break;
case "dog" :
console. log( "I own a dog");
break;
case "snake":
console. log( "I own a snake");
break;
default :
console.log("don't own a pet");
break;
}
# VSC Interface Overview
# Customize Your VSCode
// Syntaxe:
for (let <var_name> = min; <var_name> < max; <var_name>++) {
<instructions>
};
// Exemple :
for (let i = 0; i < n; i++) {
//instructions
};
# VSC Interface Overview
// loop 1
while (/* condition */) {
/* Instractions to repeat */
}
// loop 2
do{
/* Instractions to repeat */
} while (/* condition */) ;
# VSC Interface Overview
# VSC Interface Overview
Using JavaScript, write code to implement all the algorithms we discussed in the previous chapter.
# Customize Your VSCode
# VSC Interface Overview
In JS, an array is a data structure used to store multiple values in a single variable, you can see it as an ordered list of values. It can hold a collection of elements, including numbers, strings, objects, or even other arrays.
[1, "hello", true, null];
Arrays are zero-indexed. The first element is at index 0.
Arrays are dynamic and can grow or shrink dynamically.
Arrays can store elements of different data types.
# VSC Interface Overview
var color1 = "red";
var color2 = "green";
var color3 = "orange";
If you have a list of items (a list of color names, for example), storing the colors in single variables could look like this:
# VSC Interface Overview
However, what if you want to loop through the colors and find a specific one? And what if you had not 3 colors, but 300?
An array can hold many values under a single name, and you can access the values by referring to an index number.
# VSC Interface Overview
var array_name = [item1, item2, ...];
# VSC Interface Overview
It is a common practice to declare arrays with the const keyword.
var colors = ["red", "green", "orange"];
const strawhats = ["luffy", "zoro", "sanji", "nami", "tony tony chopper", "usopp", "robin", "franky", "brook", "jinbe"]
# VSC Interface Overview
You can also create an array, and then provide the elements
var colors = [];
colors[0]= "red";
colors[1]= "green";
colors[2]= "orange";
var array_name = new Array (iten1,item2, …);
# VSC Interface Overview
Example
var colors = new Array("red", "green", "orange");
# VSC Interface Overview
! Avoid using new Array(). Use [] instead.
But why ?
// Create an array with one element:
var points = [40];
// Create an array with 40 undefined elements:
var points = new Array(40);
const arr = [10, 20, 30];
console.log(arr.length); // 3
# VSC Interface Overview
const arr = [10, 20, 30, 40, 50];
console.log(arr[0]); // 10
console.log(arr[2]); // 30
console.log(arr[arr.length -1]); // 50 => last element of the array
You access an array element by referring to the index number
const arr = [10, 20, 30];
arr[1] = 50;
console.log(arr); // [10, 50, 30]
# VSC Interface Overview
# VSC Interface Overview
Example
const arr = [10, 20, 30];
arr.push(40); // [10, 20, 30, 40]
arr.pop(); // [10, 20, 30]
arr.unshift(5); // [5, 10, 20, 30]
arr.shift(); // [10, 20, 30]
# VSC Interface Overview
Example
const arr = [10, 20, 30];
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]); // Output: 10, 20, 30
}
The traditional way to iterate through an array.
# VSC Interface Overview
Example
const arr = [10, 20, 30];
for (const num of arr) {
console.log(num); // Output: 10, 20, 30
}
Simpler and more readable when you only care about the values in the array.
# VSC Interface Overview
Example
const arr = [10, 20, 30];
for (const index in arr) {
console.log(`Index: ${index}, Value: ${arr[index]}`);
}
Used to iterate over the indices (keys) of an array. This is less common for arrays but can be useful in specific cases.
Important Note: Avoid using for...in
for arrays unless you explicitly need indices, as it can iterate over non-indexed properties if the array is extended.
# VSC Interface Overview
Example
const arr = [10, 20, 30];
arr.forEach((num, index) => {
console.log(`Index: ${index}, Value: ${num}`);
});
// Output:
// Index: 0, Value: 10
// Index: 1, Value: 20
// Index: 2, Value: 30
Best for performing a specific action for each element in the array. Cannot use break or continue.
# VSC Interface Overview
Example
const arr = [10, 20, 30, 20];
console.log(arr.indexOf(20)); // 1
console.log(arr.lastIndexOf(20)); // 3
console.log(arr.includes(30)); // true
# VSC Interface Overview
Example
const numbers = [1, 2, 3, 4];
// map
const doubled = numbers.map(num => num * 2); console.log(doubled); // [2, 4, 6, 8]
// filter
const evens = numbers.filter(num => num % 2 === 0); console.log(evens); // [2, 4]
// reduce
const sum = numbers.reduce((acc, curr) => acc + curr, 0); console.log(sum); // 10
# VSC Interface Overview
Example
const arr = [3, 1, 4, 1, 5];
arr.sort(); // [1, 1, 3, 4, 5]
arr.reverse(); // [5, 4, 3, 1, 1]
// Custom sort (numerical order)
arr.sort((a, b) => a - b); // [1, 1, 3, 4, 5]
# VSC Interface Overview
Example
const arr1 = [1, 2];
const arr2 = [3, 4];
const combined = arr1.concat(arr2); // [1, 2, 3, 4]
const sliced = combined.slice(1, 3); // [2, 3]
combined.splice(1, 2, 99, 100); // [1, 99, 100, 4]
# VSC Interface Overview
Example
const nested = [1, [2, [3, 4]]];
console.log(nested.flat(2)); // [1, 2, 3, 4]
# VSC Interface Overview
Example
When an array is declared with the const keyword, it doesn't mean the array is immutable. Instead, const defines a constant reference to the array. You cannot reassign the entire array, but you can modify its elements or add new ones.
const fruits = ["apple", "banana", "cherry"];
// You can change an element
fruits[0] = "pear";
console.log(fruits); // ["pear", "banana", "cherry"]
// You can add an element
fruits.push("orange");
console.log(fruits); // ["pear", "banana", "cherry", "orange"]
// You cannot reassign the array itself
fruits = ["new", "array"]; // Error: Assignme
# VSC Interface Overview
Example
Arrays declared with const must be initialized with a value when they are declared. Declaring a const array without initialization will throw a syntax error.
const numbers; // SyntaxError: Missing initializer in const declaration
# VSC Interface Overview
Example
In contrast, arrays declared with var can be initialized later and even used before their declaration (though this is not recommended due to potential confusion).
console.log(myArray); // undefined (hoisting behavior)
var myArray = [1, 2, 3];
console.log(myArray); // [1, 2, 3]
# VSC Interface Overview
# VSC Interface Overview
You have the following inventory:
"Minecraft"
is in stock using includes
."Zelda"
using indexOf
."Call of Duty"
with "GTA V"
using splice
."Among Us"
at a specific position.const games = ["Zelda", "Minecraft", "Call of Duty"];
# VSC Interface Overview
The participants’ scores are:
map
, doubling each score.filter
.reduce
.const scores = [55, 89, 72, 45, 100, 65];
# VSC Interface Overview
Your travel steps are:
["fishmen island", "dressrosa"]
using concat
.slice
to create a new list with only "Alabasta"
and "Water 7"
.reverse
.sort
.const itinerary = ["Alabasta", "Water 7", "Red line"];
# VSC Interface Overview
Given the numbers:
const puzzle = [8, 4, 2, 10, 6];
[[8, 4], [2, 10], [6]];
# Customize Your VSCode
# VSC Interface Overview
A function is a set of code designed to perform a specific task, in the form of reusable code blocks, it is written once but is executed any number of times in the JavaScript program where it is defined.
A function is a set of code designed to perform a specific task, in the form of reusable code blocks, it is written once but is executed any number of times in the JavaScript program where it is defined.
Keep related operations grouped together.
Call the same code block multiple times without rewriting it.
Hide implementation details behind a simple interface.
# VSC Interface Overview
Functions are executed when "something" invokes it (calls it).The functions generally are used to eliminate code complexity by enabling re-usability.
Think of a function as a coffee machine.
# VSC Interface Overview
function functionName(parameter1, parameter2, ...) {
// Function body: logic to be executed
return value; // Optional
}
// EXemple
function calculateArea(width, height) {
const area = width * height
return area;
}
It is necessary to define a JavaScript function before using it. The common method for defining a function is by using the following syntax:
# VSC Interface Overview
# VSC Interface Overview
# VSC Interface Overview
After defining a function in a JavaScript program, if we want to use it anywhere within that program, we simply need to mention its name with the parameters list.
functionName(argument1, argument2, ...);
function greet(name) {
console.log(`Hello, ${name}!`);
}
greet("Fatima"); // Output: Hello, Fatima!
# VSC Interface Overview
What Are Parameters?
function greet(name) {
console.log("Hello, " + name + "!");
}
Here, name is the parameter of the function greet.
# VSC Interface Overview
What Are Arguments?
greet("Fatima"); // Output: Hello, Fatima!
"Fatima" is the argument passed to the greet function. It replaces the name parameter during execution.
# VSC Interface Overview
Number of Parameters vs. Arguments
undefined
.function multiply(a, b) {
console.log(a * b);
}
multiply(5); // Output: NaN (b is undefined)
multiply(5, 2, 3); // Output: 10 (Extra argument ignored)
# VSC Interface Overview
Default Parameters
JavaScript allows you to assign default values to parameters. These defaults are used if no argument is passed or if the argument is undefined.
function greet(name = "Stranger") {
console.log("Hello, " + name + "!");
}
greet(); // Output: Hello, Stranger!
greet("Naruto"); // Output: Hello, Naruto!
# VSC Interface Overview
Passing Arguments by Value
function changeValue(x) {
x = 10;
console.log("Inside function:", x);
}
let num = 5;
changeValue(num);
console.log("Outside function:", num);
// Output:
// Inside function: 10
// Outside function: 5
# VSC Interface Overview
Function Declarations
function
keyword.console.log(square(4)); // Output: 16
function square(n) {
return n * n;
}
# VSC Interface Overview
Function Expressions (Anonymous function)
const multiply = function(a, b) {
return a * b;
};
console.log(multiply(2, 3)); // Output: 6
# VSC Interface Overview
Arrow Functions (Lambda function, ES6)
const functionName = (parameters) => expression;
const add = (a, b) => a + b;
console.log(add(5, 7)); // Output: 12
# VSC Interface Overview
Local Scope
function example() {
var localVar = "I'm local";
console.log(localVar); // Accessible
}
// console.log(localVar); // Error: localVar is not defined
# VSC Interface Overview
Global Scope
var globalVar = "I'm global";
function showGlobal() {
console.log(globalVar); // Accessible
}
showGlobal();
# VSC Interface Overview
Block Scope (ES6)
if (true) {
var blockScoped = "I'm block-scoped";
console.log(blockScoped); // Accessible
}
// console.log(blockScoped); // Error: blockScoped is not defined
# VSC Interface Overview
# Customize Your VSCode
# VSC Interface Overview
An object is a collection of properties, where each property is a key-value pair.
Objects are one of the fundamental building blocks of JavaScript and are used to model real-world entities or data.
An object is like a student record:
# VSC Interface Overview
# VSC Interface Overview
The simplest way to create an object.
const student = {
name: "Kenza",
age: 21,
level: 4
};
console.log(student); // Output: { name: 'Kenza', age: 21, level: 4}
# VSC Interface Overview
Less common and used in specific scenarios.
const student = new Object();
student.name = "Kenza";
student.age = 21;
student.level= 4;
console.log(student); // Output: { name: 'Kenza', age: 21, level: 4}
# VSC Interface Overview
The most common way to access properties.
Useful when the property name is dynamic or contains special characters.
console.log(student.name); // Output: "Kenza"
console.log(student["age"]); // Output: 21
# VSC Interface Overview
const key = "level";
console.log(student[key]); // Output: 4
# VSC Interface Overview
student.school = "Dely brahim";
console.log(student);
student.level= 5;
console.log(student.level);
delete student.age;
console.log(student);
# VSC Interface Overview
for (var key in student) {
console.log(`${key}: ${student[key]}`);
}
Used to iterate over an object’s enumerable properties.
console.log(Object.keys(student));
Returns an array of keys.
# VSC Interface Overview
console.log(Object.values(student));
Returns an array of values.
console.log(Object.entries(student));
Returns an array of key-value pairs.
# VSC Interface Overview
const student = {
name: "Fatima",
subjects: {
math: "A",
science: "B"
}
};
console.log(student.subjects.math);
Objects can contain other objects as values.
# VSC Interface Overview
const student = {
name: "Fatima",
greet: function(name) {
console.log(`Hello, my name is ${name}.`);
}
};
student.greet("fatima"); // Output: Hello, my name is Fatima.
Objects can have functions as properties, called methods.
# VSC Interface Overview
name
(e.g., "Eren Yeager").level (from 1 to 12)
.grades
: object containing at least three subjects and their scores (e.g., { math: 85, english: 90, history: 78 }.# VSC Interface Overview
deposit(amount): A
method that adds an amount to the balance.withdraw(amount)
: A method that subtracts an amount from the balance only if there are sufficient funds.# VSC Interface Overview
# VSC Interface Overview
character
to represent a hero in an RPG game.name
: Name of the character (e.g., "Eren Yeager").level
: Character's level (default: 1).health
: Character's health points (default: 100).inventory
: An array to store collected items (starts empty).levelUp()
: Increase the level by 1 and health by 20.addItem(item)
: Add an item to the inventory.displayStats()
: Log all character stats to the console.Challenge: Create a second character and simulate a battle by reducing the health
property based on a damage value.
# VSC Interface Overview
pokedex
.name
: Name of the Pokémon (e.g., "Pikachu").type
: Type of the Pokémon (e.g., "Electric").hp
: Hit points of the Pokémon.moves
: An array of moves with their names and damage values.
Task: Write a function called battle(pokemon1, pokemon2)
that simulates a turn-based battle between two Pokémon. Reduce the HP of each Pokémon based on the damage of randomly chosen moves. The battle continues until one Pokémon's HP reaches zero.
moves: [{ name: "Thunderbolt", damage: 90 },{ name: "Quick Attack", damage: 40 }]
# VSC Interface Overview
Create an object named animeLibrary
with the following properties:
animeList
: An array of objects where each object represents an anime with:
title
: Title of the anime.genre
: Array of genres (e.g., ["Action", "Fantasy"]).rating
: Rating out of 10.Tasks:
Write a method addAnime(anime)
to add a new anime to the library. Write a method getRecommendations(genre)
that returns a list of animes matching a specific genre. Write a method getTopRated()
to return the anime with the highest rating.
# VSC Interface Overview
store
to represent a game store.games
: An array of objects where each game has:
title
: Name of the game (e.g., "Elden Ring").genre
: Game genre (e.g., "RPG").price
: Game price.stock
: Number of copies available.Challenge: Create a wallet object for the user with properties like balance
, and link it to the buyGame
method.Write a function buyGame(title)
that reduces the stock of the game by 1 if it's available and deducts the price from the user’s wallet. If the game is out of stock, log a message.
# VSC Interface Overview
searchGames(keyword)
to find games whose title contains a specific keyword (case-insensitive).
Tasks:
Write a function addGame(game)
to add a new game to the store.
# VSC Interface Overview
magicGuild
that represents a guild in a fantasy world.name
: Name of the member.rank
: Rank in the guild (e.g., "S-Class", "A-Class").magicType
: Type of magic (e.g., "Fire", "Ice", "Celestial").missionsCompleted
: Number of missions completed.
Challenge: Track the total missions completed by the guild using a guildStats
property.
# VSC Interface Overview
Tasks:
Write a functionaddMember(member)
to add a new member to the guild. Write a function promoteMember(name)
that promotes a member to the next rank based on their missions completed.
Write a function displayMembersByMagicType(type)
to list all members with a specific magic type.
# VSC Interface Overview
AnimeCollection
to represent an anime merchandise collection.figures
: An array of anime figure objects with properties name
, series
, and price
.manga
: An array of manga objects with properties title
, volume
, and price
.budget
: Total money available to buy items.
Tasks:
Write a function buyItem(type, itemName)
to buy an item (e.g., a figure or manga). Deduct the price from the budget if affordable. Write a function displayCollection()
to list all items in the collection. Write a function searchBySeries(seriesName)
to find all figures or manga from a specific series.
# Customize Your VSCode
# VSC Interface Overview
JavaScript is a dynamically typed language, meaning variables can hold values of any type and the type of a variable can change at runtime. However, there are ways to perform type checking and casting when necessary.
# VSC Interface Overview
typeof
operator returns the type of a value as a string.Type checking is the process of determining the type of a value or variable.
console.log(typeof 42); // Output: "number"
console.log(typeof "hello"); // Output: "string"
console.log(typeof true); // Output: "boolean"
console.log(typeof undefined); // Output: "undefined"
console.log(typeof null); // Output: "object" (quirk in JavaScript)
console.log(typeof {}); // Output: "object"
console.log(typeof []); // Output: "object"
console.log(typeof function(){});// Output: "function"
# VSC Interface Overview
console.log(Array.isArray([1, 2, 3])); // Output: true
console.log(Array.isArray({})); // Output: false
let value = {};
console.log(value && typeof value === "object" && !Array.isArray(value));
// Output: true for objects, false for arrays and null
# VSC Interface Overview
console.log("5" + 2); // Output: "52" (string concatenation)
console.log("5" - 2); // Output: 3 (string converted to number)
console.log(true + 1); // Output: 2 (true converted to 1)
console.log(false + 1); // Output: 1 (false converted to 0)
Type casting (or type coercion) is the process of converting a value from one type to another.
# VSC Interface Overview
let num = 42;
console.log(String(num)); // Output: "42"
let arr = [1, 2, 3];
console.log(arr.toString()); // Output: "1,2,3"
# VSC Interface Overview
console.log(Number("42")); // Output: 42
console.log(Number("abc")); // Output: NaN
console.log(Number(true)); // Output: 1
console.log(Number(false)); // Output: 0
# VSC Interface Overview
console.log(parseInt("42px")); // Output: 42
console.log(parseFloat("3.14m")); // Output: 3.14
console.log(+"42"); // Output: 42
console.log(+true); // Output: 1
console.log(+"abc"); // Output: NaN
# VSC Interface Overview
console.log(Boolean(1)); // Output: true
console.log(Boolean(0)); // Output: false
console.log(Boolean("hello")); // Output: true
console.log(Boolean("")); // Output: false
console.log(Boolean(null)); // Output: false
console.log(Boolean(undefined)); // Output: false
# VSC Interface Overview
console.log(String(null)); // Output: "null"
console.log(Number(null)); // Output: 0
console.log(Boolean(null)); // Output: false
console.log(String(undefined)); // Output: "undefined"
console.log(Number(undefined)); // Output: NaN
console.log(Boolean(undefined));// Output: false
# VSC Interface Overview
let obj = { value: 42 };
console.log(Number(obj)); // Output: NaN (default behavior unless overridden)
let customObj = {
valueOf() {
return 42;
}
};
console.log(Number(customObj)); // Output: 42
# VSC Interface Overview
===
): Compares both value and type.==
): Converts types before comparing values.console.log(5 === "5"); // Output: false (strict equality)
console.log(5 == "5"); // Output: true (loose equality)
# VSC Interface Overview
typeof
for primitives: Easy and reliable for basic types.Array.isArray()
for arrays: Avoid ambiguity with objects.==
unless you want type coercion: Prefer ===
for clarity.# VSC Interface Overview
console.log("5" + 2); // Output: "52" (string concatenation)
console.log("5" - 2); // Output: 3 (string converted to number)
console.log(true + 1); // Output: 2 (true converted to 1)
console.log(false + 1); // Output: 1 (false converted to 0)
# What is the DOM ?
ES6, also known as ECMAScript 2015, introduced a plethora of new features to JavaScript, making the language more powerful and developer-friendly. It addressed common issues, streamlined syntax, and brought JavaScript closer to other modern programming languages.
# What is HTML?
# VSC Interface Overview
let age = 25; // Can be updated
const PI = 3.14; // Cannot be re-assigned
// Block scope demonstration
if (true) {
let x = 10;
const y = 20;
console.log(x, y); // Works inside the block
}
// console.log(x, y); // Error: x and y are not defined outside the block
# VSC Interface Overview
const name = "Alice";
const age = 30;
const greeting = `Hello, my name is ${name} and I am ${age} years old.`;
console.log(greeting);
// Multi-line strings
const multiLine = `
This is a string
spanning multiple
lines.`;
console.log(multiLine);
Template literals allow embedding expressions and multi-line strings, using backticks (`) instead of quotes.
# VSC Interface Overview
condition ? expressionIfTrue : expressionIfFalse;
The ternary operator is a concise alternative to if-else statements.
Syntax
const age = 20;
const canVote = age >= 18 ? "Yes, you can vote." : "No, you cannot vote.";
console.log(canVote);
Exemple
# VSC Interface Overview
const add = (a, b) => a + b; // Implicit return
const greet = name => `Hello, ${name}!`; // Single argument doesn't need parentheses
const sayHi = () => console.log("Hi!"); // No arguments
Arrow functions provide a shorthand way to write functions.
Syntax
const numbers = [1, 2, 3];
const squared = numbers.map(num => num ** 2);
console.log(squared); // [1, 4, 9]
Exemple
# VSC Interface Overview
ES6 brought several new methods for array manipulation:
map
: Transforms each element.filter
: Filters elements based on a condition.reduce
: Reduces the array to a single value.find
: Returns the first element matching a condition.const numbers = [1, 2, 3, 4, 5];
const evens = numbers.filter(num => num % 2 === 0);
const squares = numbers.map(num => num ** 2);
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(evens); // [2, 4]
console.log(squares); // [1, 4, 9, 16, 25]
console.log(sum); // 15
# VSC Interface Overview
Destructuring is an ES6 feature that simplifies the process of extracting values from arrays or objects into distinct variables. It makes the code more concise and readable, especially when dealing with complex data structures.
# VSC Interface Overview
You can extract values from an array based on their positions.
const fruits = ["apple", "banana", "cherry"];
// Destructure into variables
const [first, second, third] = fruits;
console.log(first); // Output: "apple"
console.log(second); // Output: "banana"
console.log(third); // Output: "cherry"
Array Destructuring:
# VSC Interface Overview
You can skip unwanted elements by leaving placeholders.
const numbers = [10, 20, 30, 40];
const [, second, , fourth] = numbers;
console.log(second); // Output: 20
console.log(fourth); // Output: 40
Skipping Elements:
# VSC Interface Overview
Provide default values in case the array doesn’t have enough elements.
const colors = ["red"];
const [primary, secondary = "blue"] = colors;
console.log(primary); // Output: "red"
console.log(secondary); // Output: "blue"
Default Values:
# VSC Interface Overview
Destructuring can swap variable values without a temporary variable.
let a = 1;
let b = 2;
[a, b] = [b, a];
console.log(a); // Output: 2
console.log(b); // Output: 1
Swapping Variables:
# VSC Interface Overview
Extract properties from objects and assign them to variables.
const user = { name: "Alice", age: 25 };
// Destructure into variables
const { name, age } = user;
console.log(name); // Output: "Alice"
console.log(age); // Output: 25
Basics:
# VSC Interface Overview
You can rename variables while destructuring.
const user = { name: "Bob", age: 30 };
const { name: userName, age: userAge } = user;
console.log(userName); // Output: "Bob"
console.log(userAge); // Output: 30
Renaming Variables:
# VSC Interface Overview
Provide defaults for missing properties.
const product = { title: "Laptop" };
const { title, price = 1000 } = product;
console.log(title); // Output: "Laptop"
console.log(price); // Output: 1000
Default Values:
# VSC Interface Overview
Extract values from nested objects.
const user = {
name: "Charlie",
address: {
city: "New York",
zip: 10001
}
};
const { name, address: { city, zip } } = user;
console.log(name); // Output: "Charlie"
console.log(city); // Output: "New York"
console.log(zip); // Output: 10001
Nested Destructuring:
# VSC Interface Overview
Combine destructuring for arrays and objects.
const data = {
title: "Post Title",
tags: ["JavaScript", "ES6", "Coding"]
};
const { title, tags: [firstTag, secondTag] } = data;
console.log(title); // Output: "Post Title"
console.log(firstTag); // Output: "JavaScript"
console.log(secondTag); // Output: "ES6"
# VSC Interface Overview
Destructure directly in function parameters to make code concise.
const printUser = ({ name, age }) => {
console.log(`Name: ${name}, Age: ${age}`);
};
const user = { name: "Diana", age: 28 };
printUser(user);
// Output: Name: Diana, Age: 28
# VSC Interface Overview
With Default Values:
const greet = ({ name = "Guest", age = "unknown" }) => {
console.log(`Hello, ${name}. You are ${age} years old.`);
};
greet({ name: "Eve" });
// Output: Hello, Eve. You are unknown years old.
Provide defaults in function parameters.
# VSC Interface Overview
The spread
and rest
operators in ES6 use the same syntax: three dots (...
). However, their purpose and behavior are different.
# VSC Interface Overview
What It Does:
# VSC Interface Overview
1.1 Expanding Arrays:
const numbers = [1, 2, 3];
const newNumbers = [...numbers, 4, 5]; // Adds new elements
console.log(newNumbers); // Output: [1, 2, 3, 4, 5]
Use Cases:
1.2 Combining Arrays:
const arr1 = [1, 2];
const arr2 = [3, 4];
const combined = [...arr1, ...arr2];
console.log(combined); // Output: [1, 2, 3, 4]
# VSC Interface Overview
1.3 Copying Arrays (Immutable):
const original = [10, 20, 30];
const copy = [...original];
copy.push(40);
console.log(original); // Output: [10, 20, 30] (Unchanged)
console.log(copy); // Output: [10, 20, 30, 40]
Use Cases:
1.4 Expanding Objects:
const user = { name: "Alice", age: 30 };
const updatedUser = { ...user, location: "Paris" }; // Add a new property
console.log(updatedUser);
// Output: { name: "Alice", age: 30, location: "Paris" }
# VSC Interface Overview
1.5 Function Arguments:
const numbers = [5, 10, 15];
console.log(Math.max(...numbers)); // Output: 15
Use Cases:
# VSC Interface Overview
What It Does:
# VSC Interface Overview
2.1 Function Parameters:
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3, 4)); // Output: 10
Use Cases:
2.2 Collecting Remaining Array Items:
const [first, second, ...rest] = [10, 20, 30, 40, 50];
console.log(first); // Output: 10
console.log(second); // Output: 20
console.log(rest); // Output: [30, 40, 50]
# VSC Interface Overview
2.3 Collecting Remaining Object Properties:
const user = { name: "Alice", age: 30, location: "Paris" };
const { name, ...details } = user;
console.log(name); // Output: "Alice"
console.log(details); // Output: { age: 30, location: "Paris" }
Use Cases:
# VSC Interface Overview
const numbers = [1, 2, 3, 4, 5];
const [first, ...rest] = numbers; // Rest collects remaining items
console.log(first); // Output: 1
console.log(rest); // Output: [2, 3, 4, 5]
const newNumbers = [...rest, 6, 7]; // Spread expands elements
console.log(newNumbers); // Output: [2, 3, 4, 5, 6, 7]
Combining Both Operators:
# VSC Interface Overview
const user = { name: "Alice", age: 30, location: "Paris" };
const { location, ...personalDetails } = user; // Rest collects properties
console.log(personalDetails); // Output: { name: "Alice", age: 30 }
const updatedUser = { ...personalDetails, location: "London" }; // Spread expands properties
console.log(updatedUser); // Output: { name: "Alice", age: 30, location: "London" }
Mixing Objects:
Pro Tip: Use Spread for Expansion and Rest for Gathering