Youcef Madadi
Web and game development teacher
A Beginner's Guide 🎉
What is JS?
Where Do We Use JS
operations
History of JavaScript
Variables & Constants
Conditions and loops
# What is HTML?
The Magic Behind Interactive Web Pages! 🌟
JavaScript is a high-level, interpreted programming language primarily used for creating dynamic, interactive web applications.
# What is HTML?
# 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!
From those humble beginnings, JavaScript grew into a powerhouse that developers (like you!) still use every day.
🎥 Imagine Netflix with no autoplay previews or Gmail without real-time updates.
# 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); // trueNumbers 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; //undefinedA variable that has not been assigned a value is of type undefined.
# VSC Interface Overview
const <const_name> : <value>;// Constants
const Trainer= "Youcef Madadi";
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
// 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 = "Youcef";
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");
}# VSC Interface Overview
// 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 movieCharacters = [ "indiana jones", "james bond", "harry potter", "tony stark", "luke skywalker", "darth vader", "jack sparrow", "frodo baggins","neo","black panther"];
# 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 arrayYou 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: 30Best 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];
const sorted = arr.sort(); // [1, 1, 3, 4, 5]
sorted.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); // [1,  4]  = > [2,3]# 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
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
"Shape of You", "Blinding Lights", "Levitating".
	for...of.for...in.forEach.# VSC Interface Overview
You have the following inventory:
"Minecraft" is in stock using includes."Fortnite" using indexOf."Call of Duty" with "GTA V" using splice."Among Us" at a specific position.const games = ["Zelda", "Minecraft", "Call of Duty", "Fortnite"];# 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]];# Functions
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.
# Functions
Keep related operations grouped together.
Call the same code block multiple times without rewriting it.
Hide implementation details behind a simple interface.
Functions are executed when "something" invokes it (calls it).The functions generally are used to eliminate code complexity by enabling re-usability.
# Functions
Think of a function as a coffee machine.
# Functions
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:
# Functions
# Functions
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("Youcef"); // Output: Hello, Youcef!# Functions
What Are Parameters?
function greet(name) {
    console.log("Hello, " + name + "!");
}Here, name is the parameter of the function greet.
# Functions
What Are Arguments?
greet("Youcef"); // Output: Hello, Youcef"Fatima" is the argument passed to the greet function. It replaces the name parameter during execution.
# Functions
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)# Functions
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!# Functions
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# Functions
Function Declarations
function keyword.console.log(square(4)); // Output: 16
function square(n) {
  return n * n;
}# Functions
Function Expressions (Anonymous function)
const multiply = function(a, b) {
  return a * b;
};
console.log(multiply(2, 3)); // Output: 6# Functions
Arrow Functions (Lambda function, ES6)
const functionName = (parameters) => expression;const add = (a, b) => a + b;
console.log(add(5, 7)); // Output: 12# Functions
Local Scope
function example() {
  var localVar = "I'm local";
  console.log(localVar); // Accessible
}
// console.log(localVar); // Error: localVar is not defined# Functions
Global Scope
var globalVar = "I'm global";
function showGlobal() {
  console.log(globalVar); // Accessible
}
showGlobal();# Functions
Block Scope (ES6)
if (true) {
  var blockScoped = "I'm block-scoped";
  console.log(blockScoped); // Accessible
}
// console.log(blockScoped); // Error: blockScoped is not defined# Functions
# 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: "Raïd",
  age: 21,
  level: 4
};
console.log(student); // Output: { name: 'Raïd', age: 21, level: 4}# VSC Interface Overview
Less common and used in specific scenarios.
const student = new Object();
student.name = "Raïd";
student.age = 21;
student.level= 4;
console.log(student);  // Output: { name: 'Raïd', 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: "Raïd"console.log(student["age"]); // Output: 21# VSC Interface Overview
const key = "level";
console.log(student[key]); // Output: 4# VSC Interface Overview
student.school = "USTHB";
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: "Youcef",
  subjects: {
    math: "15",
    science: "8"
  }
};
console.log(student.subjects.math); Objects can contain other objects as values.
# VSC Interface Overview
const student = {
  name: "Raïd",
  greet: function(name) {
    console.log(`Hello, my name is ${name}.`);
  }
};
student.greet("Raïd"); // Output: Hello, my name is Raïd.Objects can have functions as properties, called methods.
# VSC Interface Overview
Create an object shoppingList that has:
A property items which is an array of objects, where each object has a name (e.g., "Chips") and quantity (e.g., 5).
A method addItem(itemName, quantity) that adds a new item to the items array.
A method printList() that logs "Shopping List: [Item1: quantity1, Item2: quantity2, ...]" to the console.
// Example:
const shoppingList = {
  // Write your code here
};
shoppingList.addItem("Soda", 3);
shoppingList.printList(); // Should print something like "Shopping List: Chips: 5, Soda: 3"# 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
You have a virtual pet! Take care of it by keeping track of its information and actions.
Create an object pet that has:
// Example:
const pet = {
  // Write your code here
};
pet.feed(); // Should print something like "Feeding Fluffy... Hunger level is now 4."# 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: falselet 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.14console.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)By Youcef Madadi