Python Java C++ HTML CSS Bootstrap JavaScript jQuery AngularJS React Node.js TypeScript Django NumPy Pandas Matplotlib Seaborn Machine Learning Deep Learning Decipher XML

Introduction to JavaScript

JavaScript is a high-level, interpreted programming language that runs inside browsers and servers. It is used to make web pages interactive, dynamic, and intelligent.

  • Runs in browser & Node.js
  • Used for frontend & backend
  • Event-driven & asynchronous
JavaScript is one of the MOST important skills for web developers, data dashboards, APIs, and automation.

Why JavaScript Matters

  • It powers interactivity (forms, animations, dynamic content).
  • It works across platforms (web, mobile, desktop, server).
  • It has a huge ecosystem (libraries, frameworks, tools).

Core Characteristics

  • Dynamically typed and flexible.
  • Supports functional, object-oriented, and procedural styles.
  • Single-threaded with asynchronous event loop.

How JavaScript Runs

In browsers, JavaScript runs in the JavaScript engine (like V8 in Chrome). In Node.js, it runs on the server to build APIs, scripts, and tools.

Basic Syntax

JavaScript syntax defines the rules for writing JavaScript programs. Understanding syntax is the first step toward writing clean and correct code.

JavaScript Structure with HTML

You can add JavaScript inside the <script> tag in the HTML file, or link an external .js file. For better performance, place scripts at the end of <body> or use defer.

<!-- Inline script -->
<script>
  console.log("Hello from inline JS");
</script>

<!-- External script -->
<script src="app.js" defer></script>
  

Comments

Comments are used to explain code and are ignored by the JavaScript engine. They help developers understand the logic later.

// Single-line comment

/*
 Multi-line comment
 Used for longer explanations
*/
  
Good code always contains meaningful comments, especially for complex logic.

Variables in JavaScript

Variables are containers used to store data values. JavaScript provides three ways to declare variables.

let x = 10;     // block-scoped variable
const y = 20;  // constant value (cannot change)
var z = 5;     // function-scoped (old style)
  

let Keyword

let is used to declare variables whose values can change. It has block scope, meaning it exists only inside the block `{}`.

let count = 1;
count = 2; // allowed

if(true){
  let a = 10;
  console.log(a); // works
}
// console.log(a); ❌ error (block scope)
  

const Keyword

const is used when the value should not change. It also has block scope.

const PI = 3.14;
// PI = 3.15; ❌ Error (cannot reassign)

const user = { name: "Aman" };
user.name = "Rahul"; // βœ… allowed (object reference remains same)
  

var Keyword (Old Style)

var was used before ES6. It has function scope and causes many bugs due to hoisting. It is not recommended.

var num = 10;

if(true){
  var num = 20;
}

console.log(num); // 20 (unexpected behavior)
  

Hoisting (Important Concept)

Hoisting means JavaScript moves variable declarations to the top of the scope before execution.

console.log(a); // undefined
var a = 5;

// console.log(b); ❌ error
let b = 10;
  
Best Practice:
βœ” Use let when value can change
βœ” Use const by default
❌ Avoid var

Naming Rules for Variables

  • Must start with a letter, _ or $
  • Cannot start with a number
  • Case-sensitive (age β‰  Age)
  • Use meaningful names
let userName = "Rahul";   // βœ… good
let _count = 10;         // βœ… valid
let 1value = 5;          // ❌ invalid
  

Data Types

JavaScript is a dynamically typed language, meaning you do not need to specify the data type of a variable. The type is determined at runtime.

JavaScript data types are divided into Primitive and Non-Primitive (Reference) types.

Primitive Data Types

  • Number
  • String
  • Boolean
  • Undefined
  • Null
  • Symbol
  • BigInt

1️⃣ Number

The Number type represents both integers and floating-point numbers.

let age = 25;
let price = 99.99;
let negative = -10;

console.log(typeof age); // number
  

Special numeric values:

let x = Infinity;
let y = -Infinity;
let z = NaN; // Not a Number

console.log(10 / "abc"); // NaN
  

2️⃣ String

Strings represent text data and can be written using single quotes, double quotes, or backticks.

let name = "Alice";
let city = 'Delhi';
let message = `Hello ${name}, welcome!`;

console.log(message);
  

3️⃣ Boolean

Boolean represents logical values: true or false.

let isLoggedIn = true;
let hasPermission = false;

console.log(5 > 3); // true
  

4️⃣ Undefined

A variable is undefined when it is declared but not assigned a value.

let score;
console.log(score);        // undefined
console.log(typeof score); // undefined
  

5️⃣ Null

null represents an intentional empty value.

let data = null;
console.log(data);        // null
console.log(typeof data); // object (JavaScript bug)
  
πŸ”₯ Important Interview Question:
null is an object due to a historical JavaScript bug.

6️⃣ Symbol

Symbols are unique and immutable values, mainly used as object keys.

let id1 = Symbol("id");
let id2 = Symbol("id");

