A Beginner's Guide 🎉
{Introduction to JavaScript}
3
Where Do We Use JS
5
operations
Summary
2
History of JavaScript
4
Variables & Constants
6
Conditions and loops
1
What is JS?
7
Arrays
8
And more....
# What is JS?
1. What is JavaScript ?
The Magic Behind Interactive Web Pages! 🌟
JavaScript is the magic that brings websites to life!
JavaScript is a high-level, interpreted programming language primarily used for creating dynamic, interactive web applications.
# What is JS?

# What is HTML?
What Can JavaScript Do?
- Manipulate HTML and CSS to create dynamic content.
- Validate forms before submission.
- Handle user inputs in real time.
- Build powerful backend systems (Node.js).
# Basic Structure
2. History of JavaScript
Once Upon a Time...
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!
The Name Game
- First, it was called Mocha (sounds fancy, right?).
- Then, it became LiveScript (a little bland…).
- Finally, a marketing genius thought:
“What if we ride the Java wave?” 💡
Thus, JavaScript was born — even though it has nothing to do with Java!
And since then, JavaScript has taken over the world
- Works on every browser — no exceptions!
- Powers 97% of websites, from Google to Netflix.
- Fun Fact: Without JavaScript, the internet would be static and boring!
🎥 Imagine Netflix with no autoplay previews or Gmail without real-time updates.
A Legacy That Lives On
From those humble beginnings, JavaScript grew into a powerhouse that developers (like you!) still use every day.
And the story continues…
# VSC Interface Overview
3. Where Do We Use JavaScript?
Front-End
- Adds interactivity to HTML and CSS.
- Used with frameworks like React and Vue.js for building interfaces.
1.
2.
Back-End
- Node.js enables building APIs and servers.
3.
Games
- Simple browser-based games or advanced ones with libraries like Phaser.js.
# CHAPTER 2
4.
Mobile Apps
- Frameworks like React Native allow creating native apps with JavaScript.
# CHAPTER 2
Client-Side
JavaScript: From Browsers to Servers
JavaScript originally ran in your browser, bringing interactivity to websites.
Examples:
- Dropdown menus 🖱️
- Real-time form validation ✅
- Dynamic content updates 📄
Server-Side
In 2009, Node.js changed the game:
JavaScript could now run on servers, powering backends and APIs.
Why It’s Big:
- Build entire apps using one language (front-end + back-end).
- Real-time applications like chats and live notifications are a breeze.
# Essential Extensions
4. Variables & Constants
# VSC Interface Overview
Declaring variables
var <var_name>;
- Syntax
// -Declarations
// var X
var name;
var anotherName;
var Name3;
var 4thName; // wrong declaration
var diffrent_name;
var §erfez; // wrong declaration
var $name;
var _name;
- Exemples
Variables are Containers for storing data that might change during the program’s exe.
Primitive Types
// 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
- Number
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
Primitive Types
var text = "message",
text2 = 'message2';
- String
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
Primitive Types
// bool
var conditionT = true;
var conditionF = false;
- Boolean
a Boolean is a logical data type that can have only the values true or false
# VSC Interface Overview
Primitive Types
var empty1= null;
- Null
Null expresses a lack of identification, indicating that a variable points to no object.
var x; //undefined
- undefined
A variable that has not been assigned a value is of type undefined.
# VSC Interface Overview
Declaring Constants
const <const_name> : <value>;
- Syntax
// 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*/
- Exemples
Constants are Fixed values that don’t change during the program’s execution.
# VSC Interface Overview
# Attributes
5. Simple manipulations and operations
Input / output Operation
const userInput = prompt("Enter a value :");
- Read a value from the user
console.log("You have entered :", userInput);
- Print a value on the console
# VSC Interface Overview
Practice:
- Ask the user for their name and display a welcome message in the console
Arithmetic operations
// 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
// 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
// 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
Exercice
# VSC Interface Overview
- Declare two variables and print their sum.
- Write a script to calculate the area of a rectangle. The user provides the length and width as input.
- Write a script to swap the values of 2 variables provided by the user.
- Ask for the user's name, age, favorite color, and hobby, then display all the info nicely formatted.
# Customize Your VSCode
6. Conditions
Making Decisions
// Conditions
if (/* condition1 */) {
/* Instractions 1 */
} else if (/* condition2 */) { // optional
/* Instractions 2 */
} else { // optional
/* Instractions 3 */
}
- Syntax
# VSC Interface Overview
- Example
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");
}
Making Decisions
// question mark operation (ternary)
let max = a>b ? a : b;
- Conditional (ternary) operator
// question mark operation (ternary)
( condition ) ? (true Result) : (false Result)
- Example
# VSC Interface Overview
Making Decisions
- Switch case
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
Making Decisions
- Switch case
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
7. Loops

