Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 63

javascript course 2024

By AI ChatGPT

MAY 3, 2024
gazania production .Lcc
Iraq, Karbala
JavaScript 2024 Course
By AI

1
Content
Revised Course Plan
Chapter 1: Basics
1. Variables: var, let, const
2. Data Types: Numbers, Strings, Booleans, Objects, Arrays
3. Control Structures: if, switch, for, while
4. Functions: Function Declarations, Expressions, Arrow Functions
Chapter 2: Working with Arrays
1. Array Methods: map(), filter(), reduce(), forEach(), some(), every(), find(),
findIndex(), includes(), indexOf(), join()
2. Array Manipulation: push(), pop(), shift(), unshift(), slice(), splice(), concat(), flat(),
flatMap()
Chapter 3: Working with Objects
1. Object Methods: Object.keys(), Object.values(), Object.entries(), Object.assign()
2. Destructuring: Array Destructuring, Object Destructuring
Chapter 4: Strings and Template Literals
1. String Methods: charAt(), includes(), indexOf(), slice(), split(), toLowerCase(),
toUpperCase(), trim()
2. Template Literals: Embedding Expressions, Multiline Strings, Tagged Templates
Chapter 5: Advanced Functions
1. Closures: How Closures Work, Use Cases
2. Callbacks: Synchronous and Asynchronous Callbacks
3. Promises: Creating Promises, Consuming Promises (then, catch, finally)
4. Async/Await: Asynchronous Functions, Error Handling
Chapter 6: Classes and OOP
1. Classes: Constructors, Methods, Inheritance
2. Object-Oriented Programming: Encapsulation, Polymorphism, Inheritance, Abstraction
Chapter 7: Working with Time

2
1. Timers: setTimeout(), setInterval(), clearTimeout(), clearInterval()
Chapter 8: ES6 and Beyond
1. New Features: let, const, Arrow Functions, Destructuring, Template Literals, Spread and
Rest Operators
2. Modules: Importing, Exporting, Default Exports, Named Exports

Beginner Level
1. Introduction to JavaScript
 What is JavaScript?
 Setting up your development environment
 Basic syntax and statements
2. Variables and Data Types
 Understanding variables and constants
 Different data types in JavaScript
3. Operators
 Arithmetic operators
 Comparison operators
 Logical operators
4. Control Structures
 Conditional statements (if, else, switch)
 Loops (for, while, do-while)
5. Functions
 Defining and invoking functions
 Function parameters and return values

3
 Scope and closures
Intermediate Level
6. Arrays and Objects
 Working with arrays
 Manipulating objects
 JSON data
7. ES6 and Beyond
 Let and const
 Arrow functions
 Template literals
 Destructuring
 Default parameters
 Spread and rest operators
8. Asynchronous JavaScript
 Callbacks
 Promises
 Async/await
9. DOM Manipulation
 Selecting elements
 Changing element properties
 Event handling
10. Form Validation and Manipulation
 Handling form inputs
 Basic client-side validation
Advanced Level
11. Advanced Functions
 Higher-order functions

4
 Callbacks and closures
12. Modules and Namespaces
 Organizing code
 Module patterns
 ES6 modules
13. Web APIs and HTTP Requests
 Fetch API
 AJAX
 Working with external APIs
14. Error Handling and Debugging
 Try, catch, finally
 Throwing errors
 Debugging techniques
15. Tools and Frameworks
 Introduction to Node.js
 Overview of front-end frameworks (React, Angular, Vue)
 Build tools (Webpack, Babel)
Project Phase
16. Capstone Projects
 Applying everything you've learned
 Building small to medium-sized projects
 Version control with Git
17. Code Reviews and Best Practices
 Writing clean code
 Performance optimization
 Security practices

5
Beginner Level
1. Introduction to JavaScript
 What is JavaScript?
 Setting up your development environment
 Basic syntax and statements
2. Variables and Data Types
 Understanding variables and constants
 Different data types in JavaScript
3. Operators
 Arithmetic operators
 Comparison operators
 Logical operators
4. Control Structures
 Conditional statements (if, else, switch)
 Loops (for, while, do-while)
5. Functions
 Defining and invoking functions
 Function parameters and return values
 Scope and closures

1# Introduction to JavaScript.
Objectives:
 Understand what JavaScript is and its role in web development.
 Learn about the history of JavaScript and how it has evolved.
 Set up a simple development environment for practicing JavaScript.
Activities:
 We will discuss the history and significance of JavaScript.

6
 I will guide you on installing a code editor if you haven’t already, and how to configure it
for JavaScript development.
 You will learn how to write and run your first JavaScript script directly in your browser.
Practical Exercise:
 Write and execute a "Hello, World!" script to see JavaScript in action.

Objectives:
 Understand what JavaScript is and its role in web development.
 Learn about the history of JavaScript and how it has evolved.
 Set up a simple development environment for practicing JavaScript.
Part 1: What is JavaScript?
JavaScript is a programming language that allows you to create dynamically updating content,
control multimedia, animate images, and pretty much everything else. (Okay, maybe not
everything, but it is amazing what you can achieve with a few lines of JavaScript code.)
Part 2: History of JavaScript
JavaScript was created in 1995 by Brendan Eich while he was an engineer at Netscape.
Originally developed under the name Mocha, it was later renamed to LiveScript, and finally to
JavaScript. JavaScript has become one of the most popular programming languages in the world,
largely due to its ability to enable interactive web experiences.
Part 3: Setting Up Your Development Environment
To write and run JavaScript code, you can use any text editor (like Notepad++, Sublime Text, or
Visual Studio Code) and a web browser (like Chrome, Firefox, or Edge).
Activity:
1. Install a Code Editor: If you haven't already, download and install Visual Studio Code
from https://code.visualstudio.com/. It's a popular editor for web development.
2. Write Your First JavaScript Code:
 Open Visual Studio Code.
 Create a new file and save it as hello.js.
 Write the following JavaScript code:
console.log('Hello, World!');

7
 Save the file.
3. Run Your JavaScript Code:
 Open your web browser.
 Press Ctrl+Shift+I (or Cmd+Option+I on Mac) to open Developer Tools.
 Click on the "Console" tab.
 Drag and drop your hello.js file into the console, or type node hello.js in the
terminal if you have Node.js installed.

8
2# Variables and Data Types.
Objectives:
 Understand the concept of variables and how they are used in JavaScript.
 Learn about different data types in JavaScript.
Part 1: Variables
Variables are like containers that store data values. In JavaScript, you can declare a variable
using var, let, or const.
 var: Declares a variable, optionally initializing it to a value.
 let: Declares a block-scoped, local variable, optionally initializing it to a value.
 const: Declares a block-scoped, read-only named constant.
