A Beginner's Guide 🎉

{Introduction to JavaScrip}

1

What is JS?

3

Where Do We Use JS

5

operations

Summary

2

History of JavaScript

4

Variables & Constants

6

Conditions and loops

#  What is HTML?

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 HTML?
#  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 

The start of JS...

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!

Naming

  • 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!

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…

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.

# 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= "Youcef Madadi";
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

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 = "Youcef";
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
  1. Write a script to calculate the area of a rectangle. The user provides the length and width as input.
  2. Write a script to swap the values of 2 variables provided by the user.
  3. Write a script to calculate the price of a product.
# 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

Making Decisions

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");
}
  • Example
# VSC Interface Overview

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
  • 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 movieCharacters = [ "indiana jones", "james bond", "harry potter", "tony stark", "luke skywalker", "darth vader", "jack sparrow", "frodo baggins","neo","black panther"];

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];
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]

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); // [1,  4]  = > [2,3]

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]

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
  1. Create a playlist with the following songs: "Shape of You", "Blinding Lights", "Levitating".
    • Add a new song to the end.
    • Remove the last song and display its name.
    • Add a song to the beginning of the list.
    • Remove the first song and display its name.
  2. Loop through the playlist:
    • Display each title using for...of.
    • Display the indices and titles using for...in.
    • Display the titles with their positions (starting from 1) using forEach.

Exo 2

Practice

# VSC Interface Overview

You have the following inventory:

 

 

 

  1. Check if "Minecraft" is in stock using includes.
  2. Find the position of "Fortnite" using indexOf.
  3. Replace "Call of Duty" with "GTA V" using splice.
  4. Add "Among Us" at a specific position.
const games = ["Zelda", "Minecraft", "Call of Duty", "Fortnite"];

Exo 3

Practice

# VSC Interface Overview

The participants’ scores are:

 

 

 

  1. Create a new list with map, doubling each score.
  2. Filter participants who scored at least 70 with filter.
  3. 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:

 

 

 

  1. Combine this list with another list: ["fishmen island", "dressrosa"] using concat.
  2. Use slice to create a new list with only "Alabasta" and "Water 7".
  3. Reverse the order of the steps with reverse.
  4. Sort the steps alphabetically with sort.
const itinerary = ["Alabasta", "Water 7", "Red line"];

Exo 5

Practice

# VSC Interface Overview

Given the numbers:

 

 

  1. Sort the numbers in ascending order.
  2. Reverse the sorted array.
  3. Group numbers into nested pairs like this:

 

 

  1. Flatten the nested array back into a single array with flat.
const puzzle = [8, 4, 2, 10, 6];
[[8, 4], [2, 10], [6]];

9. Functions

  • # Functions

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
  • 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

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.

  • Input: Coffee grounds and water (parameters).
  • Process: Brewing (logic inside the function).
  • Output: Fresh coffee (return value).

Real-World Analogy !

  • # 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:

Anatomy of a Function

  • Syntax of Function Declaration
  • # Functions
  1. Function Name: Describes the purpose of the function (e.g., calculateArea) and must be unique within the program.
  2. Parameters: Placeholders for inputs the function will receive, it may or may not be present.
  3. Function Body: Contains the logic to execute.
  4. Return Statement: Specifies the value the function should output. Without return, the function returns undefined.

Key Components

  • # Functions

Calling a Function (Invoking)

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("Youcef"); // Output: Hello, Youcef!
  • # Functions

Parameters and Arguments

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.

  • # Functions

Parameters and Arguments

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("Youcef"); // Output: Hello, Youcef

"Fatima" is the argument passed to the greet function. It replaces the name parameter during execution.

  • # Functions

Parameters and Arguments

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)
  • # Functions

Parameters and Arguments

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

Parameters and Arguments

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

Types of Functions in JavaScript

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;
}
  • # Functions

Types of Functions in JavaScript

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

Types of Functions in JavaScript

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

Scope in Functions

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

Scope in Functions

Global Scope

  • Variables declared outside any function are accessible everywhere.
var globalVar = "I'm global";
function showGlobal() {
  console.log(globalVar); // Accessible
}
showGlobal();
  • # Functions

Scope in Functions

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
  • # Functions
# 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: "Raïd", 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: "Raïd",
  age: 21,
  level: 4
};
console.log(student); // Output: { name: 'Raïd', 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 = "Raïd";
student.age = 21;
student.level= 4;
console.log(student);  // Output: { name: 'Raïd', 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: "Raïd"
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 = "USTHB";
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: "Youcef",
  subjects: {
    math: "15",
    science: "8"
  }
};
console.log(student.subjects.math); 

Objects can contain other objects as values.

Object Methods

  • # 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

Exercise 1: Shopping List

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

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:
    1. levelUp(): Increase the level by 1 and health by 20.
    2. addItem(item): Add an item to the inventory.
    3. 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: Pet Care

You have a virtual pet! Take care of it by keeping track of its information and actions.

 

Create an object pet that has:

  • A property name (e.g., "Fluffy"). A property type (e.g., "Cat" or "Dog").
  • A property hungerLevel (e.g., 5, where 0 is full and 10 is very hungry).
  • A method feed() that decreases the hungerLevel by 1 and logs "Feeding [name]... Hunger level is now [hungerLevel]."
// Example:
const pet = {
  // Write your code here
};
pet.feed(); // Should print something like "Feeding Fluffy... Hunger level is now 4."
  • # 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 function addMember(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.
  • 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 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

12. 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.

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)

JavaScript

Basics

ENDS

JS introduction

By Youcef Madadi

JS introduction

  • 312