console.log(id1 === id2); // false
  

7️⃣ BigInt

BigInt is used for very large integers.

let bigNumber = 12345678901234567890n;
console.log(typeof bigNumber); // bigint
  

Non-Primitive (Reference) Data Types

  • Object
  • Array
  • Function

8️⃣ Object

Objects store data in key-value pairs.

let person = {
  name: "Bob",
  age: 30,
  isStudent: false
};

console.log(person.name); // Bob
  

9️⃣ Array

Arrays store ordered collections of values.

let fruits = ["apple", "banana", "orange"];
fruits.push("grape");

console.log(fruits[0]); // apple
  

πŸ”Ÿ Function

Functions are also objects in JavaScript.

function greet(name){
  return "Hello " + name;
}

console.log(greet("Aman"));
  

typeof Operator

The typeof operator is used to check data types.

console.log(typeof "Hello");   // string
console.log(typeof 100);       // number
console.log(typeof true);      // boolean
console.log(typeof []);        // object
console.log(typeof {});        // object
console.log(typeof null);      // object (bug)
  
Best Practices:
βœ” Use typeof for type checking
βœ” Prefer const for reference types
βœ” Understand primitive vs reference behavior

Operators

Operators are special symbols used to perform operations on values and variables. JavaScript operators help in calculations, comparisons, logical decisions, and writing smart conditions.

Operators are one of the MOST IMPORTANT topics in JavaScript. Almost every program uses them.

1️⃣ Arithmetic Operators

Used to perform mathematical calculations.

let a = 10;
let b = 3;

console.log(a + b); // Addition β†’ 13
console.log(a - b); // Subtraction β†’ 7
console.log(a * b); // Multiplication β†’ 30
console.log(a / b); // Division β†’ 3.33
console.log(a % b); // Modulus (remainder) β†’ 1
  

Increment and Decrement operators:

let count = 5;

count++; // 6
count--; // 5
  

2️⃣ Assignment Operators

Used to assign values to variables.

let x = 10;

x += 5;  // x = x + 5 β†’ 15
x -= 3;  // x = x - 3 β†’ 12
x *= 2;  // x = x * 2 β†’ 24
x /= 4;  // x = x / 4 β†’ 6
  

3️⃣ Comparison Operators

Comparison operators compare two values and return true or false.

let p = 10;
let q = "10";

console.log(p == q);   // true (value only)
console.log(p === q);  // false (value + type)
console.log(p != q);   // false
console.log(p !== q);  // true
console.log(p > 5);    // true
console.log(p <= 10);  // true
  
βœ… Best Practice: Always use === instead of == to avoid bugs.

4️⃣ Logical Operators

Used to combine multiple conditions.

let age = 20;
let hasID = true;

console.log(age >= 18 && hasID); // AND β†’ true
console.log(age < 18 || hasID);  // OR β†’ true
console.log(!hasID);             // NOT β†’ false
  

πŸ”Ή Logical AND (&&) Return Value Concept

Logical operators do not always return true or false. They return actual values.

console.log(5 && 10); // 10
console.log(0 && 10); // 0
console.log(5 || 10); // 5
console.log(0 || 10); // 10
  

5️⃣ Ternary Operator (Conditional Operator)

The ternary operator is a short form of if-else.

let marks = 45;

let result = marks >= 40 ? "Pass" : "Fail";
console.log(result); // Pass
  

Same logic using if-else:

if (marks >= 40) {
  result = "Pass";
} else {
  result = "Fail";
}
  

6️⃣ Real-World Example

let isLoggedIn = true;
let username = isLoggedIn && "Nafees";

console.log(username); // Nafees
  
πŸ”₯ This pattern is widely used in React, Vue, and modern JavaScript apps.

βœ… Summary

  • Arithmetic operators β†’ calculations
  • Assignment operators β†’ update values
  • Comparison operators β†’ true / false
  • Logical operators β†’ combine conditions
  • Ternary operator β†’ short if-else

Control Flow Statements

Control Flow defines the order in which JavaScript statements are executed. It allows JavaScript to make decisions, repeat actions, skip code blocks, and respond intelligently to different conditions.

πŸ”‘ Without control flow, JavaScript would execute code line-by-line without logic, decisions, or dynamic behavior.

1️⃣ if Statement

The if statement executes a block of code only when the condition is true.

let age = 20;

if (age >= 18) {
  console.log("You are eligible to vote");
}
  

How it works:

  • The condition inside if is evaluated
  • If true β†’ code runs
  • If false β†’ code is skipped

2️⃣ if...else Statement

The if...else statement provides two execution paths.

let temperature = 30;

if (temperature > 25) {
  console.log("It is hot");
} else {
  console.log("It is cold");
}
  

3️⃣ else if Statement

Use else if when you need to check multiple conditions.

let marks = 72;

if (marks >= 90) {
  console.log("Grade A");
} else if (marks >= 75) {
  console.log("Grade B");
} else if (marks >= 50) {
  console.log("Grade C");
} else {
  console.log("Fail");
}
  