Example:
var name = 'Ahmed'; // String
let age = 25; // Number
const isStudent = true; // Boolean
Part 2: Data Types
JavaScript variables can hold many data types: numbers, strings, objects, and more.
 String: Represents textual data. It's surrounded by quotes.
 Number: Represents both integer and floating-point numbers.
 Boolean: Represents a logical entity and can have two values: true and false.
 Null: Represents the intentional absence of any object value.
 Undefined: Indicates that a variable has not been assigned a value.
 Object: Used to store collections of data and more complex entities.
Example:
var message = "Hello, world!"; // String
var examScore = 88.5; // Number
var isPassed = true; // Boolean
var object = null; // Null

9
var description; // Undefined
Activity:
1. Experiment with Variables:
 Create a new JavaScript file or use the same hello.js.
 Try declaring different types of variables with the data types mentioned.
 Print these variables using console.log() to see the output in the console.
For example:
console.log(message);
console.log(examScore);
console.log(isPassed);

10
3# Operators
Objectives:
 Understand and use different operators in JavaScript.
 Practice using arithmetic, comparison, and logical operators.
Part 1: Arithmetic Operators
Arithmetic operators are used to perform mathematical operations.
 Addition (+): Adds two numbers.
 Subtraction (-): Subtracts one number from another.
 Multiplication (*): Multiplies two numbers.
 Division (/): Divides one number by another.
 Modulus (%): Returns the remainder of a division.
 Exponentiation (**): Raises a base to the power of an exponent.
Example:
let a = 10;
let b = 3;
console.log(a + b); // 13
console.log(a - b); // 7
console.log(a * b); // 30
console.log(a / b); // 3.333...
console.log(a % b); // 1
console.log(a ** b); // 1000
Part 2: Comparison Operators
Comparison operators compare two values and return a Boolean value (true or false).
 Equal (==): Checks if two values are equal.
 Strict Equal (===): Checks if two values and types are equal.
 Not Equal (!=): Checks if two values are not equal.
 Strict Not Equal (!==): Checks if two values or types are not equal.

11
 Greater Than (>): Checks if a value is greater than another.
 Greater Than or Equal (>=): Checks if a value is greater than or equal to another.
 Less Than (<): Checks if a value is less than another.
 Less Than or Equal (<=): Checks if a value is less than or equal to another.
Example:
let x = 5;
let y = "5";
console.log(x == y); // true
console.log(x === y); // false
console.log(x != y); // false
console.log(x !== y); // true
console.log(x > 4); // true
console.log(x <= 5); // true
Part 3: Logical Operators
Logical operators are used to combine conditional statements.
 AND (&&): Returns true if both conditions are true.
 OR (||): Returns true if at least one condition is true.
 NOT (!): Returns the opposite of the given condition.
Example:
let a = true;
let b = false;
console.log(a && b); // false
console.log(a || b); // true
console.log(!a); // false

Activity:
1. Experiment with Operators:

12
 Create a new JavaScript file or continue using the same one.
 Write examples for each type of operator and print the results using console.log().
For example:
let num1 = 12;
let num2 = 4;
console.log(num1 + num2); // 16

let isSunny = true;


let isWeekend = false;
console.log(isSunny && isWeekend); // false

13
4# Control Structures
Objectives:
 Understand and use conditional statements.
 Explore different types of loops in JavaScript.
Part 1: Conditional Statements
If Statement
 The if statement executes a block of code if a specified condition is true.
let age = 18;
if (age >= 18) {
console.log("You are an adult.");
}
If-Else Statement
 The if-else statement provides an alternative action if the condition is false.
let age = 17;
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}
Else If Statement
 The else if statement allows multiple conditions to be tested.
let age = 16;
if (age >= 18) {
console.log("You are an adult.");
} else if (age >= 13) {
console.log("You are a teenager.");
} else {

14
console.log("You are a child.");
}
Switch Statement
 The switch statement tests a variable against multiple possible values.
let fruit = "apple";
switch (fruit) {
case "banana":
console.log("This is a banana.");
break;
case "apple":
console.log("This is an apple.");
break;
default:
console.log("Unknown fruit.");
}
Part 2: Loops
For Loop
 The for loop repeats a block of code a specific number of times.
for (let i = 0; i < 5; i++) {
console.log("Iteration: " + i);
}
While Loop
 The while loop executes a block of code as long as a specified condition is true.
let count = 0;
while (count < 5) {
console.log("Count: " + count);
count++;

15
}
Do-While Loop
 The do-while loop executes a block of code at least once, and then repeats the loop as
long as a specified condition is true.
let num = 0;
do {
console.log("Number: " + num);
num++;
} while (num < 5);
Activity:
1. Experiment with Control Structures:
 Write examples for each type of control structure.
 Test different conditions and see how the code behaves.
For example:
for (let i = 1; i <= 10; i++) {
if (i % 2 === 0) {
console.log(i + " is even.");
} else {
console.log(i + " is odd.");
}
}

16
5# Functions
Objectives:
 Understand the concept of functions and their role in JavaScript.
 Learn how to define and invoke functions.
 Explore function parameters, return values, and scope.
Part 1: What is a Function?
A function is a reusable block of code designed to perform a specific task. Functions allow you
to write modular code, improving readability and maintainability.
Part 2: Defining and Invoking Functions
Function Declaration:
 Functions can be declared using the function keyword.
 The function name is followed by parentheses, which may include parameters.
function greet() {
console.log("Hello, world!");
}
greet(); // Invokes the function
Function Expression:
 Functions can also be defined using expressions.
 These functions can be anonymous or named.
const greet = function() {
console.log("Hello, world!");
};
greet(); // Invokes the function
Arrow Function:
 Arrow functions provide a shorter syntax.
 They are commonly used for concise one-liner functions.
const greet = () => console.log("Hello, world!");

17
greet(); // Invokes the function
Part 3: Function Parameters and Return Values
Parameters:
 Functions can take parameters, allowing data to be passed in.
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Alice"); // Outputs: Hello, Alice!
Return Values:
 Functions can return a value using the return keyword.
function add(a, b) {
return a + b;
}
console.log(add(5, 3)); // Outputs: 8
Part 4: Function Scope
Scope determines the visibility of variables. Functions create their own scope, meaning variables
defined inside a function are not accessible outside it.
function testScope() {
let message = "Inside function";
console.log(message); // Outputs: Inside function
}
testScope();
// console.log(message); // Error: message is not defined
Activity:
1. Define and Invoke Functions:
 Write functions using each of the types of declarations (function declaration,
function expression, and arrow function).
 Experiment with different parameters and return values.

18
2. Explore Function Scope:
 Write functions that demonstrate different scopes.
 Test what happens when you try to access variables inside and outside functions.

1. Function Declarations:
 Syntax:
function greet(name) { return `Hello, ${name}!`; }
 Description:
 Functions are reusable blocks of code.
 Function declarations are hoisted, meaning they can be called before they
are defined in the code.
 Example:
console.log(greet("Alice")); // Outputs: "Hello, Alice!" function greet(name) { return `Hello, $
{name}!`; }
2. Function Expressions:
 Syntax:
const greet = function(name) { return `Hello, ${name}!`; }
 Description:
 Function expressions are not hoisted.
 They are often used to create anonymous functions or assign functions to
variables.
 Example:
const add = function(a, b) { return a + b; } console.log(add(2, 3)); // Outputs: 5
3. Arrow Functions:
 Syntax:
const greet = (name) => `Hello, ${name}!`;
 Description:
 Arrow functions provide a concise syntax.

19
 They inherit the this value from their enclosing context.
 Example:
const multiply = (a, b) => a * b; console.log(multiply(2, 3)); // Outputs: 6
4. Using Functions:
 Parameters:
 Functions can accept parameters to work with.
 Return Values:
 Functions can return a value.
 Default Parameters:
 Functions can have default parameter values.
 Example:
function greet(name = "Guest") { return `Hello, ${name}!`; } console.log(greet()); // Outputs:
"Hello, Guest!" console.log(greet("Alice")); // Outputs: "Hello, Alice!"
Practice
1. Task: Write a function sum that takes two numbers as arguments and returns their sum.
Answer:
function sum(a, b) { return a + b; } console.log(sum(2, 3)); // Outputs: 5
2. Task: Write a function factorial that calculates the factorial of a number using recursion.
Answer:
function factorial(n) { if (n === 0) { return 1; } else { return n * factorial(n - 1); } }
console.log(factorial(5)); // Outputs: 120
3. Task: Write an arrow function square that returns the square of a number.
Answer:
const square = (x) => x * x; console.log(square(4)); // Outputs: 16

20
6# Arrays and Objects
Objectives:
 Understand arrays and their methods.
 Work with objects and manipulate their properties.
 Practice using arrays and objects to store and manage data.
Part 1: Arrays
Array Basics:
 An array is a special type of object used to store multiple values in a single variable.
let fruits = ["apple", "banana", "mango"];
console.log(fruits[0]); // Outputs: apple
Array Methods:
 JavaScript provides many methods to manipulate arrays, including push, pop, shift,
unshift, slice, splice, concat, and more.

push()
 Purpose: Adds one or more elements to the end of an array.
 Example:
let fruits = ["apple", "banana"];
fruits.push("mango");
console.log(fruits); // ["apple", "banana", "mango"]
pop()
 Purpose: Removes the last element of an array and returns that element.
 Example:
let fruits = ["apple", "banana", "mango"];
let lastFruit = fruits.pop();
console.log(lastFruit); // "mango"
console.log(fruits); // ["apple", "banana"]

21
shift()
 Purpose: Removes the first element of an array and returns that element.
 Example:
let fruits = ["apple", "banana", "mango"];
let firstFruit = fruits.shift();
console.log(firstFruit); // "apple"
console.log(fruits); // ["banana", "mango"]
unshift()
 Purpose: Adds one or more elements to the beginning of an array.
 Example:
let fruits = ["banana", "mango"];
fruits.unshift("apple");
console.log(fruits); // ["apple", "banana", "mango"]
slice()
 Purpose: Returns a shallow copy of a portion of an array into a new array object.
 The original array will not be modified.
 Example:
Let's clarify the parameters for the slice() method.
Syntax:
array.slice(start, end)
Parameters:
1. start:
 The index at which to begin the extraction.
 The first element is at index 0.
 If the start index is omitted, it defaults to 0.
2. end:
 The index before which to end the extraction. The slice will include up to, but not
including the element at this index.

22
 If omitted, it extracts through the end of the array.
Example:
let fruits = ["apple", "banana", "mango", "orange"];
let citrus = fruits.slice(2, 4);
console.log(citrus); // ["mango", "orange"]
Explanation:
 slice(2, 4) means "start at index 2 and extract up to, but not including index 4."
 Index 2 in the fruits array corresponds to "mango".
 Index 4 in the fruits array corresponds to "orange", but it is not included in the result.
So, the result is ["mango", "orange"].

splice()
 Purpose: Adds or removes elements from an array at a specified index.
 Example:
let fruits = ["apple", "banana", "mango"];
fruits.splice(1, 1, "grape", "pear");
console.log(fruits); // ["apple", "grape", "pear", "mango"]
concat()
 Purpose: Merges two or more arrays into a new array.
 Example:
let citrus = ["orange", "lemon"];
let tropical = ["banana", "mango"];
let fruits = citrus.concat(tropical);
console.log(fruits); // ["orange", "lemon", "banana", "mango"]
Activity:
1. Experiment with Array Methods:
 Create an array of your favorite animals.

23
 Use each of the methods listed above and observe the output.
2. Apply Array Methods:
 Write a function that takes an array of numbers and returns a new array with all
negative numbers removed.
function removeNegatives(numbers) {
return numbers.filter(num => num >= 0);
}

let nums = [-1, 2, -3, 4];


console.log(removeNegatives(nums)); // [2, 4]
Part 2: Objects
Object Basics:
 Objects in JavaScript are collections of key-value pairs, where the key is a string (also
known as a property name) and the value can be any type of data.
 Objects are used to store data in a structured way.
let person = {
name: "Alice",
age: 25,
city: "New York"
};
console.log(person.name); // Outputs: Alice
Manipulating Objects:
1. Accessing Properties:
 You can access an object's properties using dot notation or bracket notation.
 Dot Notation:
console.log(person.name); // Outputs: Alice
 Bracket Notation:
console.log(person["age"]); // Outputs: 25

24
2. Adding or Modifying Properties:
 You can add or modify properties using dot notation or bracket notation.
 Adding:
person.country = "USA";
console.log(person); // Outputs: {name: "Alice", age: 25, city: "New York", country: "USA"}
 Modifying:
person.age = 26;
console.log(person.age); // Outputs: 26
3. Deleting Properties:
 You can delete properties from an object using the delete keyword.
 Deleting:

delete person.city;
console.log(person); // Outputs: {name: "Alice", age: 26, country: "USA"}
Activity:
1. Create an Object:
 Create an object representing a car with properties like brand, model, and year.
2. Manipulate the Object:
 Add a new property to the car object for color.
 Modify the year property of the car object.
 Delete the model property from the car object.
let car = {
brand: "Toyota",
model: "Corolla",
year: 2020
};

// Adding a new property


car.color = "red";

25
console.log(car); // Outputs: {brand: "Toyota", model: "Corolla", year: 2020, color: "red"}

// Modifying an existing property


car.year = 2021;
console.log(car.year); // Outputs: 2021

// Deleting a property
delete car.model;
console.log(car); // Outputs: {brand: "Toyota", year: 2021, color: "red"}

26
Questions Quiz #1 Lesson 1-6

27
Part 1: Basics and Variables
1. What is JavaScript and why is it important in web development?
2. Declare a variable `greeting` using `let` and assign it the value "Hello, World!".
Part 2: Operators
3. What will the following code output? Why?
let x = 5;
let y = "5";
console.log(x === y);
4. Write a function `multiply` that takes two numbers as arguments and returns their product.
Part 3: Control Structures
5. Write a `for` loop that prints all the even numbers from 2 to 20.
6. Given a variable `age`, write an `if` statement that logs "You are a minor." if `age` is less than
18, and "You are an adult." otherwise.
Part 4: Functions
7. Write a function `greet` that takes a `name` as an argument and returns the string "Hello,
[name]!".
8. What will the following code output? Why?
function scopeTest() {
var test = "inside";
}
console.log(test);
Part 5: Arrays
9. Given the array `fruits = ["apple", "banana", "mango"]`, write code to add "orange" to the end
of the array.
10. Write a function `sumArray` that takes an array of numbers and returns the sum of all the
numbers.
Part 6: Objects
11. Create an object `person` with properties `name`, `age`, and `city`. Then, write code to log
the `name` of the person.
12. Given an object `book = { title: "JavaScript", author: "John Doe", year: 2021 }`, write code
to update the `year` to 2022 and add a new property `pages` with value 500.

Answers
Part 1: Basics and Variables
1.Answer: JavaScript is important for creating interactive and dynamic webpages.

28
2.Answer: let greeting = "Hello, World!";
Part 2: Operators
3.Answer: false
4.Answer:
function multiply(num1, num2) {
let result;
return result = num1 * num2;
}
Part 3: Control Structures
5.Answer:
for(let i = 2; i <= 20; i += 2) {
console.log(i);
}
6.Answer:
let age = 13;
if (age < 18) {
console.log("You are a minor.");
} else {
console.log("You are an adult.");
}
Part 4: Functions
7.Answer:
function greet(name) {
let greeting = "";
return greeting = `Hello, ${name}!`;
}
8.Answer: Error, undefined variable test, because test variable inside the function is local
variable not global.
Part 5: Arrays
9.Answer: fruits.push("orange");

29
10.Answer:
function sumArray(arr) {
let sum = 0;
for(let i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
Part 6: Objects
11.Answer:
let person = {
name: "Mohammed",
age: 29,
city: "Baghdad"
};
console.log(person.name);
12.Answer:
let book = { title: "JavaScript", author: "John Doe", year: 2021 };
book.year = 2022;
book.pages = 500;

30
Questions Quiz #2 Lesson 1-6
Part 1: Basics and Variables
What will the following code output? Why?
var x = 10; if (true) { var x = 20; } console.log(x);
Declare a variable result using const and assign it the value of 100 divided by 4.
Part 2: Operators
What will the following code output? Why?
let a = 1; let b = "1"; console.log(a == b); console.log(a === b);
Write a function subtract that takes two numbers as arguments and returns their difference.
Part 3: Control Structures
Write a while loop that prints all the odd numbers from 1 to 19.
Given a variable score, write an if-else statement that logs "Passed" if score is greater than or
equal to 50, and "Failed" otherwise.
Part 4: Functions
Write a function square that takes a number as an argument and returns its square.
What will the following code output? Why?
function example() { var message = "Hello"; } example(); console.log(message);
Part 5: Arrays
Given the array numbers = [1, 2, 3, 4, 5], write code to remove the last element.
Write a function doubleArray that takes an array of numbers and returns an array where each
number is doubled.
Part 6: Objects
Create an object student with properties name, grade, and subject. Then, write code to change
the grade to "A+".
Given an object car = { brand: "Toyota", model: "Corolla", year: 2019 }, write code to delete
the model property and log the result.

Answers
Part 1: Basics and Variables
Answer: 20
Answer: const result = 100 / 4;
Part 2: Operators
Answer: true, false
Answer: function subtract(num1, num2) { return num1 - num2; }

31
Part 3: Control Structures
Answer: let count = 1; while (count <= 19) { if (count % 2 !== 0) { console.log(count); } count+
+; }
Answer: let score = 51; if (score >= 50) { console.log("Passed"); } else { console.log("Failed");
Part 4: Functions
Answer: function square(num) { return num * num; }
Answer: Error, undefined variable message
Part 5: Arrays
Answer: numbers.pop();
Answer: function doubleArray(arr) { let tempArr = []; for (let i = 0; i < arr.length; i++)
{ tempArr.push(arr[i] * 2); } return tempArr; }
Part 6: Objects
Answer: let student = { name: "Mohammed", grade: "B", subject: "Pharmacology" };
student.grade = "A+";
Answer: delete car.model; console.log(car);

32
#7 ES6 and Beyond
Objectives:
 Learn about the improvements and new features introduced in ES6 (ECMAScript 2015)
and later versions.
 Practice using let and const to declare variables.
 Understand and use arrow functions.
 Explore template literals, Destructuring, and the spread/rest operators.
Part 1: let and const
let:
1. Description: let declares block-scoped variables.
2. Scope: Block scope (within {})
3. Usage:
let x = 10;
if (true) {
let x = 20;
console.log(x); // 20
}
console.log(x); // 10
4. Benefits:
 Prevents variable hoisting issues.
 Avoids unintended global variables.
const:
1. Description: const declares block-scoped variables that cannot be reassigned.
2. Scope: Block scope (within {})
3. Usage:
const y = 30;
// y = 40; // Error: Assignment to constant variable.
4. Benefits:

33
 Prevents accidental reassignment.
 Encourages immutable data.
Activity:
 Task: Write examples using both let and const in various scopes and blocks.

Part 2: Arrow Functions


Arrow Functions:
1. Description: Arrow functions provide a concise syntax for writing functions.
2. Syntax: (param1, param2, ...) => expression
3. Usage:
const add = (a, b) => a + b;
console.log(add(2, 3)); // 5
4. Benefits:
1. Shorter syntax.
2. Lexical this (doesn't bind its own this context).
Differences with Regular Functions:
1. this Context:
 Arrow functions inherit this from the parent scope.
 Regular functions bind their own this.
const obj = {
value: 42,
regularFunction: function() {
console.log(this.value); // 42
},
arrowFunction: () => {
console.log(this.value); // undefined
}

34
};
obj.regularFunction(); // 42
obj.arrowFunction(); // undefined
2. Usage:
 Use regular functions when this context is needed.
 Use arrow functions for simple expressions or when this is not needed.
Activity:
 Task: Rewrite a regular function using an arrow function.
 Task: Explore the difference between regular functions and arrow functions regarding the
this keyword.

Part 3: Template Literals


Template Literals:
1. Description: Template literals allow embedding expressions inside string literals using
backticks (`).
2. Syntax: `Hello, ${name}!`
3. Usage:
let name = "Alice"; console.log(`Hello, ${name}!`); // Hello, Alice!
Benefits:
1. Multi-line Strings:
let multiLine = `This is a multi-line string.`; console.log(multiLine);
2. String Interpolation:
let a = 5; let b = 10; console.log(`The sum of ${a} and ${b} is ${a + b}.`); // The sum of 5 and
10 is 15.