// Syntaxe:
for (let <var_name> = min; <var_name> < max; <var_name>++) {
<instructions>
};
// Exemple :
for (let i = 0; i < n; i++) {
//instructions
};
- For Loop
Repeating Actions
# VSC Interface Overview
// loop 1
while (/* condition */) {
/* Instractions to repeat */
}
- While Loop
Repeating Actions
// loop 2
do{
/* Instractions to repeat */
} while (/* condition */) ;
- Do While Loop
# VSC Interface Overview

Practice
# VSC Interface Overview
Using JavaScript, write code to implement all the algorithms we discussed in the previous chapter.
- CheckEvenOrOdd (in two different ways)
- PrintOddNumbers (between an interval)
- MultiplicationTable
- Sum
- Factorial (use do while function)
- FindMaximum (of 2 numbers)
- MysteryNumberGame
# Customize Your VSCode
8. Arrays
Arrays
# 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];
- Indexed
Arrays are zero-indexed. The first element is at index 0.
- Dynamic
Arrays are dynamic and can grow or shrink dynamically.
- Heterogeneous
Arrays can store elements of different data types.
Characteristics
# 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:
Why using an Array ?!
# 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.
The solution is an array!
# VSC Interface Overview
var array_name = [item1, item2, ...];
Creating an array
Common Operations on Arrays
# VSC Interface Overview
It is a common practice to declare arrays with the const keyword.
- Using an array literal
var colors = ["red", "green", "orange"];
const strawhats = ["luffy", "zoro", "sanji", "nami", "tony tony chopper", "usopp", "robin", "franky", "brook", "jinbe"]
Creating an array
Common Operations on Arrays
# 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, …);
Creating an array
Common Operations on Arrays
# VSC Interface Overview
Example
- Using the Keyword new
var colors = new Array("red", "green", "orange");
Creating an array
Common Operations on Arrays
# 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
Length of an Array
Common Operations on Arrays
# VSC Interface Overview
Accessing Elements
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]
Modifying Elements
Common Operations on Arrays
# VSC Interface Overview
Adding and Removing Elements
Array Methods
# VSC Interface Overview
Example
- push: Add elements to the end.
- pop: Remove the last element.
- unshift: Add elements to the beginning.
- shift: Remove the first element.
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]
Iterating Over Arrays
Array Methods
# VSC Interface Overview
Example
- for loop
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.
Iterating Over Arrays
Array Methods
# VSC Interface Overview
Example
- for...of
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.
Iterating Over Arrays
Array Methods
# VSC Interface Overview
Example
- for...in
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.
Iterating Over Arrays
Array Methods
# VSC Interface Overview
Example
- forEach (Higher-order function)
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.
Searching in Arrays
Array Methods
# VSC Interface Overview
Example
- indexOf: Returns the index of the first occurrence of an element.
- lastIndexOf: Returns the index of the last occurrence.
- includes: Checks if an element exists.
const arr = [10, 20, 30, 20];
console.log(arr.indexOf(20)); // 1
console.log(arr.lastIndexOf(20)); // 3
console.log(arr.includes(30)); // true
Transforming Arrays
Array Methods
# VSC Interface Overview
Example
- map: Creates a new array by applying a function to each element.
- filter: Creates a new array with elements that pass a condition.
- reduce: Reduces the array to a single value.
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
Sorting and Reversing
Array Methods
# VSC Interface Overview
Example
- sort: Sorts the elements (alphabetically by default).
- reverse: Reverses the order of elements.
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]
Combining and Slicing
Array Methods
# VSC Interface Overview
Example
- concat: Combines two or more arrays.
- slice: Extracts a portion of an array.
- splice: Modifies an array by adding/removing elements. // 0 insert / 1 replacing / no 2nd elemt removing.
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]
Flattening Arrays
Array Methods
# VSC Interface Overview
Example
- flat: Flattens nested arrays.
const nested = [1, [2, [3, 4]]];
console.log(nested.flat(2)); // [1, 2, 3, 4]
Arrays Are Not Constants
Constant Arrays
# 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
Assigned When Declared
Constant Arrays
# 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
Using var
Constant Arrays
# 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]
Exo 1
Practice
# VSC Interface Overview
- Create a playlist with the following songs: "Blinding Lights", "Levitating", "Save Your Tears", "Flowers"
- Add a new song to the end.
- Remove the first song and display it as the one that was just played.
- Re-add "Flowers" to the beginning of the playlist.
- Loop through the playlist:
- Use for...of to Search for a Song.
- Use for...in to Find the Index of a Song
Exo 2
Practice
# VSC Interface Overview
You have the following inventory:
- Check if
"Minecraft"
is in stock usingincludes
. - Find the position of
"Zelda"
usingindexOf
. - Replace
"Call of Duty"
with"GTA V"
usingsplice
. - Add
"Among Us"
at a specific position.
const games = ["Zelda", "Minecraft", "Call of Duty"];
Exo 3
Practice
# VSC Interface Overview
The participants’ scores are:
- Create a new list with
map
, doubling each score. - Filter participants who scored at least 70 with
filter
. - Calculate the total score of all participants with
reduce
.
const scores = [55, 89, 72, 45, 100, 65];
Exo 4
Practice
# VSC Interface Overview
Your travel steps are:
- Combine this list with another list:
["fishmen island", "dressrosa"]
usingconcat
. - Use
slice
to create a new list with only"Alabasta"
and"Water 7"
. - Reverse the order of the steps with
reverse
. - Sort the steps alphabetically with
sort
.
const itinerary = ["Alabasta", "Water 7", "Red line"];
Exo 5
Practice
# VSC Interface Overview
Given the numbers:
- Sort the numbers in ascending order.
- Reverse the sorted array.
- Group numbers into nested pairs like this:
- Flatten the nested array back into a single array with flat.
const puzzle = [8, 4, 2, 10, 6];
[[8, 4], [2, 10], [6]];
# Customize Your VSCode
9. Functions

