JAVASCRIPT
Building the Web That Connects the World bali abdelkouddous
UNIT 1: INTRODUCTION TO JAVASCRIPT
AND VARIABLES
LESSON 1: WHAT IS JAVASCRIPT?
DEVELOPER TOOLS AND VARIABLES
Concepts and detailed explanation
What is JavaScript and why do we learn it?
JavaScript is a programming language that runs within the browser (and later on the server via
[Link]) and gives web pages the ability to interact: respond to clicks, update content without
reloading the page, and communicate with servers. While HTML builds the structure and CSS
sets the appearance, JavaScript adds the behavior.
Developer Tools and the Console Panel
The Console Panel is the first debugging tool any JavaScript developer learns. It allows you to
execute code directly, print variable values during execution, and display errors with their details
(line and error message), which is what we will rely on throughout the course instead of
guesswork.
Variables: var vs. let vs. const
`var` was the only way to use `var` before ES6, but it operates within a function
scope and can cause surprises due to hoisting. `let` and `const` (since ES6)
operate within a block scope enclosed in `{}`. The rule of thumb: Use `const` by
default, switch to `let` only when you actually need to reset a value, and avoid
`var` altogether in modern code.
✍️ Exercise 1: Experimenting with the Console and Variable Types
1. Open any webpage and press F12 to open DevTools, then go to the Console tab.
2. Define a variable named studentName using `let` and assign it your name.
3. Define a constant named birthYear using `const` and assign it your birth year.
4. Print a greeting that combines the two variables using [Link].
5. Try resetting birthYear and observe the error message in the Console.
✍️ Exercise 2: From Old var to Modern let/const
1. Write an old-style function that uses var for a counter inside a for loop.
2. Rewrite it using let instead of var.
3. Explain in a comment the difference you noticed when printing i outside the loop.
BREAK
SLIDES
Let’s Take a Break 5 Minutes! bali abdelkouddous
UNIT 1: INTRODUCTION TO JAVASCRIPT
AND VARIABLES
LESSON 2: DATA TYPES, TYPE CONVERSION,
AND OPERATORS
Concepts and detailed explanation
Basic Data Types
JavaScript has primitive data types: Number for
numbers, String for text, Boolean for logical values,
Undefined for a declared variable that is not
assigned a value, and Null for an intentionally
empty value. Objects represent composite
structures (objects, arrays, and functions).
Type Conversion: == vs. ===
Type conversion occurs automatically when you
compare or combine values of different types. The
== operator (flexible equality) converts the types
first and then compares, while === (strict equality)
compares the value and type together without any
conversion. The golden rule in modern JavaScript:
Always use === to avoid implicit conversion
surprises.
Operators and True/False Values
Besides the well-known arithmetic operators, JavaScript provides % for the
remainder and ** for the exponent. The logical operators &&, ||, and ! are essential
in conditions. It is important to remember only the six pseudo-values (false, 0,
empty text, null, undefined, NaN)—any other value is treated as True, including the
empty array [] and the empty object {}!
✍️ Exercise 3: Testing == vs. ===
1. Write 5 different comparisons using == and then rewrite them using
===
2. For each comparison, write a comment explaining whether the result
changed or not and why.
✍️ Exercise 4: Sorting Values into True and False
1. Create an array containing: 0, 1, "", "a", null, undefined, [], {}, NaN
2. Iterate through the array with a for...of loop and print whether each
element is true or false.
BREAK
SLIDES
Let’s Take a Break 5 Minutes! bali abdelkouddous
UNIT 2: FLOW CONTROL AND FUNCTIONS
LESSON 3 : CONDITIONS AND LOOPS
Concepts and detailed explanation
The if/else and switch conditions
The if/else condition is used to branch between
different cases based on a logical condition. When
multiple cases are associated with a single value
(not ranges), the switch is more straightforward,
but remember to break the execution after each
case, otherwise it will continue to the next case
(fall-through).
The ternary operator
The ternary operator `condition ? valueIfTrue :
valueIfFalse` is a neat, one-line shortcut for if/else
when there are only two values to choose
between. It is frequently used later in React to
display conditional statements.
Loops: for, while, for...of, for...in
The for loop is suitable when the number of iterations is known beforehand, and
the while loop is used when continuation depends on a variable condition. The
for...of loop is used to iterate through the values of iterable structures (arrays,
strings), and the for...in loop is used to iterate through object keys.
✍️ Exercise 5: Grade Classifier
1. Write a function `gradeOf(score)` that returns 'Pass' if the score is 50 or
higher and 'Fail' otherwise.
2. Rewrite it using the `if/else` operator instead of `if/else`.
3. Test it on 3 different values and print the result.
✍️ Exercise 6: Printing Even Numbers Using `break/continue`
1. Use a `for` loop from 1 to 20.
2. Skip the odd numbers using `continue`.
3. Stop the loop completely (`break`) when the number reaches the first
even number greater than 10.
BREAK
SLIDES
Let’s Take a Break 5 Minutes! bali abdelkouddous
UNIT 2: FLOW CONTROL AND FUNCTIONS
LESSON 4: FUNCTIONS, RANGE, RAISING,
AND CLOSING
Concepts and detailed explanation
Function Definitions: `function` vs. `arrow` Function
A regular `function` is defined by a keyword and has its own
`this` attribute, which determines the callback time. An
arrow function is shorter in length and doesn't have its own
`this` attribute; instead, it inherits it from the surrounding
context. This is very useful for callback functions later on.
Scope and Hoisting
Hoisting is an internal JavaScript behavior that 'hoists' `var`
declarations and functions defined by `function` to the top
of the file before actual execution. However, with `var`, only
the declaration retains the value `undefined`, not the
assigned value. `let` and `const`, on the other hand, remain
in what's called the 'temporal dead zone' until their
definition line. Trying to use them before that line throws an
error—one reason why `let` and `const` are preferred, as
they prevent silent errors.
Closures
mean that an inner function retains a reference to the variables of an outer
function even after that outer function has finished executing. This allows for the
creation of 'private memory' for each instance of the function, which is the basis
of important patterns such as private counters and data encapsulation in
JavaScript.
✍️ Exercise 7: Converting a Regular Function to an Arrow Function
1. Write a regular function `multiply(a, b)` that returns the product.
2. Rewrite it in three different arrow formats: full, one-line condensed,
and with only one parameter.
✍️ Exercise 8: Building a Simple Bank Using Closure
1. Write a function `createBankAccount(initialBalance)` that returns an
object containing `deposit`, `withdraw`, and `getBalance`.
2. Ensure that `balance` is a special variable that cannot be accessed
directly from outside the function.
3. Try depositing and withdrawing an amount, then print the final
balance.
BREAK
SLIDES
Let’s Take a Break 5 Minutes! bali abdelkouddous
UNIT 3 ARRAYS AND OBJECTS
LESSON 5: MATRICES, THEIR METHODS,
DECOMPOSITION, AND DIFFUSION
Concepts and detailed explanation
Basic array methods: map, filter, reduce, find.
map creates a new array of the same length after applying
a function to each element. filter creates a new array
containing the elements that satisfy a condition. reduce
sums all elements to a single final value using a cumulative
function. find returns only the first element that satisfies the
condition (or undefined). forEach performs an action on
each element but returns nothing.
Destructuring:
Destructuring allows you to extract multiple values from an
array or object in a single line instead of accessing each
element individually. The extracted variable can also be
renamed and given a default value if the property doesn't
exist in the object.
Spread and Rest Operators
Spreading (...) when 'giving' (an array or a ready-made object) expands its
elements to copy or merge them without affecting the original. The same code
when 'receiving' (function parameters) is called Rest and combines an unlimited
number of values into a single array.
✍️ Exercise 9: Processing a Product List with map/filter/reduce
1. Create an array of product objects, each containing a name and price.
2. Use filter to display products with prices greater than 100.
3. Use map to create an array of names only.
4. Use reduce to calculate the total for all prices.
✍️ Exercise 10: Safely Merging User Profiles
1. Create a defaultSettings object containing a theme and language.
2. Create a userSettings object containing only the theme (chosen by the
user).
3. Merge the two objects using Spread so that the user's values override the
default.
BREAK
SLIDES
Let’s Take a Break 5 Minutes! bali abdelkouddous
UNIT 3 ARRAYS AND OBJECTS
LESSON 6: OBJECTS, THIS, AND JSON
Concepts and detailed explanation
Objects and Their Methods and `this`
An object can contain functions as properties, called
methods. Within these methods, `this` refers to the
object from which the method was called—this differs
from arrow functions, which do not inherit `this` from
the object but from the surrounding context.
Converting Text and JSON Objects
JSON (JavaScript Object Notation) is the most
common format for exchanging data between a
browser and a server. `[Link]()` converts a JS
object into JSON text (for example, for storage or
transmission over a network), while `[Link]()`
does the opposite: it converts JSON text into a ready-
to-use JS object.
Useful Text and Number Methods Everyday
Common text methods like trim, toLowerCase/toUpperCase, includes, and split
are used almost daily to clean and parse text coming from the user or the API.
ToFixed, for example, is used to adjust the number of decimal places when
displaying prices.
✍️ Exercise 11: Employee ID Card as an Object
1. Create an employee object containing name, salary, and a method to
raiseSalary(amount) to increase the salary.
2. Ensure that the method uses `this` to access and modify the current salary.
3. Try increasing the salary twice and print the final value.
✍️ Exercise 12: Simulating an API Response with JSON
1. Write a JSON string representing a user with id, name, and `isActive`.
2. Convert it to a JS object using `[Link]` within a `try/catch`
environment.
3. Modify the `isActive` property and then convert it back to JSON using
`[Link]`.
BREAK
SLIDES
Let’s Take a Break 5 Minutes! bali abdelkouddous
UNIT 4: DOM, EVENTS, AND ERROR
HANDLING
LESSON 7: SELECTING AND NAVIGATING
DOM ELEMENTS
Concepts and detailed explanation
Selecting Elements: querySelector and
querySelectorAll
`[Link]` returns the first element
that matches a specific CSS parameter (id, class, or
tag), while `querySelectorAll` returns a NodeList of all
matching elements, which can be iterated over using
`forEach`. After selecting an element, its `textContent`,
`innerHTML`, `style`, or `classList` can be read and
modified.
Dynamic Creation and Deletion of Elements
`[Link]` creates a new element in
memory (not yet visible), which is then added to the
page via `appendChild` or `prepend`. For deletion, the
modern `[Link]()` method is simpler than
the older `[Link](element)`
method.
DOM Traversal
Sometimes you don't know the direct CSS selector for the element you want, but
you know its relationship to another element you have a reference to. Traversal
properties (parentElement, children, nextElementSibling...) provide a way to
access those related elements, and `closest()` is very useful for finding the
nearest parent container that matches a specific condition.
✍️ Exercise 13: Building a Dynamic Shopping List
1. Create an empty `<ul id='shopping-list'></ul>` element in HTML.
2. In JS, create an array containing 4 shopping list items.
3. Use a loop and `createElement` to add each item as a `<li>` within
the list.
✍️ Exercise 14: Deleting an Item by Navigating from a Button Inside It
1. For each `<li>`, place a small button inside it with the text 'Delete'.
2. When the button is clicked, use `closest('li')` to find the full parent
item.
3. Delete the entire item using `remove()`.
BREAK
SLIDES
Let’s Take a Break 5 Minutes! bali abdelkouddous
UNIT 4: DOM, EVENTS, AND ERROR
HANDLING
LESSON 8: EVENTS, EVENT DELEGATION,
AND ERROR HANDLING
Concepts and detailed explanation
Basic Events and the Event
addEventListener object: This connects a handler
function to a specific event on an element (click,
submit, input, keydown, etc.). The event object is
automatically passed to the function and carries
important information such as target (the element
the event actually calls) and preventDefault() to
override the browser's default behavior when needed.
Event Delegation:
Instead of adding a separate listener for each child
element (which is costly and may not work with later-
added elements), you can add only one listener to
the parent element and check within the function
that [Link] is the actual target element using
matches(). This is event delegation, which is essential
for handling dynamic content.
Error handling: try/catch/finally and throw
try/catch catches errors that occur
during execution and prevents the
program from crashing. A custom error
can also be thrown manually with `throw
new Error('explanatory message')` when
an illogical situation is detected in the
business logic; this is a professional
technique for early validation of inputs
before proceeding.
✍️ Exercise 15: Delegable Task List
1. Create a list `<ul id='tasks'>` containing 4 `<li>` items
2. Add only one event listener to the `#tasks` (not to each `li`)
3. When any `li` is clicked, change its class to `done` (adds a line above the
text via CSS)
✍️ Exercise 16: Age-Safe Function with Error Handling
1. Write a function `registerUser(age)` that throws an error if the age is less
than 0 or greater than 120
2. Call it inside a `try/catch` for three different values (negative, logical, very
large)
3. Clearly print a success or error message for each case
BREAK
SLIDES
Let’s Take a Break 5 Minutes! bali abdelkouddous
UNIT 5 ASYNCHRONOUS PROGRAMMING
AND APIS
LESSON 9: THE PROBLEM OF CALLBACKS
AND PROMISES
Concepts and detailed explanation
The Problem of Callbacks (Callback Hell)
Before promises, asynchronous operations were
managed through nested callback functions. When
multiple operations depended on each other, the
code became a tangled pyramid, difficult to read
and trace errors—a phenomenon known as 'Callback
Hell'.
Promises and Their Three States
A promise is an object that represents the outcome
of an asynchronous operation that will be completed
later, in one of three states: pending, fulfilled
(completed successfully via resolve), or rejected
(failed via reject). .then() is used to handle success,
.catch() for failure, and .finally() to execute code that
always occurs regardless of the outcome.
[Link]() for executing multiple
promises in parallel
[Link]() takes an array of promises
and executes them in parallel, waiting for
all to complete before proceeding. If
even one promise fails, the entire
[Link] process immediately rejects it,
even if the rest succeed—a significant
difference from waiting for each promise
to be executed separately and
sequentially.
✍️ Exercise 17: Delegable Task List
1. Create a list `<ul id='tasks'>` containing 4 `<li>` items
2. Add only one event listener to the `#tasks` (not to each `li`)
3. When any `li` is clicked, change its class to `done` (adds a line above the
text via CSS)
✍️ Exercise 18: Age-Safe Function with Error Handling
1. Write a function `registerUser(age)` that throws an error if the age is less
than 0 or greater than 120
2. Call it inside a `try/catch` for three different values (negative, logical, very
large)
3. Clearly print a success or error message for each case
BREAK
SLIDES
Let’s Take a Break 5 Minutes! bali abdelkouddous
UNIT 5 ASYNCHRONOUS PROGRAMMING
AND APIS
LESSON 10: ASYNC/AWAIT, FETCH API, AND
REST
Concepts and detailed explanation
Clearer Syntax Above Promises: async/await
Async/await syntax is a newer and clearer syntax
above Promises that makes asynchronous code
appear synchronous to read. The `await` keyword is
used only within the `async` function, and `.catch()` is
replaced with a regular `try/catch` statement, making
error handling more like traditional synchronous
code.
REST Principles: GET, POST, PUT, DELETE Fetch API
Resting REST principles provide a standardized way to
communicate with servers via HTTP: GET to fetch data,
POST to add new data, PUT to update existing data
completely, and DELETE to delete it. The fetch() API
supports all these operations by passing the method,
headers, and body where needed, provided the
Content-Type is correctly specified.
Analyzing Network Errors Intelligently
It's important to distinguish between two
types of network errors: server response
errors (such as 404 or 500, where a
response arrives but displays a failure
status) and genuine connection errors
(such as an internet outage, where the
fetch itself throws a TypeError). Handling
each type differently provides the user
with a clearer and more helpful
message.
✍️ Exercise 19: Fetching User Data from a Real API
1. Use async/await to fetch data from
[Link]
2. Verify [Link] before converting the response to JSON
3. Print the names of only the first 5 users using slice and map
✍️ Exercise 20: Sending a New Task via POST
1. Write an async function addTask(title) that sends a POST request with a
valid JSON address
2. Verify the request's success using [Link] before marking it as successful
3. Print a clear success or error message depending on the outcome
BREAK
SLIDES
Let’s Take a Break 5 Minutes! bali abdelkouddous
UNIT 6 MODERN JAVASCRIPT AND STATE
MANAGEMENT
LESSON 11 : ES MODULES AND CLASSES
Concepts and detailed explanation
ES Modules: import and export
Modules allow you to split code into separate, reusable
files that can be tested independently. There are two
types of exports: default export (one default export per
file, imported without curly braces and with any name)
and named export (multiple named exports within the
same file, imported with the same name enclosed in
curly braces {}).
Classes and Inheritance
A class provides clearer syntax for creating objects and
iterating behavior through inheritance (extends), but it
still relies on JavaScript's native prototype system. The
constructor contains the initial configuration logic, while
the `super()` function in a child class allows you to call
the parent class's constructor before adding new
properties specific to the child class.
✍️ Exercise 21: Splitting Utilities into a Separate Unit
1. Create a [Link] file that exports two functions named formatPrice and
slugify.
2. Import them into a [Link] file and use each one on an example.
3. Also, add a default export for the store name constant and import it
without brackets.
✍️ Exercise 22: Geometric Shape Inheritance System
1. Create a base class, Shape, with a constructor(name) and a describe()
method.
2. Create a child class, Circle, that inherits from Shape and adds a radius
and an area() method.
3. Create an instance of Circle and call both methods.
BREAK
SLIDES
Let’s Take a Break 5 Minutes! bali abdelkouddous
UNIT 6 MODERN JAVASCRIPT AND STATE
MANAGEMENT
LESSON 12: MAP, SET, OPTIONAL CHAINING,
AND SAVING STATE
Concepts and detailed explanation
Map and Set
Set automatically stores unique values without
duplication, a direct solution to a common problem:
'How do we remove duplicates from an array?'. Map, on
the other hand, stores key-value pairs while preserving
input order and supports any data type as a key (unlike
a regular object, which always converts keys to strings).
Optional Safe Binding (?) and Null Value Merging (??)
Optional safe binding prevents errors when trying to
access a property within an object that might be null or
undefined, returning undefined instead of throwing an
error. The null value merge operator returns only the
right-hand value if the left-hand value is specifically
null or undefined (unlike ||, which replaces any false
value such as 0 or empty strings—a very important
distinction).
State storage: localStorage and sessionStorage
localStorage allows you to store data in the browser that remains even
after you close it, while sessionStorage data is erased when you close the
tab. Both store data only as strings, so you should use [Link]()
when saving and [Link]() when retrieving to store objects or arrays,
with a default value on the first read.
✍️ Exercise 23: Safely Read Nested User Data
1. Create an apiResponse object that may not contain an address field at all.
2. Read [Link] using a question mark (?) to avoid any
errors.
3. Use a question mark (?) to display 'Undefined' if the city does not exist.
✍️ Exercise 24: Saving and Restoring User Preferences
1. Write a saveTheme(theme) function to store the value in localStorage.
2. Write a loadTheme() function to retrieve it with a default value of 'light' if it
is not saved.
3. Try saving with 'dark' and then retrieving to ensure the process works.
BREAK
SLIDES
Let’s Take a Break 5 Minutes! bali abdelkouddous
THE FINAL PROJECT IS SMART TASK
MANAGER.
Concepts and detailed explanation
1) Basic Structure and Class Design
📌 Requirements:
Create a Task class with: id (unique), title, priority, isDone, and createdAt.
Create a TaskManager class containing an internal tasks array and methods: addTask,
deleteTask, toggleTask, and getStats.
Use Spread or map/filter within the TaskManager to avoid directly modifying the original array
where possible.
2) DOM Interface and Event Delegation
📌 Requirements:
Task Add Form: Title field + Priority list (Low/Medium/High) + Add button.
Dynamicly display tasks via createElement without any manually typed static HTML for each task.
Use Event Delegation on the parent container to handle 'Complete' and 'Delete' buttons for each
task.
Add a visually distinct CSS class (e.g., strikethrough) for completed tasks via classList.
3) Local Storage (localStorage)
📌 Requirements:
Automatically save the entire task list to localStorage after each addition, deletion, or status
change.
Automatically retrieve saved tasks upon page relaunch (don't start from an empty list each
time).
Use [Link] and [Link] correctly, with default values on first execution.
4) True Asynchronous Element (Bonus required for full credit)
📌 Requirements:
When adding a 'high' priority task, call (virtually or via a public API) a daily weather or quote
check service with async/await as an additional task alert.
Display a clear 'Loading' indicator while awaiting a response, and handle request failures
with a polite error message interface instead of a page crash.
5) Statistics and Matrix Filtering
📌 Requirements:
Display live statistics: total, completed, and
remaining tasks (using filters and reduce).
Add filter buttons: All / Completed Only /
Incomplete Only, without page reloading.
THANKYOU
Let’s Take a Break 5 Minutes! bali abdelkouddous