Activity:
 Task: Write a string using template literals, embedding variables and expressions.
 Task: Create a multi-line string using template literals.

35
Part 4: Destructuring
Destructuring Assignment:
1. Description: Destructuring allows unpacking values from arrays or properties from
objects.
2. Array Destructuring:
Syntax: [a, b] = [1, 2]
Example:
let numbers = [1, 2, 3]; let [a, b, c] = numbers; console.log(a, b, c); // 1 2 3
3. Object Destructuring:
Syntax: {key1, key2} = {key1: value1, key2: value2}
Example:
let person = { name: "Alice", age: 25 }; let { name, age } = person; console.log(name, age); //
Alice 25
4. Benefits:
 Simplifies code.
 Provides clean ways to extract data.
Activity:
 Task: Write examples unpacking arrays and objects using Destructuring.
 Task: Swap two variables using Destructuring.

36
Part 5: Spread and Rest Operators
Spread Operator:
1. Description: The spread operator (...) expands an iterable into individual elements.
2. Usage:
let arr1 = [1, 2, 3]; let arr2 = [...arr1, 4, 5]; console.log(arr2); // [1, 2, 3, 4, 5]
3. Benefits:
 Combines arrays.
 Clones arrays or objects.
Rest Operator:
1. Description: The rest operator (...) collects multiple elements into a single array.
2. Usage:
function sum(...numbers) { return numbers.reduce((acc, num) => acc + num, 0); }
console.log(sum(1, 2, 3, 4)); // 10
3. Benefits:
 Handles variable function arguments.
 Simplifies parameter lists.