Functions
# 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.

- Encapsulate logic
Keep related operations grouped together.
- Reuse code
Call the same code block multiple times without rewriting it.
- Abstract complexity
Hide implementation details behind a simple interface.
Characteristics
# 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.
- Input: Coffee grounds and water (parameters).
- Process: Brewing (logic inside the function).
- Output: Fresh coffee (return value).
Real-World Analogy !
# 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:
Anatomy of a Function
# VSC Interface Overview
- Syntax of Function Declaration
- Function Name: Describes the purpose of the function (e.g., calculateArea) and must be unique within the program.
- Parameters: Placeholders for inputs the function will receive, it may or may not be present.
- Function Body: Contains the logic to execute.
- Return Statement: Specifies the value the function should output. Without return, the function returns undefined.
Key Components
# VSC Interface Overview
Calling a Function (Invoking)
# 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, ...);
- Parameters are placeholders; arguments are actual values provided when the function is called.
- A function must be called to execute.
function greet(name) {
console.log(`Hello, ${name}!`);
}
greet("Fatima"); // Output: Hello, Fatima!
Parameters and Arguments
# VSC Interface Overview
What Are Parameters?
- Parameters are placeholders defined in a function's declaration. They act as variables that receive values when the function is invoked.
- Think of parameters as inputs a function needs to perform its task.
function greet(name) {
console.log("Hello, " + name + "!");
}
Here, name is the parameter of the function greet.
Parameters and Arguments
# VSC Interface Overview
What Are Arguments?
- Arguments are the actual values you pass into a function when calling it.
- These values replace the parameters defined in the function.
greet("Fatima"); // Output: Hello, Fatima!
"Fatima" is the argument passed to the greet function. It replaces the name parameter during execution.
Parameters and Arguments
# VSC Interface Overview
Number of Parameters vs. Arguments
- The number of parameters does not need to match the number of arguments.
- If there are too few arguments, the missing parameters will be
undefined
. - If there are too many arguments, the extra arguments will be ignored unless you handle them explicitly.
function multiply(a, b) {
console.log(a * b);
}
multiply(5); // Output: NaN (b is undefined)
multiply(5, 2, 3); // Output: 10 (Extra argument ignored)
Parameters and Arguments
# 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!
Parameters and Arguments
# VSC Interface Overview
Passing Arguments by Value
- Primitive types (e.g., numbers, strings) are passed by value.
- Changing a parameter inside a function does not affect the original 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
Types of Functions in JavaScript
# VSC Interface Overview
Function Declarations
- Defined using the
function
keyword. - Hoisted to the top of their scope, meaning you can call them before they are defined.
console.log(square(4)); // Output: 16
function square(n) {
return n * n;
}
Types of Functions in JavaScript
# VSC Interface Overview
Function Expressions (Anonymous function)
- A function assigned to a variable.
- It’s called “anonymous function” because it doen’t have any name associated with it.
- Not hoisted, so you must define it before calling.
const multiply = function(a, b) {
return a * b;
};
console.log(multiply(2, 3)); // Output: 6
Types of Functions in JavaScript
# VSC Interface Overview
Arrow Functions (Lambda function, ES6)
- Arrow functions allow us to write shorter function syntax:
const functionName = (parameters) => expression;
const add = (a, b) => a + b;
console.log(add(5, 7)); // Output: 12
Scope in Functions
# VSC Interface Overview
Local Scope
- Variables declared inside a function are accessible only within that function.
function example() {
var localVar = "I'm local";
console.log(localVar); // Accessible
}
// console.log(localVar); // Error: localVar is not defined
Scope in Functions
# VSC Interface Overview
Global Scope
- Variables declared outside any function are accessible everywhere.
var globalVar = "I'm global";
function showGlobal() {
console.log(globalVar); // Accessible
}
showGlobal();
Scope in Functions
# VSC Interface Overview
Block Scope (ES6)
- Variables declared with let or const inside a block {} are not accessible outside.
if (true) {
var blockScoped = "I'm block-scoped";
console.log(blockScoped); // Accessible
}
// console.log(blockScoped); // Error: blockScoped is not defined
Practice
# VSC Interface Overview
- Write a function that returns the square of a number.
- Write a function that adds two numbers and returns the result.
- Write a function to convert a string to title case (first letter capitalized)
- Write a function that returns the longest word in a sentence
# Customize Your VSCode
10. Objects
Objects
# 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:
- Keys (properties): name, age, level.
- Values: "Kenza", 21, 4.
Real-World Analogy !
# VSC Interface Overview
Creating an Object
# VSC Interface Overview
- Object Literal Syntax
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}
Creating an Object
# VSC Interface Overview
- Using new Object()
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}
Accessing Object Properties
# VSC Interface Overview
- Dot Notation
The most common way to access properties.
- Bracket Notation
Useful when the property name is dynamic or contains special characters.
console.log(student.name); // Output: "Kenza"
console.log(student["age"]); // Output: 21
Accessing Object Properties
# VSC Interface Overview
- Dynamic Property Access
const key = "level";
console.log(student[key]); // Output: 4
Adding, Updating, and Deleting Properties
# VSC Interface Overview
- Adding Properties
student.school = "Dely brahim";
console.log(student);
- Updating Properties
student.level= 5;
console.log(student.level);
- Deleting Properties
delete student.age;
console.log(student);
Iterating Through an Object
# VSC Interface Overview
- for...in Loop
for (var key in student) {
console.log(`${key}: ${student[key]}`);
}
Used to iterate over an object’s enumerable properties.
- Object.keys()
console.log(Object.keys(student));
Returns an array of keys.
Iterating Through an Object
# VSC Interface Overview
- Object.values()
console.log(Object.values(student));
Returns an array of values.
- Object.entries()
console.log(Object.entries(student));
Returns an array of key-value pairs.
Nested Objects
# VSC Interface Overview
const student = {
name: "Fatima",
subjects: {
math: "A",
science: "B"
}
};
console.log(student.subjects.math);
Objects can contain other objects as values.
Object Methods
# 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
Exercise 1: Student Grade Analyzer
- You are building a tool that helps students track their grades across multiple subjects and calculate their average score.
- Create an objec called student with :
-
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 }.
-
- Add a method to calculate the average grade and print it.
# VSC Interface Overview
Exercise 2: Account Manager
- You're simulating a simple bank account system where users can deposit money, withdraw money, and check their balance safely.
- Create an account object with :
- balance (default 100).
-
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.
- Test your methods
- Deposit $50
- Try to withdraw $200 and display an error message
- Log the final balance
# VSC Interface Overview
Exercise 3: Account Manager
- You are creating a simple dictionary application that finds the capital city of a given country.
- Create a capitals object : Include at least 5 key-value pairs, e.g.:
- {
France: "Paris",
Germany: "Berlin"
} - Write the getCapital(country) function
- Use bracket notation to access the value
- If no match is found, return "Capital not found"
# VSC Interface Overview
Exercise 1: Create Your RPG Character
- Create an object named
character
to represent a hero in an RPG game. - The object should include the following properties:
-
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).
-
- Add the following functions:
-
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
Exercise 2: Build a Pokédex
- Create an object named
pokedex
. - Add at least three Pokémon, each represented as an object with the following properties:
-
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
Exercise 3: Anime Recommendation System
-
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
Exercise 4: Create Your Gaming Store
- Create an object named
store
to represent a game store. - The store should have the following properties:
-
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
Exercise 4: Create Your Gaming Store
- Write a function
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
Exercise 5: Create a Magic Guild Database
- Create an object
magicGuild
that represents a guild in a fantasy world. - Each member of the guild is an object with the following properties:
-
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
Exercise 5: Create a Magic Guild Database
-
Tasks:
Write a functionaddMember(member)
to add a new member to the guild. Write a functionpromoteMember(name)
that promotes a member to the next rank based on their missions completed. - Example promotion rule: If missionsCompleted > 50, rank to "S-Class".
Write a function displayMembersByMagicType(type)
to list all members with a specific magic type.
# VSC Interface Overview
Exercise 6:
- Create an object named
AnimeCollection
to represent an anime merchandise collection. - The collection should include:
-
figures
: An array of anime figure objects with propertiesname
,series
, andprice
. -
manga
: An array of manga objects with propertiestitle
,volume
, andprice
. -
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
11. Type checking & Casting
Type Checking and Casting
# 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.
Type Checking
# VSC Interface Overview
-
Using typeof
- The
typeof
operator returns the type of a value as a string. - It works for most primitive types but has limitations for objects.
- The
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"
Type Checking
# VSC Interface Overview
-
Checking Arrays
- Use Array.isArray() to check if a value is an array.
console.log(Array.isArray([1, 2, 3])); // Output: true
console.log(Array.isArray({})); // Output: false
-
Checking Objects
- To differentiate between objects, arrays, and null, you can use more specific checks.
let value = {};
console.log(value && typeof value === "object" && !Array.isArray(value));
// Output: true for objects, false for arrays and null
Type Casting
# VSC Interface Overview
-
Implicit Casting (Coercion)
- JavaScript automatically converts types in some operations, which can lead to unexpected results.
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.
-
Explicit Casting
- You can explicitly convert values between types using built-in methods.
Converting to String
# VSC Interface Overview
-
Using String()
- Converts any value to a string.
let num = 42;
console.log(String(num)); // Output: "42"
-
Using .toString()
- Works for numbers, strings, arrays, and objects, but not for null or undefined.
let arr = [1, 2, 3];
console.log(arr.toString()); // Output: "1,2,3"
Converting to Number
# VSC Interface Overview
-
Using Number()
- Converts strings, booleans, or other values to a number. Returns NaN if conversion fails.
console.log(Number("42")); // Output: 42
console.log(Number("abc")); // Output: NaN
console.log(Number(true)); // Output: 1
console.log(Number(false)); // Output: 0
Converting to Number
# VSC Interface Overview
-
Using parseInt() and parseFloat()
- These functions convert strings to integers or floating-point numbers, respectively. They stop parsing at the first invalid character.
console.log(parseInt("42px")); // Output: 42
console.log(parseFloat("3.14m")); // Output: 3.14
-
Unary + Operator
- Converts a value to a number.
console.log(+"42"); // Output: 42
console.log(+true); // Output: 1
console.log(+"abc"); // Output: NaN
Converting to Boolean
# VSC Interface Overview
-
Using Boolean()
- Converts values to true or false based on their truthiness.
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
Special Cases
# VSC Interface Overview
-
null and undefined
- null and undefined behave differently when cast.
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
Special Cases
# VSC Interface Overview
-
Objects to Primitives
- Objects are cast to primitives using valueOf() or toString().
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
Comparing Types
# VSC Interface Overview
-
Strict Equality (
===
): Compares both value and type. -
Loose Equality (
==
): Converts types before comparing values.
console.log(5 === "5"); // Output: false (strict equality)
console.log(5 == "5"); // Output: true (loose equality)
Type Checking Best Practices
# VSC Interface Overview
-
Use
typeof
for primitives: Easy and reliable for basic types. -
Use
Array.isArray()
for arrays: Avoid ambiguity with objects. -
Avoid
==
unless you want type coercion: Prefer===
for clarity.
Type Casting
# VSC Interface Overview
-
Implicit Casting (Coercion)
- JavaScript automatically converts types in some operations, which can lead to unexpected results.
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 ?
12. What is ECMAScript ?
ES6 (ECMAScript 2015)
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
Variable Declaration
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
- let: Used for block-scoped variables. Unlike var, it cannot be re-declared in the same scope.
- const: Declares constants. These cannot be re-assigned after initialization.
# VSC Interface Overview
Template Literals
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
Ternary Operator
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
Arrow Functions
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
Array Functions
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
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
1. Array Destructuring
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
1. Array Destructuring
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
1. Array Destructuring
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
1. Array Destructuring
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
2. Object Destructuring
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
2. Object Destructuring
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
2. Object Destructuring
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
2. Object Destructuring
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
3. Mixed Destructuring
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
4. Function Parameters Destructuring
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
4. Function Parameters Destructuring
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
Spread VS Rest Operator
The spread
and rest
operators in ES6 use the same syntax: three dots (...
). However, their purpose and behavior are different.
# VSC Interface Overview
1. The Spread Operator (...)
What It Does:
- The spread operator expands the elements of an array or object into individual elements.
- It’s used to copy or combine arrays and objects or pass array elements as arguments to a function.
# VSC Interface Overview
1. The Spread Operator (...)
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. The Spread Operator (...)
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. The Spread Operator (...)
1.5 Function Arguments:
const numbers = [5, 10, 15];
console.log(Math.max(...numbers)); // Output: 15
Use Cases:
# VSC Interface Overview
2. The Rest Operator (...)
- The rest operator collects the remaining elements of an array or object into a single variable.
- It’s used in function parameters to handle variable numbers of arguments or to gather properties into a new object.
What It Does:
# VSC Interface Overview
2. The Rest Operator (...)
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. The Rest Operator (...)
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
3. Examples Showing Both in Action
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
3. Examples Showing Both in Action
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:
- Think of spread as unpacking a suitcase (taking items out).
- Think of rest as packing a suitcase (gathering items in).
Pro Tip: Use Spread for Expansion and Rest for Gathering
JavaScript
Basics
ENDS
JS introduction
By Fatima BENAZZOU
JS introduction
- 255