βœ… Conditions are checked from top to bottom. Once a true condition is found, remaining blocks are skipped.

4️⃣ Nested if Statements

A nested if means an if inside another if.

let username = "admin";
let password = "1234";

if (username === "admin") {
  if (password === "1234") {
    console.log("Login Successful");
  } else {
    console.log("Wrong Password");
  }
} else {
  console.log("Invalid User");
}
  

5️⃣ switch Statement

The switch statement is used when one value is compared against multiple possible cases.

let day = 3;

switch (day) {
  case 1:
    console.log("Monday");
    break;
  case 2:
    console.log("Tuesday");
    break;
  case 3:
    console.log("Wednesday");
    break;
  case 4:
    console.log("Thursday");
    break;
  default:
    console.log("Invalid Day");
}
  
❗ break is mandatory to stop execution. Without it, all following cases will run (fall-through).

When to use switch?

  • Menu selection
  • Day / month logic
  • Status codes

6️⃣ Ternary Operator (Conditional Expression)

The ternary operator is a shorter alternative to if...else for simple conditions.

let age = 20;

let result = age >= 18 ? "Adult" : "Minor";
console.log(result);
  

Syntax:

condition ? valueIfTrue : valueIfFalse
  
⚠️ Use ternary only for simple logic. Complex logic reduces readability.

7️⃣ Logical Operators in Control Flow

AND (&&) – All conditions must be true

let isLoggedIn = true;
let isAdmin = true;

if (isLoggedIn && isAdmin) {
  console.log("Access Granted");
}
  

OR (||) – At least one condition must be true

let hasEmail = false;
let hasPhone = true;

if (hasEmail || hasPhone) {
  console.log("Contact possible");
}
  

NOT (!) – Reverses condition

let isBlocked = false;

if (!isBlocked) {
  console.log("User can access");
}
  

8️⃣ Real-World Example: Login System

let isLoggedIn = true;
let role = "admin";

if (isLoggedIn && role === "admin") {
  console.log("Welcome Admin");
} else if (isLoggedIn) {
  console.log("Welcome User");
} else {
  console.log("Please Login");
}
  

βœ… Summary

  • if β†’ execute code when condition is true
  • if...else β†’ two execution paths
  • else if β†’ multiple conditions
  • nested if β†’ conditions inside conditions
  • switch β†’ multiple fixed values
  • ternary β†’ short conditional logic
  • Logical operators β†’ advanced decision making

Loops

A loop is used to execute the same block of code repeatedly as long as a specified condition is true. Loops are widely used in JavaScript for working with arrays, objects, numbers, DOM elements, and API data.

πŸ”‘ Loops are the backbone of logic building. They are extremely important for interviews and real-world JavaScript projects.

1️⃣ for Loop

The for loop is used when we already know how many times the loop should run.

Syntax:

for (initialization; condition; increment/decrement) {
  // code to execute
}
  
for (let i = 1; i <= 5; i++) {
  console.log(i);
}
  

How it works:

  • let i = 1 β†’ starting value
  • i <= 5 β†’ condition to continue
  • i++ β†’ increase value after each iteration

Looping through an array:

let fruits = ["apple", "banana", "orange"];

for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}
  

Reverse loop:

for (let i = 5; i >= 1; i--) {
  console.log(i);
}
  

2️⃣ while Loop

The while loop is used when the exact number of iterations is unknown and execution depends only on a condition.

let count = 5;

while (count > 0) {
  console.log(count);
  count--;
}
  
⚠️ If the condition never becomes false, the loop will run forever (infinite loop).

Real-world example:

let password = "";

while (password !== "admin") {
  password = prompt("Enter password");
}
  

3️⃣ do...while Loop

The do...while loop always executes at least once, even if the condition is false.

let num = 0;

do {
  console.log("This runs at least once");
  num++;
} while (num < 0);
  

Use case example:

let otp;

do {
  otp = prompt("Enter OTP");
} while (otp !== "1234");
  

4️⃣ for...of Loop

The for...of loop is used for arrays and strings. It provides a clean and modern syntax.

let colors = ["red", "green", "blue"];

for (let color of colors) {
  console.log(color);
}
  

String example:

let name = "JS";

for (let char of name) {
  console.log(char);
}
  

5️⃣ for...in Loop

The for...in loop is used to iterate over the keys of an object.

let user = {
  name: "Nafees",
  age: 22,
  city: "Delhi"
};

for (let key in user) {
  console.log(key + " : " + user[key]);
}
  
❗ for...in is not recommended for arrays.

6️⃣ forEach Loop (Array Method)

forEach is an array method that executes a function for each element.

let numbers = [1, 2, 3, 4];

numbers.forEach(function(num) {
  console.log(num * 2);
});
  

Using arrow function:

numbers.forEach(num => console.log(num));
  

7️⃣ break and continue

break β†’ immediately stops the loop

for (let i = 1; i <= 5; i++) {
  if (i === 4) break;
  console.log(i);
}
  