Activity:
 Task: Write examples using the spread operator in different scenarios.
 Task: Write examples using the rest operator to handle variable function arguments.

37
More Explanation and examples about spread and rest:
Rest Operator
The Rest Operator (...) allows a function to accept an indefinite number of arguments as an
array.
Usage:
Rest Operator in Functions:
1. Description:
 The rest operator gathers remaining elements into an array.
2. Example:
function sum(...numbers) { return numbers.reduce((acc, num) => acc + num, 0); }
console.log(sum(1, 2, 3)); // Outputs: 6
 Explanation:
 The sum function takes any number of arguments.
 These arguments are gathered into an array called numbers.
 The .reduce() method adds up all the elements in numbers.
Rest Operator in Array Destructuring:
1. Description:
 The rest operator gathers remaining elements after the specified ones into an
array.
2. Example:
let [first, ...rest] = [10, 20, 30, 40]; console.log(first); // Outputs: 10 console.log(rest); // Outputs:
[20, 30, 40]
 Explanation:
 The variable first gets the value 10.
 The rest of the elements (20, 30, and 40) are gathered into the array rest.
Spread Operator
The Spread Operator (...) allows you to expand elements of an array or object.
Usage:

38
Spread Operator with Arrays:
1. Description:
 The spread operator expands elements of an array into individual elements.
2. Example:
let arr1 = [1, 2, 3]; let arr2 = [...arr1, 4, 5]; console.log(arr2); // Outputs: [1, 2, 3, 4, 5]
 Explanation:
 The elements of arr1 (1, 2, 3) are expanded into individual elements.
 These elements are combined with 4 and 5 to form the new array arr2.
Spread Operator with Objects:
1. Description:
 The spread operator expands properties of an object into individual key-value
pairs.
2. Example:
let person = { name: "Alice", age: 25 }; let clonedPerson = { ...person, city: "Wonderland" };
console.log(clonedPerson); // Outputs: { name: "Alice", age: 25, city: "Wonderland" }
 Explanation:
 The properties of person are expanded into individual key-value pairs.
 These properties are combined with a new property city to form
clonedPerson.
Summary:
1. Rest Operator:
 Use: To gather multiple elements into an array.
 Examples: Handling multiple arguments, array Destructuring.
2. Spread Operator:
 Use: To expand elements into individual elements.
 Examples: Combining arrays, cloning objects.

39
Rest Operator
The Rest Operator (...) allows you to pass an indefinite number of arguments to a function,
which are then grouped into an array.
Rest Operator in Functions
1. Description:
 The rest operator collects multiple elements and combines them into an array.
2. Usage:
function greet(...names) { console.log("Hello, " + names.join(", ") + "!"); } greet("Alice", "Bob",
"Charlie"); // Outputs: "Hello, Alice, Bob, Charlie!"
 Explanation:
 The greet function takes any number of names as arguments.
 The names parameter is an array containing all the arguments passed to
the function.
Rest Operator in Array Destructuring
1. Description:
 The rest operator collects the remaining elements after specified ones into an
array.
2. Usage:
let [first, ...rest] = [1, 2, 3, 4]; console.log(first); // Outputs: 1 console.log(rest); // Outputs: [2, 3,
4]
 Explanation:
 The variable first gets the value 1.
 The remaining elements (2, 3, and 4) are collected into the array rest.
Spread Operator
The Spread Operator (...) allows you to expand elements of an array or properties of an object.
Spread Operator with Arrays
1. Description:
 The spread operator expands elements of an array into individual elements.
2. Usage:

40
let arr1 = [1, 2, 3]; let arr2 = [...arr1, 4, 5]; console.log(arr2); // Outputs: [1, 2, 3, 4, 5]
 Explanation:
 The elements of arr1 (1, 2, 3) are expanded into individual elements.
 These elements are combined with 4 and 5 to form the new array arr2.
Spread Operator with Objects
1. Description:
 The spread operator expands properties of an object into individual key-value
pairs.
2. Usage:
let person = { name: "Alice", age: 25 }; let clonedPerson = { ...person, city: "Wonderland" };
console.log(clonedPerson); // Outputs: { name: "Alice", age: 25, city: "Wonderland" }
 Explanation:
 The properties of person are expanded into individual key-value pairs.
 These properties are combined with a new property city to form
clonedPerson.
Summary
1. Rest Operator:
 Use: To collect multiple elements into an array.
 Examples: Handling multiple arguments, array Destructuring.
2. Spread Operator:
 Use: To expand elements into individual elements.
 Examples: Combining arrays, cloning objects.

41
Rest Operator
The Rest Operator (...) is used to gather multiple elements into an array. It's primarily used in
two contexts:
1. Function Parameters:
 The rest operator gathers multiple function arguments into an array.
function sum(...numbers) { return numbers.reduce((acc, num) => acc + num, 0); }
console.log(sum(1, 2, 3, 4)); // Outputs: 10
2. Array Destructuring:
 The rest operator gathers the remaining elements after specified ones into an
array.
let [first, ...rest] = [10, 20, 30, 40]; console.log(first); // Outputs: 10 console.log(rest); // Outputs:
[20, 30, 40]
Spread Operator
The Spread Operator (...) is used to expand elements of an iterable (like an array or object) into
individual elements. It's primarily used in two contexts:
1. Function Arguments:
 The spread operator expands an array into individual arguments for a function
call.
function multiply(a, b, c) { return a * b * c; } let numbers = [2, 3, 4];
console.log(multiply(...numbers)); // Outputs: 24
2. Array/Object Literals:
 The spread operator expands elements of an array or properties of an object.