continue β†’ skips the current iteration

for (let i = 1; i <= 5; i++) {
  if (i === 3) continue;
  console.log(i);
}
  

8️⃣ Nested Loop

A nested loop is a loop inside another loop. It is commonly used for tables, patterns, and matrices.

for (let i = 1; i <= 3; i++) {
  for (let j = 1; j <= 2; j++) {
    console.log(i, j);
  }
}
  

9️⃣ Loop Comparison (Quick Review)

  • for β†’ fixed number of iterations
  • while β†’ condition-based looping
  • do...while β†’ runs at least once
  • for...of β†’ arrays and strings
  • for...in β†’ objects
  • forEach β†’ arrays only
βœ… Once loops are clear, JavaScript logic becomes much stronger and easier to apply in real applications.

Functions

A function is a reusable block of code that performs a specific task. Functions help reduce repetition, improve readability, and make code easier to maintain.

πŸ”‘ Functions are the foundation of JavaScript. Almost everything in JavaScript is built using functions.

Why Use Functions?

  • Avoid repeating the same code
  • Write clean and organized programs
  • Improve debugging and maintenance
  • Reuse logic anywhere in the application

1️⃣ Function Declaration

A function declaration defines a function using the function keyword.

// Function declaration
function add(a, b) {
  return a + b;
}

console.log(add(2, 3)); // 5
  

Explanation:

  • a and b are parameters
  • return sends a value back
  • The function can be reused multiple times

2️⃣ Function Expression

A function expression stores a function inside a variable.

const subtract = function(a, b) {
  return a - b;
};

console.log(subtract(10, 4)); // 6
  
❗ Function expressions are not hoisted, unlike function declarations.

3️⃣ Arrow Function (ES6)

Arrow functions provide a shorter syntax and are commonly used in modern JavaScript.

// Arrow function
const multiply = (a, b) => a * b;

console.log(multiply(2, 3)); // 6
  

Arrow function with block body:

const divide = (a, b) => {
  return a / b;
};

console.log(divide(10, 2)); // 5
  
const cube = num => num * num * num;
console.log(cube(3));

const isEven = num => num % 2 === 0;
console.log(isEven(10));
console.log(isEven(7));
  
⚠️ Arrow functions do not have their own this.

4️⃣ Parameters and Arguments

Parameters are variables defined in a function. Arguments are actual values passed to the function.

function greet(name) {
  console.log("Hello " + name);
}

greet("Nafees");
greet("JavaScript");
  

5️⃣ Default Parameters

Default parameters provide a value when no argument is passed.

function welcome(user = "Guest") {
  console.log("Welcome " + user);
}

welcome();
welcome("Admin");
  

6️⃣ Return vs console.log

return sends data back from a function, while console.log only displays output.

function square(num) {
  return num * num;
}

let result = square(4);
console.log(result);
  

7️⃣ Calling a Function

A function runs only when it is called.

function welcomeUser() {
  console.log("Welcome to Technacode");
}

welcomeUser();
welcomeUser();
  

8️⃣ Nested Functions

A function inside another function is called a nested function.

function mainFunction() {
  console.log("Main function");

  function childFunction() {
    console.log("Child function");
  }

  childFunction();
}

mainFunction();
  
function outer() {
  function inner() {
    console.log("Inner function");
  }
  inner();
}

outer();
  

9️⃣ Callback Functions

A callback is a function passed as an argument to another function.

function processData(callback) {
  callback();
}

processData(function() {
  console.log("Callback executed");
});
  

Arrow callback example:

setTimeout(() => {
  console.log("Executed after 2 seconds");
}, 2000);
  

Real-world callback example:

function calculate(a, b, operation) {
  return operation(a, b);
}

const addNumbers = (x, y) => x + y;
const multiplyNumbers = (x, y) => x * y;

console.log(calculate(5, 3, addNumbers));
console.log(calculate(5, 3, multiplyNumbers));
  

πŸ”Ÿ Real-World Example: Calculator

function calculate(a, b, operation) {
  return operation(a, b);
}

const add = (x, y) => x + y;
const multiply = (x, y) => x * y;

console.log(calculate(5, 3, add));
console.log(calculate(5, 3, multiply));
  

Real-World Example: Login Check

function login(username, password) {
  if (username === "admin" && password === "1234") {
    return "Login Successful";
  }
  return "Login Failed";
}

console.log(login("admin", "1234"));
console.log(login("user", "0000"));
  

1️⃣1️⃣ Functions with Arrays

function printItems(arr) {
  for (let item of arr) {
    console.log(item);
  }
}

printItems(["HTML", "CSS", "JavaScript"]);
  

1️⃣2️⃣ Functions with Objects

function showUser(user) {
  console.log("Name:", user.name);
  console.log("Age:", user.age);
}

showUser({ name: "Nafees", age: 22 });
  

βœ… Summary

  • Functions group reusable logic
  • Function declaration is hoisted
  • Arrow functions are modern and concise
  • Parameters receive values
  • Return sends data back
  • Callbacks enable advanced logic