let arr1 = [1, 2, 3]; let arr2 = [...arr1, 4, 5]; console.log(arr2); // Outputs: [1, 2, 3, 4, 5]

let person = { name: "Alice", age: 25 }; let clonedPerson = { ...person, city: "Wonderland" };
console.log(clonedPerson); // Outputs: { name: "Alice", age: 25, city: "Wonderland" }
Key Differences
1. Purpose:
 Rest: Gathers multiple elements into an array.
 Spread: Expands elements into individual elements.

42
2. Context:
 Rest: Typically used in function parameters or array Destructuring.
 Spread: Typically used in function arguments or array/object literals.
Examples Side by Side
Rest Operator Examples:
1. Function Parameters:
function greet(...names) { console.log("Hello, " + names.join(", ") + "!"); } greet("Alice", "Bob",
"Charlie"); // Outputs: "Hello, Alice, Bob, Charlie!"
2. Array Destructuring:
let [head, ...tail] = [1, 2, 3, 4]; console.log(head); // Outputs: 1 console.log(tail); // Outputs: [2, 3,
4]
Spread Operator Examples:
1. Function Arguments:
let numbers = [1, 2, 3]; console.log(Math.max(...numbers)); // Outputs: 3
2. Array Literals:
let arr1 = [1, 2, 3]; let arr2 = [...arr1, 4, 5]; console.log(arr2); // Outputs: [1, 2, 3, 4, 5]
3. Object Literals:
let person = { name: "Alice", age: 25 }; let clonedPerson = { ...person, city: "Wonderland" };
console.log(clonedPerson); // Outputs: { name: "Alice", age: 25, city: "Wonderland" }
Summary
The Rest and Spread operators (...) are flexible tools in JavaScript. The key to using them
effectively is to understand their different purposes:
 Rest gathers multiple elements.
 Spread expands elements into individual elements.

Explanation of the methods used in the above Spread & Rest examples
Reduce(), Join()
Understanding reduce()

43
The reduce() method is used to process an array and reduce it to a single value.
Syntax:
array.reduce(callback, initialValue)
Components:
1. callback:
 A function that executes on each element in the array.
 Parameters of callback:
 accumulator: The accumulated result from the previous iteration.
 currentValue: The current element being processed.
 currentIndex (optional): The index of the current element.
 array (optional): The array being processed.
 Function Body:
 Defines how the accumulator and currentValue should be combined.
2. initialValue (optional):
 The initial value of the accumulator.
 If not provided, reduce() starts with the first element.
Example:
Let's use reduce() to sum all the elements in an array.
let numbers = [1, 2, 3, 4]; let sum = numbers.reduce((accumulator, currentValue) => accumulator
+ currentValue, 0); console.log(sum); // Outputs: 10
How It Works:
1. Initialization:
 The reduce() method starts with the initialValue of 0.
 It sets the accumulator to 0.
2. Iteration:
 In each iteration, reduce():
 Adds the currentValue to the accumulator.

44
 Returns the new accumulator value.
 Here's how it works for our example:
 First Iteration: accumulator = 0, currentValue = 1 → accumulator = 1
 Second Iteration: accumulator = 1, currentValue = 2 → accumulator =
3
 Third Iteration: accumulator = 3, currentValue = 3 → accumulator =
6
 Fourth Iteration: accumulator = 6, currentValue = 4 → accumulator =
10
3. Result:
 The final result, 10, is returned and stored in the variable sum.
Another Example: Multiplication:
let numbers = [1, 2, 3, 4]; let product = numbers.reduce((accumulator, currentValue) =>
accumulator * currentValue, 1); console.log(product); // Outputs: 24
Explanation:
1. Initialization:
 The reduce() method starts with the initialValue of 1.
2. Iteration:
 In each iteration, reduce() multiplies the currentValue with the accumulator.
3. Result:
 The final result, 24, is returned and stored in the variable product.
Conclusion:
The reduce() method is a powerful way to aggregate or transform data in arrays. The function
provided as the callback determines how the accumulation occurs.

join() Method
The join() method creates and returns a new string by concatenating all elements in an array,
separated by a specified separator.
Syntax:

45
array.join(separator)
Parameters:
1. separator: This is optional. It's a string that separates the elements of the array. If
omitted, the default separator is a comma ,.
Usage:
1. Basic Example:
let fruits = ["apple", "banana", "cherry"]; let result = fruits.join(", "); console.log(result); //
Outputs: "apple, banana, cherry"
2. Explanation:
 The array fruits contains elements "apple", "banana", and "cherry".
 The join() method combines these elements into a single string.
 The separator ", " is used to place a comma and a space between each element.
3. Different Separator:
let numbers = [1, 2, 3, 4]; let result = numbers.join("-"); console.log(result); // Outputs: "1-2-3-4"
 The separator "-" is used, resulting in a string with hyphens between the
numbers.
4. No Separator:
let letters = ["A", "B", "C"]; let result = letters.join(""); console.log(result); // Outputs: "ABC"
 When no separator is provided or an empty string is used, the elements are
concatenated without any separator.
Conclusion
The join() method is useful when you want to create a single string from an array of elements,
especially for displaying or logging purposes.
Rest Operator Revisited
Now that you understand join(), let's revisit the Rest Operator example:
function greet(...names) { console.log("Hello, " + names.join(", ") + "!"); } greet("Alice", "Bob",
"Charlie"); // Outputs: "Hello, Alice, Bob, Charlie!"
In this example:
1. The greet function uses the Rest Operator to accept any number of names.

46
2. The names parameter is an array containing all the arguments.
3. The join(", ") method is used to combine these names with a comma and a space
between them.
4. The final output is "Hello, Alice, Bob, Charlie!".

47
Part 6: Classes
Classes:
1. Description: Classes provide a blueprint for creating objects. They encapsulate data with
code to work on that data.
2. Syntax:
class Person { constructor(name, age) { this.name = name; this.age = age; } greet() { return
`Hello, my name is ${this.name}`; } }
3. Usage:
let person = new Person("Alice", 25); console.log(person.greet()); // Outputs: "Hello, my name is
Alice"
4. Features:
 Constructor:
 Special method used to initialize an object.
 Methods:
 Functions defined inside a class.
 Inheritance:
 Classes can inherit from other classes using the extends keyword.
Activity:
1. Task: Create a class Car with properties make and model, and a method displayInfo
that returns the car's make and model.
Answer:
class Car {
constructor(make, model) {
this.make = make;
this.model = model;
}

displayInfo() {
return `Car: ${this.make} ${this.model}`;
48
}
}
let car = new Car("Toyota", "Corolla");
console.log(car.displayInfo()); // Outputs: "Car: Toyota Corolla"
2. Task: Create a subclass ElectricCar that inherits from Car and adds a property
batteryRange. Define a method displayRange that returns the car's battery range.
Answer:
class ElectricCar extends Car {
constructor(make, model, batteryRange) {
super(make, model);
this.batteryRange = batteryRange;
}

displayRange() {
return `Battery range: ${this.batteryRange} km`;
}
}
let electricCar = new ElectricCar("Tesla", "Model 3", 400);
console.log(electricCar.displayInfo()); // Outputs: "Car: Tesla Model 3"
console.log(electricCar.displayRange()); // Outputs: "Battery range: 400 km"

What are Classes?


1. Description:
 Classes in JavaScript provide a blueprint for creating objects.
 They encapsulate data (properties) and behavior (methods) together.
2. Syntax:
class Person { constructor(name, age) { this.name = name; this.age = age; } greet() { return
`Hello, my name is ${this.name}`; } }

49
 constructor(): A special method that initializes new objects.
 this: Refers to the current instance of the class.
3. Creating Instances:
 An object created using a class is called an "instance".
let alice = new Person("Alice", 30); console.log(alice.greet()); // Outputs: "Hello, my name is
Alice"
Features of Classes
1. Properties:
 Data fields of a class.
class Car { constructor(make, model) { this.make = make; this.model = model; } }
2. Methods:
 Functions defined inside a class.
class Car { constructor(make, model) { this.make = make; this.model = model; } displayInfo()
{ return `Car: ${this.make} ${this.model}`; } } let car = new Car("Toyota", "Corolla");
console.log(car.displayInfo()); // Outputs: "Car: Toyota Corolla"
3. Inheritance:
 Classes can inherit from other classes.
class ElectricCar extends Car { constructor(make, model, batteryRange) { super(make, model);
this.batteryRange = batteryRange; } displayRange() { return `Battery range: $
{this.batteryRange} km`; } } let electricCar = new ElectricCar("Tesla", "Model 3", 400);
console.log(electricCar.displayInfo()); // Outputs: "Car: Tesla Model 3"
console.log(electricCar.displayRange()); // Outputs: "Battery range: 400 km"
Real-Life Situations
1. Creating Objects:
 Classes help you define objects, like users in a system.
class User { constructor(username, email) { this.username = username; this.email = email; }
displayUser() { return `User: ${this.username}, Email: ${this.email}`; } } let user1 = new
User("johnDoe", "john@example.com"); console.log(user1.displayUser()); // Outputs: "User:
johnDoe, Email: john@example.com"
2. Modeling Systems:

50
 Classes model complex systems, like a library system.