πŸš€ Mastering functions is mandatory before learning DOM manipulation, events, and async JavaScript.

Objects

In JavaScript, an object is a collection of related data and functionality stored as key–value pairs. Objects are used to represent real-world entities like users, products, cars, students, etc.

πŸ“Œ Objects are one of the MOST important concepts in JavaScript. Almost everything in JavaScript is an object.

1️⃣ Creating a Basic Object

Objects are created using curly braces { }.

let person = {
  name: "Alice",
  age: 25,
  city: "London"
};

console.log(person);
  

2️⃣ Accessing Object Properties

You can access properties in two ways:

Dot Notation

console.log(person.name);
console.log(person.age);
  

Bracket Notation

console.log(person["city"]);
  
βœ” Use bracket notation when the property name is dynamic or stored in a variable.

3️⃣ Adding & Updating Properties

person.age = 26;            // update
person.country = "UK";     // add new property

console.log(person);
  

4️⃣ Deleting a Property

delete person.city;
console.log(person);
  

5️⃣ Object Methods

When a function is stored inside an object, it is called a method.

let user = {
  name: "Bob",
  greet: function () {
    console.log("Hello " + this.name);
  }
};

user.greet();
  
this refers to the current object.

6️⃣ Understanding the this Keyword

let car = {
  brand: "BMW",
  model: "X5",
  info: function () {
    return this.brand + " " + this.model;
  }
};

console.log(car.info());
  

7️⃣ Nested Objects

let student = {
  name: "Nafees",
  marks: {
    math: 85,
    science: 90
  }
};

console.log(student.marks.math);
  

8️⃣ Looping Through an Object

let product = {
  name: "Laptop",
  price: 50000,
  brand: "HP"
};

for (let key in product) {
  console.log(key + ": " + product[key]);
}
  

9️⃣ Objects with External Functions

function displayUser(user) {
  console.log("Name:", user.name);
  console.log("Age:", user.age);
}

displayUser({ name: "Aman", age: 23 });
  

πŸ”Ÿ Array of Objects (Very Important)

let users = [
  { name: "Ali", age: 20 },
  { name: "Sara", age: 22 },
  { name: "John", age: 25 }
];

users.forEach(user => {
  console.log(user.name, user.age);
});
  

1️⃣1️⃣ Object Destructuring (ES6)

let employee = {
  id: 101,
  role: "Developer",
  salary: 60000
};

let { role, salary } = employee;
console.log(role);
console.log(salary);
  

1️⃣2️⃣ Useful Object Methods

let keys = Object.keys(employee);
let values = Object.values(employee);
let entries = Object.entries(employee);

console.log(keys);
console.log(values);
console.log(entries);
  

1️⃣3️⃣ Real-World Example: User Profile

let profile = {
  username: "technacode",
  isLoggedIn: true,
  login() {
    console.log("User logged in");
  },
  logout() {
    console.log("User logged out");
  }
};

if (profile.isLoggedIn) {
  profile.logout();
}
  

πŸ“ Practice Tasks

  • Create an object for a book
  • Create an array of student objects
  • Loop through object and print values
  • Add a method to calculate total marks
  • Use destructuring on an object
πŸš€ Mastering objects will make learning APIs, JSON, frameworks, and backend development much easier.

Arrays

An array is a data structure used to store multiple values in a single variable. Arrays are ordered, zero-indexed, and can hold any data type.

πŸ“Œ Arrays are widely used to store lists like users, products, marks, messages, and API data.

1️⃣ Creating an Array

let fruits = ["apple", "banana", "orange"];
console.log(fruits);
  

Array index starts from 0.

console.log(fruits[0]); // apple
console.log(fruits[2]); // orange
  

2️⃣ Updating Array Elements

fruits[1] = "mango";
console.log(fruits);
  

3️⃣ Array Length

console.log(fruits.length);
  

4️⃣ push() and pop()

push() adds an element to the end pop() removes the last element

fruits.push("grape");
console.log(fruits);

fruits.pop();
console.log(fruits);
  

5️⃣ shift() and unshift()

unshift() adds to start shift() removes from start

fruits.unshift("kiwi");
console.log(fruits);

fruits.shift();
console.log(fruits);
  

6️⃣ Looping Through an Array

Using for Loop

for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}
  

Using for...of Loop

for (let fruit of fruits) {
  console.log(fruit);
}
  

7️⃣ forEach() Method

fruits.forEach(function(fruit) {
  console.log(fruit);
});
  
fruits.forEach(fruit => console.log(fruit));
  

8️⃣ map() Method

map() creates a new array by transforming each element.

let upperFruits = fruits.map(fruit => fruit.toUpperCase());
console.log(upperFruits);
  

9️⃣ filter() Method

let numbers = [10, 25, 40, 15, 5];

let filteredNumbers = numbers.filter(num => num > 20);
console.log(filteredNumbers);
  

πŸ”Ÿ reduce() Method

let prices = [100, 200, 300];

let total = prices.reduce((sum, price) => sum + price, 0);
console.log(total);
  

1️⃣1️⃣ find() Method

let result = numbers.find(num => num > 20);
console.log(result);
  

1️⃣2️⃣ includes()

console.log(fruits.includes("apple"));
console.log(fruits.includes("papaya"));
  

1️⃣3️⃣ sort()

let scores = [40, 10, 100, 25];
scores.sort((a, b) => a - b);
console.log(scores);
  

1️⃣4️⃣ splice()

fruits.splice(1, 1, "pineapple");
console.log(fruits);
  

1️⃣5️⃣ slice()

let newFruits = fruits.slice(0, 2);
console.log(newFruits);
  

1️⃣6️⃣ Array of Objects (Very Important)

let students = [
  { name: "Ali", marks: 80 },
  { name: "Sara", marks: 90 },
  { name: "John", marks: 70 }
];

students.forEach(student => {
  console.log(student.name, student.marks);
});
  

1️⃣7️⃣ Real-World Example: Shopping Cart

let cart = [200, 450, 300];

let cartTotal = cart.reduce((sum, item) => sum + item, 0);
console.log("Total Price:", cartTotal);
  

πŸ“ Practice Tasks

  • Create an array of numbers and find the sum
  • Filter even numbers from an array
  • Convert all strings to uppercase using map()
  • Find the highest number in an array
  • Create an array of users and print their names
πŸš€ Mastering arrays is essential for DOM manipulation, API handling, and JavaScript frameworks.

DOM Manipulation in JavaScript

The DOM (Document Object Model) represents the structure of an HTML document as a tree of objects. JavaScript can use the DOM to read, change, add, or remove HTML elements dynamically.

πŸ“Œ DOM manipulation is the core of interactive websites. Buttons, forms, popups, animations, and dynamic content all depend on the DOM.

1️⃣ Selecting Elements from the DOM

JavaScript provides multiple ways to select HTML elements.

getElementById

const title = document.getElementById("title");
console.log(title);
  

querySelector

const heading = document.querySelector("h1");
const card = document.querySelector(".card");
  

querySelectorAll

const items = document.querySelectorAll("li");
console.log(items);
  
βœ” querySelector returns the first match βœ” querySelectorAll returns a NodeList

2️⃣ Changing Text Content

const h1 = document.querySelector("h1");

h1.textContent = "Hello JavaScript";
h1.innerHTML = "Welcome to JS";
  
⚠ Use innerHTML carefully to avoid security issues.

3️⃣ Changing Styles Using JavaScript

const box = document.querySelector(".card");

box.style.backgroundColor = "#fff7cc";
box.style.borderRadius = "12px";
box.style.padding = "20px";
  

4️⃣ Working with CSS Classes

const element = document.querySelector(".card");

element.classList.add("active");
element.classList.remove("active");
element.classList.toggle("active");
  

5️⃣ Working with Attributes

const img = document.querySelector("img");

img.setAttribute("alt", "JavaScript Logo");
console.log(img.getAttribute("src"));
img.removeAttribute("width");
  

6️⃣ Event Handling (Very Important)

Events allow JavaScript to respond to user actions like clicks, typing, hovering, etc.

const btn = document.getElementById("btn");

btn.addEventListener("click", () => {
  alert("Button clicked!");
});
  

Mouse & Keyboard Events

btn.addEventListener("mouseover", () => {
  console.log("Mouse over button");
});

document.addEventListener("keydown", (event) => {
  console.log("Key pressed:", event.key);
});
  

7️⃣ Creating & Adding Elements

const list = document.querySelector("ul");
const newItem = document.createElement("li");

newItem.textContent = "New Item";
list.appendChild(newItem);
  

8️⃣ Removing Elements

const removeItem = document.querySelector(".remove");
removeItem.remove();
  

9️⃣ Looping Through DOM Elements

const buttons = document.querySelectorAll("button");

buttons.forEach(btn => {
  btn.addEventListener("click", () => {
    console.log("Button clicked");
  });
});
  

πŸ”Ÿ Form Handling with DOM

const form = document.querySelector("form");

form.addEventListener("submit", (e) => {
  e.preventDefault();

  const name = document.getElementById("name").value;
  console.log("User Name:", name);
});
  

1️⃣1️⃣ Real-World Example: Theme Toggle

const toggleBtn = document.getElementById("toggle");

toggleBtn.addEventListener("click", () => {
  document.body.classList.toggle("dark-mode");
});
  

1️⃣2️⃣ DOMContentLoaded Event

document.addEventListener("DOMContentLoaded", () => {
  console.log("DOM fully loaded");
});
  

πŸ“ Practice Tasks

  • Change text on button click
  • Create a list dynamically using JavaScript
  • Toggle dark/light theme
  • Validate form input using DOM
  • Show/hide elements on click
πŸš€ DOM mastery is essential for React, Vue, Angular, and real-world JavaScript applications.