class Book { constructor(title, author) { this.title = title; this.author = author; } displayBook()
{ return `Book: ${this.title} by ${this.author}`; } } let book1 = new Book("1984", "George
Orwell"); console.log(book1.displayBook()); // Outputs: "Book: 1984 by George Orwell"
3. Encapsulation:
 Classes encapsulate data and behavior, useful for a bank account system.
class BankAccount { constructor(owner, balance) { this.owner = owner; this.balance = balance; }
deposit(amount) { this.balance += amount; } withdraw(amount) { if (amount <= this.balance)
{ this.balance -= amount; } else { console.log("Insufficient funds"); } } displayBalance() { return
`Account holder: ${this.owner}, Balance: $${this.balance}`; } } let account = new
BankAccount("Alice", 500); account.deposit(200); console.log(account.displayBalance()); //
Outputs: "Account holder: Alice, Balance: $700"
Practice Tasks for Classes
1. Task: Create a class Movie with properties title and director. Add a method displayInfo
that returns the movie's title and director.
Answer:
class Movie { constructor(title, director) { this.title = title; this.director = director; } displayInfo()
{ return `Movie: ${this.title} directed by ${this.director}`; } } let movie = new
Movie("Inception", "Christopher Nolan"); console.log(movie.displayInfo()); // Outputs: "Movie:
Inception directed by Christopher Nolan"
2. Task: Create a subclass AnimatedMovie that inherits from Movie and adds a property
animationStudio. Add a method displayStudio that returns the animation studio.
Answer:
class AnimatedMovie extends Movie { constructor(title, director, animationStudio) { super(title,
director); this.animationStudio = animationStudio; } displayStudio() { return `Animation Studio:
${this.animationStudio}`; } } let animatedMovie = new AnimatedMovie("Toy Story", "John
Lasseter", "Pixar"); console.log(animatedMovie.displayInfo()); // Outputs: "Movie: Toy Story
directed by John Lasseter" console.log(animatedMovie.displayStudio()); // Outputs: "Animation
Studio: Pixar"

51
Part 7: Promises
Promises:
1. Description: Promises represent the eventual completion (or failure) of an asynchronous
operation and its resulting value.
2. Syntax:
let promise = new Promise((resolve, reject) => { // Asynchronous code });
3. Usage:
let promise = new Promise((resolve, reject) => { setTimeout(() => resolve("Success"), 1000); });
promise .then(result => console.log(result)) // Outputs: "Success" .catch(error =>
console.error(error));
4. Methods:
 then: Executes when the promise is resolved.
 catch: Executes when the promise is rejected.
 finally: Executes regardless of the promise outcome.
Activity:
1. Task: Create a promise that resolves after 2 seconds with the message "Completed".
Answer:
let delayedMessage = new Promise((resolve, reject) => {
setTimeout(() => resolve("Completed"), 2000);
});
delayedMessage.then(result => console.log(result)); // Outputs: "Completed"
2. Task: Create a promise that rejects with an error message "Failed".
Answer:
let failedPromise = new Promise((resolve, reject) => {
reject("Failed");
});
failedPromise.catch(error => console.error(error)); // Outputs: "Failed"

52
What are Promises?
1. Description: Promises represent the eventual completion (or failure) of an asynchronous
operation and its resulting value.
2. Syntax:
let promise = new Promise((resolve, reject) => { // Asynchronous code });
Using Promises
1. Creating a Promise:
 A promise is created using the Promise constructor.
 The constructor function takes a function with two parameters, resolve and reject.
let promise = new Promise((resolve, reject) => { let success = true; if (success)
{ resolve("Operation succeeded"); } else { reject("Operation failed"); } });
2. Consuming a Promise:
 The then method is used to handle a successful result.
 The catch method is used to handle an error.
promise .then(result => { console.log(result); // Outputs: "Operation succeeded" }) .catch(error
=> { console.error(error); });
Real-Life Situations
1. Fetching Data:
 Promises are commonly used to fetch data from an API.
function fetchData(url) { return new Promise((resolve, reject) => { // Simulating fetching data
from a server setTimeout(() => { if (url === "validURL") { resolve("Data retrieved
successfully"); } else { reject("Error: Invalid URL"); } }, 1000); }); }
fetchData("validURL") .then(result => { console.log(result); // Outputs: "Data retrieved
successfully" }) .catch(error => { console.error(error); // Outputs: "Error: Invalid URL" });
2. Delaying Execution:
 Promises can be used to delay execution for a set period of time.
function delay(milliseconds) { return new Promise((resolve) => { setTimeout(() =>
{ resolve("Delay completed"); }, milliseconds); }); } delay(2000) .then(result =>
{ console.log(result); // Outputs: "Delay completed" after 2 seconds });
Practice Tasks for Promises

53
1. Task: Create a promise that resolves after 3 seconds with the message "Time's up!".
Answer:
let timer = new Promise((resolve) => { setTimeout(() => { resolve("Time's up!"); }, 3000); });
timer.then(result => { console.log(result); // Outputs: "Time's up!" after 3 seconds });
2. Task: Create a promise that simulates a server request and randomly resolves or rejects
after 1 second.
Answer:
let serverRequest = new Promise((resolve, reject) => { setTimeout(() => { if (Math.random() >
0.5) { resolve("Request succeeded"); } else { reject("Request failed"); } }, 1000); });
serverRequest .then(result => { console.log(result); // Outputs either "Request succeeded" or
"Request failed" }) .catch(error => { console.error(error); });

Recap and Conclusion:


 We've covered key features of ES6 and beyond.
 Practiced using let and const.
 Explored arrow functions, template literals, Destructuring, and the spread/rest operators.
 Learned about classes and promises.

54
………………………………..

Intermediate Level
6. Arrays and Objects
 Working with arrays
 Manipulating objects
 JSON data
7. ES6 and Beyond
 Let and const
 Arrow functions
 Template literals
 Destructuring
 Default parameters
 Spread and rest operators
8. Asynchronous JavaScript
 Callbacks
 Promises
 Async/await
9. DOM Manipulation
 Selecting elements
 Changing element properties
 Event handling

55
10. Form Validation and Manipulation
 Handling form inputs
 Basic client-side validation

………………………………..

Advanced Level
11. Advanced Functions
 Higher-order functions
 Callbacks and closures
12. Modules and Namespaces
 Organizing code
 Module patterns
 ES6 modules
13. Web APIs and HTTP Requests
 Fetch API
 AJAX
 Working with external APIs
14. Error Handling and Debugging
 Try, catch, finally
 Throwing errors
 Debugging techniques
15. Tools and Frameworks
 Introduction to Node.js
 Overview of front-end frameworks (React, Angular, Vue)
 Build tools (Webpack, Babel)
Project Phase
16. Capstone Projects

56
 Applying everything you've learned
 Building small to medium-sized projects
 Version control with Git
17. Code Reviews and Best Practices
 Writing clean code
 Performance optimization
 Security practices

57
Quizzes
JavaScript Quiz #1 - Questions and Answers
Lesson 1-6

Part 1: Basics and Variables

1. What is JavaScript and why is it important in web development?


Answer: JavaScript is important for creating interactive and dynamic webpages.

2. Declare a variable `greeting` using `let` and assign it the value "Hello, World!".
Answer: let greeting = "Hello, World!";

Part 2: Operators

3. What will the following code output? Why?


let x = 5;
let y = "5";
console.log(x === y);

Answer: false

4. Write a function `multiply` that takes two numbers as arguments and returns their
product.
Answer:
function multiply(num1, num2) {
let result;
return result = num1 * num2;
}

Part 3: Control Structures

5. Write a `for` loop that prints all the even numbers from 2 to 20.
Answer:
for(let i = 2; i <= 20; i += 2) {
console.log(i);
}

58
6. Given a variable `age`, write an `if` statement that logs "You are a minor." if `age` is
less than 18, and "You are an adult." otherwise.
Answer:
let age = 13;
if (age < 18) {
console.log("You are a minor.");
} else {
console.log("You are an adult.");
}

Part 4: Functions

7. Write a function `greet` that takes a `name` as an argument and returns the string
"Hello, [name]!".
Answer:
function greet(name) {
let greeting = "";
return greeting = `Hello, ${name}!`;
}

8. What will the following code output? Why?


function scopeTest() {
var test = "inside";
}
console.log(test);

Answer: Error, undefined variable test, because test variable inside the function is local variable not
global.

Part 5: Arrays

9. Given the array `fruits = ["apple", "banana", "mango"]`, write code to add "orange"
to the end of the array.
Answer: fruits.push("orange");

10. Write a function `sumArray` that takes an array of numbers and returns the sum of
all the numbers.
Answer:
function sumArray(arr) {
let sum = 0;
for(let i = 0; i < arr.length; i++) {

59
sum += arr[i];
}
return sum;
}

Part 6: Objects

11. Create an object `person` with properties `name`, `age`, and `city`. Then, write
code to log the `name` of the person.
Answer:
let person = {
name: "Mohammed",
age: 29,
city: "Baghdad"
};
console.log(person.name);

12. Given an object `book = { title: "JavaScript", author: "John Doe", year: 2021 }`,
write code to update the `year` to 2022 and add a new property `pages` with value
500.
Answer:
let book = { title: "JavaScript", author: "John Doe", year: 2021 };
book.year = 2022;
book.pages = 500;

60
Quiz 2# Lesson 1-6
Part 1: Basics and Variables
1. What will the following code output? Why?
var x = 10; if (true) { var x = 20; } console.log(x);
Answer: 20
2. Declare a variable result using const and assign it the value of 100 divided by 4.
Answer: const result = 100 / 4;
Part 2: Operators
3. What will the following code output? Why?
let a = 1; let b = "1"; console.log(a == b); console.log(a === b);
Answer: true, false
4. Write a function subtract that takes two numbers as arguments and returns their
difference.
Answer: function subtract(num1, num2) { return num1 - num2; }
Part 3: Control Structures
5. Write a while loop that prints all the odd numbers from 1 to 19.
Answer: let count = 1; while (count <= 19) { if (count % 2 !== 0) { console.log(count); } count+
+; }
6. Given a variable score, write an if-else statement that logs "Passed" if score is greater
than or equal to 50, and "Failed" otherwise.
Answer: let score = 51; if (score >= 50) { console.log("Passed"); } else { console.log("Failed"); }
Part 4: Functions
7. Write a function square that takes a number as an argument and returns its square.
Answer: function square(num) { return num * num; }
8. What will the following code output? Why?
function example() { var message = "Hello"; } example(); console.log(message);
Answer: Error, undefined variable message
Part 5: Arrays

61
9. Given the array numbers = [1, 2, 3, 4, 5], write code to remove the last element.
Answer: numbers.pop();
10. Write a function doubleArray that takes an array of numbers and returns an array where
each number is doubled.
Answer: function doubleArray(arr) { let tempArr = []; for (let i = 0; i < arr.length; i++)
{ tempArr.push(arr[i] * 2); } return tempArr; }
Part 6: Objects
11. Create an object student with properties name, grade, and subject. Then, write code to
change the grade to "A+".
Answer: let student = { name: "Mohammed", grade: "B", subject: "Pharmacology" };
student.grade = "A+";
12. Given an object car = { brand: "Toyota", model: "Corolla", year: 2019 }, write code
to delete the model property and log the result.
Answer: delete car.model; console.log(car);

62

You might also like