Events in JavaScript

In JavaScript, an event is an action performed by the user or the browser, such as clicking a button, typing on the keyboard, submitting a form, or loading a page.

πŸ“Œ Events make websites interactive. Without events, JavaScript would not be able to respond to user actions.

1️⃣ What is an Event?

Examples of common events:

  • Mouse click
  • Mouse hover
  • Key press
  • Form submit
  • Page load

2️⃣ addEventListener()

The addEventListener() method attaches an event handler to an element.

const btn = document.getElementById("btn");

btn.addEventListener("click", () => {
  console.log("Button clicked");
});
  

3️⃣ Mouse Events

const box = document.querySelector(".box");

box.addEventListener("click", () => {
  console.log("Box clicked");
});

box.addEventListener("mouseover", () => {
  console.log("Mouse over box");
});

box.addEventListener("mouseout", () => {
  console.log("Mouse left box");
});
  
βœ” click β†’ mouse click βœ” mouseover β†’ cursor enters element βœ” mouseout β†’ cursor leaves element

4️⃣ Keyboard Events

document.addEventListener("keydown", (event) => {
  console.log("Key pressed:", event.key);
});

document.addEventListener("keyup", () => {
  console.log("Key released");
});
  

5️⃣ Form Events

const form = document.querySelector("form");

form.addEventListener("submit", (e) => {
  e.preventDefault();
  console.log("Form submitted");
});
  
const input = document.getElementById("username");

input.addEventListener("input", () => {
  console.log("User typing...");
});
  

6️⃣ Event Object

The event object contains details about the event.

document.addEventListener("click", (event) => {
  console.log(event.target);
  console.log(event.type);
});
  

7️⃣ Using this in Events

const button = document.querySelector(".myBtn");

button.addEventListener("click", function () {
  this.style.backgroundColor = "green";
});
  

8️⃣ Multiple Events on One Element

const card = document.querySelector(".card");

card.addEventListener("mouseenter", () => {
  console.log("Mouse entered");
});

card.addEventListener("mouseleave", () => {
  console.log("Mouse left");
});
  

9️⃣ Event Delegation (Advanced & Important)

Event delegation allows handling events on multiple child elements using a single parent element.

const list = document.querySelector("ul");

list.addEventListener("click", (e) => {
  if (e.target.tagName === "LI") {
    console.log("Clicked item:", e.target.textContent);
  }
});
  

πŸ”Ÿ Removing an Event Listener

function sayHello() {
  console.log("Hello!");
}

btn.addEventListener("click", sayHello);
btn.removeEventListener("click", sayHello);
  

1️⃣1️⃣ Page Load Events

window.addEventListener("load", () => {
  console.log("Page fully loaded");
});

document.addEventListener("DOMContentLoaded", () => {
  console.log("HTML loaded");
});
  

1️⃣2️⃣ Real-World Example: Button Counter

let count = 0;
const counterBtn = document.getElementById("counter");

counterBtn.addEventListener("click", () => {
  count++;
  console.log("Clicked:", count);
});
  

πŸ“ Practice Tasks

  • Change text on button click
  • Show alert on mouse hover
  • Detect key presses
  • Validate form on submit
  • Create a click counter
πŸš€ Mastering events is essential for DOM manipulation, animations, forms, games, and modern JavaScript frameworks.

ES6+ JavaScript Features (Modern JavaScript)

ES6 (ECMAScript 2015) and later versions introduced powerful features that make JavaScript cleaner, shorter, faster, and easier to read. Modern JavaScript development heavily relies on ES6+ features.

πŸš€ ES6+ is used in modern frameworks like React, Vue, Angular, and Node.js.

1️⃣ Template Literals

Template literals use backticks (`) and allow string interpolation and multi-line strings.

let name = "Alice";
let age = 22;

let message = `Hello ${name}, you are ${age} years old.`;
console.log(message);
  
let multiLine = `
This is line one
This is line two
This is line three
`;
console.log(multiLine);
  

2️⃣ Destructuring (Arrays & Objects)

Array Destructuring

let colors = ["red", "green", "blue"];

let [first, second] = colors;
console.log(first);  // red
console.log(second); // green
  

Object Destructuring

let user = {
  username: "john_doe",
  email: "john@gmail.com",
  age: 25
};

let { username, age } = user;
console.log(username);
console.log(age);
  

3️⃣ Default Parameters

Default parameters allow function parameters to have default values if no argument is passed.

function greet(name = "Guest") {
  console.log(`Welcome ${name}`);
}

greet("Rahul");
greet();
  

4️⃣ Arrow Functions

Arrow functions provide a shorter syntax and do not bind their own this.

const add = (a, b) => a + b;
console.log(add(5, 3));
  
const square = x => x * x;
console.log(square(4));
  

5️⃣ Spread Operator (...)

The spread operator expands elements of an array or object.

With Arrays

let arr1 = [1, 2, 3];
let arr2 = [...arr1, 4, 5];

console.log(arr2);
  

With Objects

let user1 = { name: "Alex", age: 20 };
let user2 = { ...user1, city: "Delhi" };

console.log(user2);
  

6️⃣ Rest Operator (...)

The rest operator collects multiple values into an array.

function sum(...numbers) {
  return numbers.reduce((total, n) => total + n, 0);
}

console.log(sum(1, 2, 3, 4));
  

7️⃣ let and const

let and const provide block-scoped variables.

let count = 10;
count = 20;

const PI = 3.14;
// PI = 4; ❌ Error
  

8️⃣ Classes

Classes are a cleaner way to create objects and handle inheritance.

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  greet() {
    console.log(`Hello, my name is ${this.name}`);
  }
}

let p1 = new Person("Aman", 23);
p1.greet();
  

9️⃣ JavaScript Modules (export / import)

Modules allow splitting code into reusable files.

Export (math.js)

export function add(a, b) {
  return a + b;
}

export const PI = 3.14;
  

Import (main.js)

import { add, PI } from "./math.js";

console.log(add(2, 3));
console.log(PI);
  

πŸ”Ÿ Optional Chaining (?.)

Prevents errors when accessing nested properties.

let userData = {};

console.log(userData.profile?.name);
  

πŸ“ Practice Tasks

  • Create a function using default parameters
  • Use destructuring on an API response object
  • Merge two arrays using spread operator
  • Build a class for Student
  • Create and import a module
βœ… Mastering ES6+ is essential for writing clean, professional, and modern JavaScript code.

Asynchronous JavaScript

Asynchronous JavaScript allows code to run without blocking the execution of other tasks. This is important for handling time-consuming operations like API calls, timers, file loading, and user interactions.

⏳ JavaScript is single-threaded, but async programming makes it appear multi-threaded by using callbacks, promises, and async/await.

1️⃣ Synchronous vs Asynchronous

Synchronous Code (Blocking)

console.log("Start");
console.log("Middle");
console.log("End");
  

Asynchronous Code (Non-Blocking)

console.log("Start");

setTimeout(() => {
  console.log("Async Task");
}, 2000);

console.log("End");
  
Output order will be: Start β†’ End β†’ Async Task

2️⃣ setTimeout()

setTimeout() executes a function after a specified delay.

setTimeout(() => {
  console.log("Executed after 1 second");
}, 1000);
  

Cancel setTimeout

let timer = setTimeout(() => {
  console.log("Will not run");
}, 2000);

clearTimeout(timer);
  

3️⃣ setInterval()

setInterval() repeatedly executes code at fixed time intervals.

let count = 0;

let intervalId = setInterval(() => {
  count++;
  console.log("Count:", count);

  if (count === 5) {
    clearInterval(intervalId);
  }
}, 1000);
  

4️⃣ Callbacks

A callback is a function passed as an argument to be executed later.

function fetchData(callback) {
  setTimeout(() => {
    callback("Data received");
  }, 1000);
}

fetchData((data) => {
  console.log(data);
});
  
❌ Too many callbacks can cause callback hell.

5️⃣ Promises

A Promise represents a value that will be available in the future.

const promise = new Promise((resolve, reject) => {
  let success = true;

  setTimeout(() => {
    if (success) {
      resolve("Task completed");
    } else {
      reject("Task failed");
    }
  }, 1000);
});

promise
  .then(result => console.log(result))
  .catch(error => console.log(error));
  

Promise States

  • Pending
  • Fulfilled
  • Rejected

6️⃣ Promise Chaining

new Promise(resolve => resolve(5))
  .then(num => num * 2)
  .then(result => console.log(result));
  

7️⃣ async / await

async/await makes asynchronous code look like synchronous code.

function getData() {
  return new Promise(resolve => {
    setTimeout(() => resolve("Data loaded"), 1000);
  });
}

async function showData() {
  const result = await getData();
  console.log(result);
}

showData();
  
βœ” Cleaner than promises βœ” Easier to read & debug

8️⃣ Error Handling with try...catch

async function loadData() {
  try {
    let response = await Promise.reject("Network Error");
    console.log(response);
  } catch (error) {
    console.log("Error:", error);
  }
}

loadData();
  

9️⃣ Promise.all()

Runs multiple promises in parallel.

let p1 = Promise.resolve(10);
let p2 = Promise.resolve(20);

Promise.all([p1, p2]).then(values => {
  console.log(values);
});
  

πŸ”Ÿ Real-World Example: Fake API Call

function fakeApi() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve({ user: "Admin", role: "Manager" });
    }, 1500);
  });
}

async function login() {
  let data = await fakeApi();
  console.log("Welcome", data.user);
}

login();
  

πŸ“ Practice Tasks

  • Create a countdown using setInterval
  • Convert a callback to a promise
  • Handle errors using try/catch
  • Fetch data using async/await
  • Run multiple promises using Promise.all
πŸš€ Asynchronous JavaScript is essential for APIs, databases, animations, and modern web apps.