J

JavaScript Handbook

Clean • Professional

JavaScript Basics Cheatsheet (Beginner-Friendly Guide)

48 minute

JavaScript Basics Cheatsheet (Beginner-Friendly Guide)

JavaScript is the world’s most popular programming language for building interactive websites.

This cheatsheet is a quick reference guide to help beginners learn syntax, statements, comments, and output methods.

1. JavaScript Basics

JavaScript (What is JavaScript?)

JavaScript (JS) is a lightweight, interpreted programming language used to:

  • Make web pages dynamic (forms, sliders, popups).
  • Build backend apps (Node.js).
  • Create mobile and desktop apps.

JavaScript Introduction

  • JS is case-sensitive (let xLet x).
  • Statements end with a ; (optional but recommended).
  • Code is executed from top to bottom.

Example:

let name = "John";
console.log("Hello " + name);

Where To Place JavaScript (Embedding JS)

MethodExampleUsage
Inline JS<button onclick="alert('Hi!')">Click</button>Small scripts
Internal JS<script>console.log("Hello JS")</script>Inside HTML <head> or <body>
External JS<script src="app.js"></script>Recommended (clean, reusable)

JavaScript Output Methods

MethodExampleUse Case
console.log()console.log("Debug");Debugging in browser console
alert()alert("Welcome!");Popup notifications
document.write()document.write("Hello World");Writing directly to the page (not recommended)

JavaScript Syntax

  • Variables: let, const, var
  • Case-sensitive: Namename
  • Semicolon: Optional, but best practice to use.

Example:

let age = 25;   // variable
const pi = 3.14; // constant
var city = "Delhi"; // old way (avoid in modern JS)

JavaScript Statements

Statements are instructions for the browser.

  • Can be simple (let x = 10;)
  • Or compound (loops, if-else).

Example:

let x = 5;
let y = 10;
let z = x + y; // statement

JavaScript Comments

  • Single-line comment// This is a comment
  • Multi-line comment
/*
This is a
multi-line comment
*/

2. JavaScript Variables & Constants

Variables in JavaScript are containers for storing data.

You can declare variables using var, let, or const depending on your use case.


JavaScript Variables (var, let, const)

KeywordScopeReassign?HoistingBest Use
varFunction scopeYesHoisted (initialized as undefined)Legacy code
letBlock scopeYesHoisted (but not initialized)Modern variable
constBlock scopeNoHoisted (but not initialized)Fixed values

Example:

var city = "Delhi";     // Function-scoped
let age = 25;           // Block-scoped
const pi = 3.1416;      // Constant (cannot be reassigned)

JavaScript Let

  • Introduced in ES6 (2015).
  • Block-scoped → only available inside {}.
  • Can be reassigned, but not redeclared in the same scope.

Example:

let x = 10;
x = 20; //  allowed
let x = 30; // error (cannot redeclare in same scope)

JavaScript Const

  • Block-scoped like let.
  • Cannot be reassigned.
  • Must be initialized at declaration.

Example:

const country = "India";
country = "USA"; //  error (cannot reassign)

Objects and arrays declared with const can be modified, but not reassigned:

const arr = [1, 2, 3];
arr.push(4); //  allowed
arr = [5, 6]; //  error

JavaScript Scope (Local, Global, Block)

TypeExampleAccessible From
Global Scopevar a = 10;Anywhere in code
Local Scope (Function)Declared inside functionOnly inside that function
Block Scopelet or const inside {}Only inside that block

Example:

let globalVar = "I am Global";

function testScope() {
  let localVar = "I am Local";
  console.log(globalVar); // 
  console.log(localVar);  // 
}

console.log(globalVar);   // 
console.log(localVar);    // error

JavaScript Hoisting

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

  • var → Hoisted as undefined.
  • let & const → Hoisted, but not initialized (they are in a Temporal Dead Zone).

Example with var:

console.log(a); // undefined (hoisted)
var a = 10;

Example with let:

console.log(b); // ReferenceError (TDZ)
let b = 20;

3. JavaScript Operators

Operators in JavaScript are symbols that perform actions on values or variables.

They are used for assignments, comparisons, arithmetic, logic, and more.

JS Operators Overview

JavaScript has several categories of operators:

  • Assignment Operators (=, +=, -=, …)
  • Arithmetic Operators (+, -, *, /, …)
  • Comparison Operators (==, ===, !=, >, <, …)
  • Logical Operators (&&, ||, !)
  • Bitwise Operators (&, |, ^, ~, <<, >>, >>>)
  • Others: typeof, instanceof, ternary ? :

Assignment Operators

Assignment operators are used to assign values to variables.

OperatorMeaningExampleResult
=Assignx = 10x = 10
+=Add and assignx += 5x = x + 5
-=Subtract and assignx -= 3x = x - 3
*=Multiply and assignx *= 2x = x * 2
/=Divide and assignx /= 4x = x / 4
%=Modulus and assignx %= 4x = x % 4
**=Exponent and assignx **= 3x = x ** 3

Example:

let a = 10;
a += 5; // 15
a *= 2; // 30

Arithmetic Operators

Used to perform mathematical operations.

OperatorExampleResult
+5 + 27
-5 - 23
*5 * 210
/5 / 22.5
%5 % 21 (remainder)
**2 ** 38 (power)
++x++Increment by 1
--x--Decrement by 1

Example:

let x = 10;
console.log(x++); // 10 (post-increment)
console.log(++x); // 12 (pre-increment)
  • Post-increment (x++) → Uses the current value first, then increases it by 1.
  • Pre-increment (++x) → Increases the value by 1 first, then uses the new value.

Comparison Operators

Used to compare values and return true or false.

OperatorExampleResult
==5 == "5"true (checks value only)
===5 === "5"false (checks value + type)
!=5 != "5"false
!==5 !== "5"true
>10 > 5true
<10 < 5false
>=5 >= 5true
<=3 <= 5true

Example:

let age = 18;
console.log(age >= 18); // true

Logical Operators

Used to combine conditions.

OperatorExampleMeaning
&& (AND)(x > 5 && y < 10)true if both are true
` ` (OR)
! (NOT)!(x > 5)Reverses the result

Example:

let age = 20;
if (age > 18 && age < 30) {
  console.log("Valid age");
}

Bitwise Operators

Operate on binary values (0s and 1s).

OperatorExampleResult (Binary)
& (AND)5 & 11
`` (OR)`5
^ (XOR)5 ^ 14
~ (NOT)~5-6
<< (Left Shift)5 << 110
>> (Right Shift)5 >> 12
>>> (Unsigned Right Shift)-5 >>> 1A large positive number

Example:

console.log(5 & 1);  // 1
console.log(5 | 1);  // 5
console.log(5 ^ 1);  // 4

Operator Precedence

Determines the order of execution when multiple operators are used.

Highest → Lowest order:

  1. () → Parentheses
  2. ++, - → Increment/Decrement
  3. * → Exponentiation
  4. , /, % → Multiplication, Division, Modulus
  5. +, → Addition, Subtraction
  6. <, >, <=, >= → Comparisons
  7. ==, ===, !=, !== → Equality
  8. && → Logical AND
  9. || → Logical OR
  10. = → Assignment

Example:

let result = 5 + 3 * 2; // 5 + (3*2) = 11

4. JavaScript Data Types

JavaScript variables can hold different data types: numbers, strings, arrays, objects, booleans, etc. Unlike other languages, JavaScript is dynamically typed→ you don’t need to declare a type. JavaScript has two main categories of data types:

1. Primitive Data Types

  • Stored directly in the stack (fixed memory).
  • Immutable (cannot be changed, only replaced).
  • Compared by value.

Includes: String, Number, BigInt, Boolean, Undefined, Null, Symbol

2. Non-Primitive (Reference) Data Types

  • Stored in the heap (dynamic memory).
  • Mutable (can be updated or modified).
  • Compared by reference (memory address).

Includes: Object, Array, Date, Function

Primitive Data Types

String

Strings are text values wrapped in quotes.

let str1 = "Hello";
let str2 = 'World';
let str3 = `Template`;

String Methods

  • .length, .toUpperCase(), .toLowerCase(), .slice(), .replace(), .trim()
  • .indexOf(), .includes(), .startsWith(), .endsWith()
MethodExampleResult
.length"Hello".length5
.toUpperCase()"hi".toUpperCase()"HI"
.toLowerCase()"HI".toLowerCase()"hi"
.trim()" JS ".trim()"JS"
.slice(0,3)"Hello".slice(0,3)"Hel"
.replace("JS","JavaScript")"I love JS".replace("JS","JavaScript")"I love JavaScript"

Example:

"JavaScript".includes("Script"); // true

➝ String Search

  • .indexOf("text") → Finds position.
  • .includes("word") → Returns true/false.
  • .startsWith("prefix") → Checks beginning.
  • .endsWith("suffix") → Checks ending.

Example:

"JavaScript".includes("Script"); // true

String Templates

Use backticks (``) with ${} for variables.

let name = "John";
console.log(`Hello, ${name}!`);

Number

All integers and floating-point values.

let x = 10;
let y = 10.5;
let z = 1e6;

➝ Number Methods

MethodExampleResult
.toString()(10).toString()"10"
.toFixed(2)(3.1416).toFixed(2)"3.14"
.toPrecision(3)(3.1416).toPrecision(3)"3.14"
Number("5")Number("5")5

➝ Number Properties

  • Number.MAX_VALUE → Largest number.
  • Number.MIN_VALUE → Smallest number.
  • Number.POSITIVE_INFINITY → Infinity.
  • Number.NaN → Not a Number.

Math & Random

JavaScript has a built-in Math object.

MethodDescriptionExample
Math.PIReturns the value of π3.14159
Math.EReturns Euler’s number e2.718
Math.sqrt(x)Returns square root of xMath.sqrt(9) → 3
Math.pow(x, y)Returns x raised to the power yMath.pow(2,3) → 8
Math.abs(x)Returns absolute value of xMath.abs(-5) → 5
Math.round(x)Rounds to nearest integerMath.round(4.6) → 5
Math.floor(x)Rounds downMath.floor(4.9) → 4
Math.ceil(x)Rounds upMath.ceil(4.1) → 5
Math.random()Returns random number 0 ≤ x < 1Math.random() → 0.234
Math.floor(Math.random()*n)Random integer 0 to n-10–9

Random Numbers:

Math.random();        // 0 to <1
Math.floor(Math.random() * 10); // 0 to 9

BigInt

Used for very large integers.

let big = 123456789012345678901234567890n;

Boolean

Boolean has two values: true or false.

let isOnline = true;
let isLoggedIn = false;

Null vs Undefined

  • null → intentional empty value.
  • undefined → declared but not assigned.
let a;          // undefined
let b = null;   // null

typeof

Checks data type of a value.

typeof "Hello"; // "string"
typeof 123;     // "number"
typeof null;    // "object" (special case)
typeof [];      // "object"

Type Conversion

Implicit (Type Coercion)

JavaScript automatically converts data types during operations.

"5" + 2; // "52"
"5" - 2; // 3

Explicit

Developer manually converts data type using functions.

Number("123");   // 123
String(123);     // "123"
Boolean(0);      // false

toString()

Converts a value to string.

let num = 10;
num.toString(); // "10"

Non-Primitive (Reference) Data Types

Object

Collection of key–value pairs.

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

Arrays

Arrays hold multiple values in one variable.

let fruits = ["Apple", "Banana", "Mango"];

➝ Array Methods

MethodExampleResult
.push("Orange")Adds at end["Apple","Banana","Mango","Orange"]
.pop()Removes last["Apple","Banana"]
.shift()Removes first["Banana","Mango"]
.unshift("Kiwi")Adds at start["Kiwi","Apple","Banana"]
.concat()Combines arrays 
.join(",")"Apple,Banana,Mango" 

➝ Array Search

  • .indexOf("Banana") → 1
  • .includes("Apple") → true
  • .find(x => x > 10) → First match

➝ Array Sort

let nums = [40, 100, 1, 5];
nums.sort();        // [1,100,40,5] (wrong for numbers)
nums.sort((a,b)=>a-b); // [1,5,40,100]

➝ Array Iteration Methods

  • .forEach(fn) → Loops through array.
  • .map(fn) → Returns new array.
  • .filter(fn) → Returns elements that match condition.
  • .reduce(fn) → Reduces array to single value.

Example:

let arr = [1,2,3,4];
let doubled = arr.map(x => x*2); // [2,4,6,8]

➝ Array Const

You can declare arrays with const, but you can modify elements.

const cars = ["BMW","Audi"];
cars[0] = "Tesla"; // allowed
cars = ["Honda"];  //  error

Dates

JavaScript Date object handles time and date.

let d = new Date();
console.log(d.toDateString());

➝ Date Formats

  • "2025-09-03" → ISO format.
  • "09/03/2025" → Short date.
  • "September 3, 2025" → Long date.

➝ Date Get Methods

  • getFullYear() → Year
  • getMonth() → Month (0–11)
  • getDate() → Day of month
  • getDay() → Weekday

➝ Date Set Methods

  • setFullYear(2030)
  • setMonth(11)
  • setDate(25)
  • Get Methods: getDate(), getMonth(), getDay()
  • Set Methods: setDate(), setMonth(), setFullYear()

Function

Functions are objects in JS.

function greet() {
  return "Hello";
}

5. JavaScript Control Flow

Control flow defines the order in which code executes. It helps you make decisions and repeat actions based on conditions.

If…Else

The if…else statement allows you to execute a block of code if a condition is true, and another block if it’s false. It supports multiple else if conditions.

let age = 18;

if (age >= 18) {
  console.log("You are an adult.");
} else {
  console.log("You are a minor.");
}

Switch

The switch statement is used when you have many possible conditions. Instead of writing multiple if...else, you can use case values inside a switch.

let day = 2;

switch(day) {
  case 1: console.log("Monday"); break;
  case 2: console.log("Tuesday"); break;
  case 3: console.log("Wednesday"); break;
  default: console.log("Invalid day");
}

Loops

Loops are used to repeat a block of code multiple times until a condition is false.

➝ for Loop

The for loop runs a block of code a fixed number of times, using a counter variable.

for (let i = 0; i < 5; i++) {
  console.log(i);
}

➝ while Loop

The while loop keeps running as long as the condition is true.

let i = 0;
while (i < 5) {
  console.log(i);
  i++;
}

➝ do…while Loop

The do…while loop always executes at least once, then checks the condition for further execution.

let i = 0;
do {
  console.log(i);
  i++;
} while (i < 5);

➝ for…in Loop

The for…in loop is used to iterate over the keys (properties) of an object.

let person = {name: "John", age: 25};

for (let key in person) {
  console.log(key, person[key]);
}

➝ for…of Loop

The for…of loop is used to iterate over values of an iterable (like arrays or strings).

let fruits = ["Apple", "Banana", "Mango"];

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

Break & Continue

  • break → Immediately stops the loop.
  • continue → Skips the current iteration and goes to the next one.
for (let i = 0; i < 5; i++) {
  if (i === 3) break;
  console.log(i);
}
// 0 1 2
for (let i = 0; i < 5; i++) {
  if (i === 3) continue;
  console.log(i);
}
// 0 1 2 4

Code Blocks

A code block { } groups multiple statements together so they run as a unit.

{
  let x = 10;
  let y = 20;
  console.log(x + y); // 30
}

6. JavaScript Functions

Functions in JavaScript are blocks of code designed to perform specific tasks. They make code reusable, organized, and easy to maintain.

Function Definitions

Functions can be defined using the function keyword.

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

Call it with:

greet(); // Hello World!

Function Parameters & Arguments

  • Parameters → placeholders in the function definition.
  • Arguments → actual values passed when calling the function.
function add(a, b) {  // parameters
  return a + b;
}
console.log(add(5, 3)); // arguments → 5, 3

Default Parameters

If no argument is passed, default values are used.

function greet(name = "Guest") {
  console.log("Hello " + name);
}
greet();       // Hello Guest
greet("John"); // Hello John

Rest & Spread Operators

Rest (...) → Collects multiple arguments into an array.

function sum(...nums) {
  return nums.reduce((a, b) => a + b, 0);
}
console.log(sum(1, 2, 3, 4)); // 10

Spread (...) → Expands an array into individual elements.

let arr = [1, 2, 3];
console.log(Math.max(...arr)); // 3

Function Invocation

A function runs when it is invoked (called).

function greet() {
  return "Hello!";
}
console.log(greet()); // Function invoked

Functions can also be invoked automatically with IIFE (Immediately Invoked Function Expression):

(function() {
  console.log("IIFE runs immediately!");
})();

Arrow Functions

Shorter syntax for writing functions. They don’t bind their own this.

const add = (a, b) => a + b;
console.log(add(5, 3)); // 8

Function Expressions

Functions can be stored inside variables.

const multiply = function(x, y) {
  return x * y;
};
console.log(multiply(4, 5)); // 20

Anonymous Functions

Functions without a name, often used as callbacks.

setTimeout(function() {
  console.log("Hello after 2 seconds");
}, 2000);

Function Scope & Closures

  • Function Scope: Variables declared inside a function cannot be accessed outside.
  • Closure: A function can access variables from its outer scope even after the outer function has finished.
function outer() {
  let count = 0;
  function inner() {
    count++;
    return count;
  }
  return inner;
}
let counter = outer();
console.log(counter()); // 1
console.log(counter()); // 2

Function this Keyword

  • In a regular function, this refers to the object that called the function.
  • In an arrow function, this refers to the parent scope.
const person = {
  name: "Alice",
  greet: function() {
    console.log("Hello, " + this.name);
  }
};
person.greet(); // Hello, Alice

Call, Apply, Bind

These methods control the value of this.

  • call() → Invokes a function with arguments separated by commas.
  • apply() → Invokes a function with arguments as an array.
  • bind() → Returns a new function with this permanently set.
function greet(city, country) {
  console.log(this.name + " from " + city + ", " + country);
}

let person = { name: "John" };

greet.call(person, "Paris", "France");
greet.apply(person, ["Berlin", "Germany"]);
let boundGreet = greet.bind(person, "Rome", "Italy");
boundGreet();

Recursion

A function that calls itself until a condition is met.

function factorial(n) {
  if (n === 0) return 1;
  return n * factorial(n - 1);
}
console.log(factorial(5)); // 120

7. JavaScript Objects

Objects in JavaScript are collections of key–value pairs used to store related data and functionality. They are the backbone of JavaScript programming, as most values in JS are objects (arrays, functions, dates, etc.).

let person = {
  name: "John",
  age: 30,
  greet: function() {
    return "Hello, " + this.name;
  }
};

Object Definitions

Objects can be created in different ways:

Object Literals

The simplest way to create an object using curly braces {} with key–value pairs.

let car = { brand: "Tesla", model: "Model 3" };

Using new Object()

Creates an empty object using the built-in Object constructor, then properties can be added.

let obj = new Object();
obj.name = "Alice";

Using Object.create() (with prototype)

Creates a new object and sets its prototype to an existing object.

let proto = { greet: () => "Hello!" };
let obj = Object.create(proto);
console.log(obj.greet()); // Hello!

Object Properties

Properties are key–value pairs inside objects.

let user = { name: "Alice", age: 25 };

// Access
console.log(user.name);   // Alice
console.log(user["age"]); // 25

// Add new property
user.city = "New York";

// Delete property
delete user.age;

Object Methods

Functions inside objects are called methods.

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

ES6 shorthand:

let user = {
  name: "Bob",
  greet() { return "Hi " + this.name; }
};

Object Display

Console Logging

The console object provides methods to output information to the browser’s developer console (mainly used for debugging).

let obj = { x: 10, y: 20 };
console.log(obj); // { x: 10, y: 20 }

Common Console Methods

console.log() → Print general messages or values.

console.log("Hello, World!");
console.log(5 + 3); // 8

console.error() → Print error messages in red.

console.error("Something went wrong!");

console.warn() → Print warning messages (yellow).

console.warn("This is a warning!");

console.info() → Print informational messages.

console.info("This is some info");

console.table() → Display arrays/objects in a table format.

let users = [
  { name: "Alice", age: 25 },
  { name: "Bob", age: 30 }
];
console.table(users);

console.clear() → Clear the console.

console.clear();

console.time() / console.timeEnd() → Measure execution time.

console.time("Loop");
for (let i = 0; i < 1000000; i++) {}
console.timeEnd("Loop");
// Loop: 3.5ms

JSON.stringify()

Converts object into JSON string.

console.log(JSON.stringify(obj)); // {"x":10,"y":20}

Object Constructors

Used to create multiple similar objects.

function Person(name, age) {
  this.name = name;
  this.age = age;
}
let p1 = new Person("John", 30);
let p2 = new Person("Alice", 25);

Object this

The this keyword refers to the object that owns the method.

let person = {
  name: "John",
  greet: function() {
    return "Hello, " + this.name;
  }
};
console.log(person.greet()); // Hello, John

Note: Arrow functions don’t have their own this.

Object Destructuring

Extract values from objects into variables.

let user = { name: "Eve", age: 28 };
let { name, age } = user;
console.log(name, age); // Eve 28

// Renaming
let { name: userName } = user;
console.log(userName); // Eve

Object Prototypes & Inheritance

Every object in JS has a prototype (except the base Object).

function Person(name) {
  this.name = name;
}
Person.prototype.greet = function() {
  return "Hi " + this.name;
};

let p = new Person("Mike");
console.log(p.greet()); // Hi Mike

Prototype Chain: Person → Object.prototype → null

Object Iterations

Ways to loop over object properties:

let user = { name: "Leo", age: 40 };

// for…in (keys + values)
for (let key in user) console.log(key, user[key]);

// Object.keys()
console.log(Object.keys(user)); // ["name", "age"]

// Object.values()
console.log(Object.values(user)); // ["Leo", 40]

// Object.entries()
console.log(Object.entries(user)); // [["name","Leo"],["age",40]]

// Convert back with Object.fromEntries()
let arr = [["a", 1], ["b", 2]];
let obj = Object.fromEntries(arr);
console.log(obj); // { a: 1, b: 2 }

Object Management

Built-in methods to create, copy, and check objects.

Object.assign() → Copy & Merge

The Object.assign() method is used to copy properties from one or more source objects into a target object, effectively performing a shallow copy or merge of objects.

let obj1 = { a: 1 };
let obj2 = { b: 2 };
let merged = Object.assign({}, obj1, obj2);
console.log(merged); // { a: 1, b: 2 }

Spread Operator (...)

The spread operator (...) is used to unpack elements from arrays or copy/merge properties from objects into another array or object.

let obj1 = { x: 10 };
let obj2 = { y: 20 };
let copy = { ...obj1, ...obj2 };
console.log(copy); // { x: 10, y: 20 }

Object.defineProperty()

Defines a new property or modifies an existing property on an object with specific descriptors (writable, enumerable, configurable).

let user = {};
Object.defineProperty(user, "name", {
  value: "Alice",
  writable: false
});
console.log(user.name); // Alice

Object.defineProperties()

Defines or modifies multiple properties at once on an object.

let car = {};
Object.defineProperties(car, {
  brand: { value: "Tesla" },
  model: { value: "Model 3" }
});
console.log(car.brand, car.model); // Tesla Model 3

Object.hasOwnProperty()

Checks if a property exists directly on the object itself, not inherited from its prototype.

let person = { name: "John" };
console.log(person.hasOwnProperty("name")); // true

Object.getOwnPropertyNames()

Returns an array of all property names (including non-enumerable) directly on the object.

let obj = { x: 10 };
console.log(Object.getOwnPropertyNames(obj)); // ["x"]

Object.getPrototypeOf() / Object.setPrototypeOf()

Object.getPrototypeOf() → Returns the prototype (internal [[Prototype]]) of a given object.

Object.setPrototypeOf() → Sets the prototype of a given object to another object.

let proto = { greet: () => "Hi" };
let obj = {};
Object.setPrototypeOf(obj, proto);
console.log(Object.getPrototypeOf(obj)); // { greet: [Function] }

Object.is()

Compares two values for strict equality, similar to ===, but handles special cases (NaN, +0 vs -0) more accurately.

console.log(Object.is(NaN, NaN)); // true
console.log(Object.is(0, -0));    // false

Object Getters & Setters

Control access to object properties.

let person = {
  firstName: "John",
  lastName: "Doe",
  get fullName() {
    return this.firstName + " " + this.lastName;
  },
  set fullName(name) {
    [this.firstName, this.lastName] = name.split(" ");
  }
};

console.log(person.fullName); // John Doe
person.fullName = "Jane Smith";
console.log(person.firstName); // Jane

Object Protection

Object.freeze()

Makes an object immutable (no adding, removing, or modifying properties).

let obj = { a: 1 };
Object.freeze(obj);
obj.a = 2; // ignored
console.log(obj.a); // 1

Object.seal()

Prevents adding or removing properties, but allows modifying existing property values.

let user = { name: "Alex" };
Object.seal(user);
user.name = "Tom"; // allowed
delete user.name;  // not allowed

Object Reference & Copy

In JavaScript, objects are assigned by reference, meaning multiple variables can point to the same object.

let obj1 = { a: 1 };
let obj2 = obj1;
obj2.a = 2;
console.log(obj1.a); // 2 (same reference)

Shallow Copy

A copy where only the first level of properties is cloned; nested objects still share references.

let copy1 = Object.assign({}, obj1);
let copy2 = { ...obj1 };

Deep Copy

A copy where all levels of the object are cloned, creating a completely independent duplicate.

let deepCopy = JSON.parse(JSON.stringify(obj1));

8. JavaScript Classes

JavaScript Classes (introduced in ES6) are templates for creating objects. They provide a cleaner and more structured way to work with constructors, inheritance, and methods compared to prototype-based syntax.

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  greet() {
    return `Hello, my name is ${this.name}`;
  }
}
let p1 = new Person("John", 30);
console.log(p1.greet()); // Hello, my name is John

JS Classes

Classes are blueprints for objects that encapsulate data (fields) and behavior (methods).

  • Declared with the class keyword.
  • Support inheritance, encapsulation, and static methods.

Example:

class Animal {
  constructor(type) {
    this.type = type;
  }
}
let dog = new Animal("Dog");
console.log(dog.type); // Dog

Class Methods

Class methods are functions defined inside a class that describe the behavior of objects created from that class and can be called on its instances (or on the class itself if declared static).

Instance Methods (default methods)

Methods defined inside a class that are available to all instances of that class.

class Car {
  start() {
    return "Car started!";
  }
}
let c = new Car();
console.log(c.start()); // Car started!

Getters & Setters in Classes

Special methods in classes used to access (get) and update (set) property values with controlled behavior.

class Rectangle {
  constructor(width, height) {
    this.width = width;
    this.height = height;
  }
  get area() {
    return this.width * this.height;
  }
  set widthUpdate(newWidth) {
    this.width = newWidth;
  }
}
let rect = new Rectangle(10, 5);
console.log(rect.area); // 50
rect.widthUpdate = 20;
console.log(rect.area); // 100

Constructor

The constructor() method is automatically executed when a new object is created.

  • Initializes properties.
  • Only one constructor is allowed per class.
class Student {
  constructor(name, grade) {
    this.name = name;
    this.grade = grade;
  }
}
let s = new Student("Alice", "A");
console.log(s.name, s.grade); // Alice A

Class Inheritance (extends, super)

A mechanism that allows one class to inherit properties and methods from another class, promoting reusability.

Using extends

The extends keyword is used to create a class that inherits from a parent class.

class Animal {
  constructor(name) {
    this.name = name;
  }
  speak() {
    return `${this.name} makes a noise`;
  }
}

class Dog extends Animal {
  speak() {
    return `${this.name} barks`;
  }
}

let d = new Dog("Rex");
console.log(d.speak()); // Rex barks

Using super

The super keyword is used to call the parent class’s constructor or methods inside a derived class.

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

class Employee extends Person {
  constructor(name, role) {
    super(name); // Call parent constructor
    this.role = role;
  }
}
let emp = new Employee("Bob", "Manager");
console.log(emp.name, emp.role); // Bob Manager

Static Methods

  • Declared with static keyword.
  • Belong to the class itself, not to instances.
class MathHelper {
  static add(a, b) {
    return a + b;
  }
}
console.log(MathHelper.add(5, 3)); // 8

Note: You call them with ClassName.method(), not with an object instance.

Private & Public Fields

Fields define properties inside a class.

Public Fields (default)

Public fields are class properties that are accessible from anywhere (inside or outside the class) and are created without any special modifier.

class User {
  name = "Guest"; // Public field
}
let u = new User();
console.log(u.name); // Guest

Private Fields (with #)

Private fields are class properties defined with # that are accessible only within the class itself and cannot be read or modified from outside the class.

class BankAccount {
  #balance = 1000; // private field
  getBalance() {
    return this.#balance;
  }
}
let acc = new BankAccount();
console.log(acc.getBalance()); // 1000
console.log(acc.#balance); //  Error

Combining Public & Private Fields

A class can define both public fields (accessible everywhere) and private fields (restricted to within the class using #) to separate internal data from externally accessible properties.

class Employee {
  #salary; // private
  constructor(name, salary) {
    this.name = name;   // public
    this.#salary = salary;
  }
  get details() {
    return `${this.name} earns ${this.#salary}`;
  }
}
let e = new Employee("Alice", 5000);
console.log(e.details); // Alice earns 5000

9. JavaScript Sets & Maps

JavaScript provides Set and Map objects (introduced in ES6) to handle collections of values and key–value pairs more efficiently than plain objects or arrays.

Sets

A Set is a collection of unique values (no duplicates).

let mySet = new Set([1, 2, 3, 3, 4]);
console.log(mySet); // Set(4) {1, 2, 3, 4}

Creating Sets

  • From an array: new Set([1, 2, 3])
  • Empty set: new Set()
let numbers = new Set([10, 20, 30]);
let emptySet = new Set();

Set Methods

Set methods are built-in functions that allow you to manipulate and manage values inside a Set object (e.g., add(), delete(), has(), clear(), and the size property).

MethodDescriptionExample
add(value)Adds valuemySet.add(5)
delete(value)Removes valuemySet.delete(2)
has(value)Checks if existsmySet.has(1)true
clear()Removes all valuesmySet.clear()
sizeReturns sizemySet.size
let set = new Set();
set.add("A").add("B");
console.log(set.has("A")); // true
console.log(set.size); // 2
set.delete("B");
console.log(set); // Set(1) {"A"}

Set Iteration

Set iteration refers to the process of looping through all values in a Set using methods like for…of, forEach(), or by converting it into an array.

let fruits = new Set(["apple", "banana", "mango"]);

// for…of
for (let f of fruits) console.log(f);

// forEach
fruits.forEach(f => console.log(f));

Set Operations

Unlike arrays, JS doesn’t have built-in operations, but we can implement them.

Union

A set operation that combines all unique elements from two or more sets into one.

let a = new Set([1, 2, 3]);
let b = new Set([3, 4, 5]);
let union = new Set([...a, ...b]);
console.log(union); // {1, 2, 3, 4, 5}

Intersection

A set operation that returns only the common elements present in all sets.

let intersection = new Set([...a].filter(x => b.has(x)));
console.log(intersection); // {3}

Difference

A set operation that returns the elements that are in one set but not in the other.

let difference = new Set([...a].filter(x => !b.has(x)));
console.log(difference); // {1, 2}

WeakSet

  • Only stores objects (not primitives).
  • Weakly held → values can be garbage-collected.
  • Methods: add, delete, has.
let ws = new WeakSet();
let obj = {name: "Alice"};
ws.add(obj);
console.log(ws.has(obj)); // true
ws.delete(obj);
console.log(ws.has(obj)); // false

Set Reference

A reference means when assigning a set to another variable, both point to the same object.

let s1 = new Set([1, 2]);
let s2 = s1;
s2.add(3);
console.log(s1); // Set {1, 2, 3}

Maps

A Map is a collection of key–value pairs, where keys can be any type (objects, functions, primitives).

let map = new Map();
map.set("name", "John");
map.set(1, "one");
map.set({id: 1}, "Object key");
console.log(map);

Creating Maps

  • Empty: new Map()
  • From array of pairs:
let map1 = new Map([["a", 1], ["b", 2]]);
console.log(map1.get("a")); // 1

Map Methods

Map methods are built-in functions that allow you to work with key–value pairs inside a Map object, such as set(), get(), has(), delete(), clear(), and the size property.

MethodDescriptionExample
set(key, value)Add/update entrymap.set("x", 10)
get(key)Retrieve valuemap.get("x")
has(key)Check keymap.has("x")
delete(key)Remove entrymap.delete("x")
clear()Remove allmap.clear()
sizeGet total entriesmap.size
let map = new Map();
map.set("color", "red");
console.log(map.get("color")); // red
console.log(map.has("color")); // true
console.log(map.size); // 1

Map Iteration

Map iteration is the process of looping through key–value pairs in a Map using for…of, forEach(), or by converting the map into an array with the spread operator ([...]).

let map = new Map([["a", 1], ["b", 2]]);

// for…of
for (let [k, v] of map) console.log(k, v);

// forEach
map.forEach((v, k) => console.log(k, v));

// Convert to array
console.log([...map]); // [["a",1],["b",2]]

WeakMap

  • Keys must be objects (not primitives).
  • Values are weakly held → garbage collected if no reference.
  • Methods: set, get, has, delete.
  • No iteration or size.
let wm = new WeakMap();
let obj = {};
wm.set(obj, "data");
console.log(wm.get(obj)); // data
wm.delete(obj);
console.log(wm.has(obj)); // false

Map Reference

  • Maps in JavaScript are reference types.
  • When you assign one map to another, both variables point to the same map in memory.
  • Changes in one will affect the other.
let m1 = new Map([["x", 1]]);
let m2 = m1;
m2.set("y", 2);
console.log(m1); // Map(2) {"x" => 1, "y" => 2}

To copy a Map

  1. Using Constructor
let original = new Map([["x", 10], ["y", 20]]);
let copy = new Map(original);
console.log(copy); // Map(2) { "x" => 10, "y" => 20 }
  1. Using Spread Operator (...)
let original = new Map([["p", 100], ["q", 200]]);
let copy = new Map([...original]);
console.log(copy); // Map(2) { "p" => 100, "q" => 200 }

10. Iterables & Generators

JavaScript provides special mechanisms to loop through collections of data using iterables, iterators, and generators. These concepts give developers more control, flexibility, and efficiency while working with data structures.

Iterables

An iterable is any object that can be looped over using a for…of loop.

  • Common examples: Arrays, Strings, Maps, Sets.
  • An iterable must implement the Symbol.iterator method, which returns an iterator.

Example: Built-in Iterables

let arr = [10, 20, 30];
for (let num of arr) {
  console.log(num); // 10, 20, 30
}

let str = "JS";
for (let char of str) {
  console.log(char); // J, S
}

Custom Iterable

You can create your own iterable by defining [Symbol.iterator].

let myIterable = {
  data: [1, 2, 3],
  [Symbol.iterator]() {
    let i = 0;
    let self = this;
    return {
      next() {
        if (i < self.data.length) {
          return { value: self.data[i++], done: false };
        } else {
          return { done: true };
        }
      }
    };
  }
};

for (let val of myIterable) {
  console.log(val); // 1, 2, 3
}

Iterators

An iterator is an object returned by the Symbol.iterator method.

  • It provides a .next() method.
  • .next() returns an object with two properties:
    • value → current element
    • done → boolean (true if iteration finished)

Example: Using an Iterator

let arr = [5, 10, 15];
let iterator = arr[Symbol.iterator]();

console.log(iterator.next()); // { value: 5, done: false }
console.log(iterator.next()); // { value: 10, done: false }
console.log(iterator.next()); // { value: 15, done: false }
console.log(iterator.next()); // { value: undefined, done: true }

Generators (function*)

A generator is a special function that can pause execution (yield) and resume later.

  • Defined using function* syntax.
  • Calling a generator function returns an iterator.
  • Each call to .next() continues execution until the next yield.

Basic Generator Example

function* numberGenerator() {
  yield 1;
  yield 2;
  yield 3;
}

let gen = numberGenerator();

console.log(gen.next()); // { value: 1, done: false }
console.log(gen.next()); // { value: 2, done: false }
console.log(gen.next()); // { value: 3, done: false }
console.log(gen.next()); // { value: undefined, done: true }

Using Generators with for…of

Generators are iterables, so you can loop directly.

function* fruits() {
  yield "Apple";
  yield "Banana";
  yield "Mango";
}

for (let fruit of fruits()) {
  console.log(fruit);
}
// Apple, Banana, Mango

Passing Values into Generators

You can pass values back into a generator using .next(value).

function* greet() {
  let name = yield "What is your name?";
  yield `Hello, ${name}!`;
}

let gen = greet();
console.log(gen.next().value); // "What is your name?"
console.log(gen.next("Alice").value); // "Hello, Alice!"

Infinite Generators

Generators can create infinite sequences efficiently.

function* naturalNumbers() {
  let num = 1;
  while (true) {
    yield num++;
  }
}

let gen = naturalNumbers();
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // 3

Generator with yield* (Delegating to Another Generator)

yield* allows a generator to delegate to another generator.

function* gen1() {
  yield "A";
  yield "B";
}

function* gen2() {
  yield* gen1();
  yield "C";
}

for (let val of gen2()) {
  console.log(val);
}
// A, B, C

11. Regular Expressions (RegExp)

Regular Expressions (RegEx) in JavaScript are patterns used to match character combinations in strings. They are essential for searching, validating, and replacing text efficiently.

RegExp Basics

A RegExp is a sequence of characters that defines a search pattern. It can be used with strings to test, match, or replace text.

Example:

let pattern = /hello/;       // Literal notation
let pattern2 = new RegExp('hello'); // Constructor notation

console.log(pattern.test("hello world")); // true

RegExp Flags

Flags modify the behavior of a RegExp.

Common Flags:

FlagMeaningExample
gGlobal search (all matches)/cat/g
iCase-insensitive/cat/i
mMulti-line search/^cat/m
sDot matches newline/a.b/s
uUnicode support/\\u{1F600}/u
ySticky match/cat/y

Example:

let text = "Cat cat CAT";
let regex = /cat/gi;
console.log(text.match(regex)); // ["Cat", "cat", "CAT"]

RegExp Character Classes

Character classes allow matching specific types of characters.

SymbolDefinitionExample
\\dDigit [0-9]/\\d/.test("5") → true
\\DNon-digit/\\D/.test("a") → true
\\wWord character [a-zA-Z0-9_]/\\w/.test("_") → true
\\WNon-word character/\\W/.test("@") → true
\\sWhitespace/\\s/.test(" ") → true
\\SNon-whitespace/\\S/.test("a") → true
.Any character except newline/./.test("\\n") → false

RegExp Metacharacters

Metacharacters are special characters that control how patterns match.

SymbolMeaningExample
^Start of string/^cat/.test("catdog") → true
$End of string/dog$/.test("catdog") → true
[]Character set/[abc]/.test("b") → true
[^]Negated set/[^abc]/.test("d") → true
``OR
()Grouping/colou?r/.test("color") → true

RegExp Assertions

Assertions match patterns without consuming characters, useful for lookahead and lookbehind.

AssertionMeaningExample
(?=...)Positive lookahead/\\d(?=px)/.test("10px") → true
(?!...)Negative lookahead/\\d(?!px)/.test("10em") → true
(?<=...)Positive lookbehind/(?<=\\$)\\d+/.test("$100") → true
(?<!...)Negative lookbehind/(?<!\\$)\\d+/.test("100") → true

RegExp Quantifiers

Quantifiers define how many times a character or group can repeat.

SymbolMeaningExample
*0 or more/a*/.test("aaa") → true
+1 or more/a+/.test("a") → true
?0 or 1/colou?r/.test("color") → true
{n}Exactly n/a{3}/.test("aaa") → true
{n,}n or more/a{2,}/.test("aaaa") → true
{n,m}Between n and m/a{2,4}/.test("aaa") → true

RegExp Patterns

Patterns are combinations of characters, classes, metacharacters, and quantifiers.

Example:

let emailPattern = /^[\\w.-]+@[\\w.-]+\\.[a-zA-Z]{2,6}$/;
console.log(emailPattern.test("[email protected]")); // true

RegExp Objects

JavaScript RegExp object stores a pattern and its properties.

Example:

let regex = /hello/g;
console.log(regex.source); // "hello"
console.log(regex.flags);  // "g"

RegExp Methods

These are built-in methods to test, match, and manipulate strings using RegEx.

MethodDescriptionExample
test()Returns true/false if pattern matches/\\d/.test("123") → true
exec()Returns matched results or null/\\d+/.exec("123") → ["123"]
match()Returns array of matches"123 abc".match(/\\d+/g) → ["123"]
replace()Replace matches with new string"123 abc".replace(/\\d+/g, "456") → "456 abc"

12. Typed Arrays

Typed Arrays in JavaScript provide arrays of specific numeric types, allowing for high-performance operations on binary data, such as graphics, WebGL, and data streams. Unlike regular arrays, they store homogeneous values in contiguous memory, improving speed and efficiency.

Introduction to Typed Arrays

Typed Arrays are array-like objects that provide a mechanism to read and write raw binary data in memory buffers.

Common Typed Arrays:

TypeBytes per elementRange
Int8Array1-128 to 127
Uint8Array10 to 255
Uint8ClampedArray10 to 255 (clamped)
Int16Array2-32,768 to 32,767
Uint16Array20 to 65,535
Int32Array4-2³¹ to 2³¹-1
Uint32Array40 to 2³²-1
Float32Array4±1.18e−38 to ±3.4e38
Float64Array8±2.23e−308 to ±1.79e308

Example:

let buffer = new ArrayBuffer(16); // 16 bytes
let int32View = new Int32Array(buffer);
int32View[0] = 42;
console.log(int32View); // Int32Array(4) [42, 0, 0, 0]

Use Case: Efficiently handle binary data for WebGL, audio, or file processing.

Typed Array Methods

Typed Arrays provide methods similar to regular arrays but optimized for numeric operations.

MethodDescriptionExample
set()Copy values into typed arraylet arr = new Int8Array(4); arr.set([1,2]); console.log(arr)[1,2,0,0]
subarray()Creates a new view into the arrayarr.subarray(1,3) → view [2,0]
slice()Returns a shallow copy of a portionarr.slice(1,3)[2,0]
map()Applies a function to each elementarr.map(x => x*2)[2,4,0,0]
forEach()Iterates over elementsarr.forEach(x => console.log(x))
reduce()Reduces array to a single valuearr.reduce((a,b) => a+b) → 3

Example:

let floatArr = new Float32Array([1.5, 2.5, 3.5]);
let doubled = floatArr.map(x => x * 2);
console.log(doubled); // Float32Array [3, 5, 7]

Typed Array Reference

Typed Arrays are views over ArrayBuffer objects, allowing you to access raw binary data efficiently.

Creating Typed Arrays:

// From an Array
let uint8 = new Uint8Array([10, 20, 30]);

// From ArrayBuffer
let buffer = new ArrayBuffer(8);
let view = new Float64Array(buffer);
view[0] = 3.14;
console.log(view); // Float64Array [3.14]

Properties:

PropertyDescription
bufferThe underlying ArrayBuffer
byteLengthLength in bytes
lengthNumber of elements
byteOffsetOffset from start of buffer

Example:

console.log(view.buffer);      // ArrayBuffer { byteLength: 8 }
console.log(view.byteLength);  // 8
console.log(view.length);      // 1

13. Asynchronous Programming – Callbacks, Promises & Async/Await

JavaScript is single-threaded, but asynchronous programming allows it to perform long-running tasks like fetching data, reading files, or timers without blocking the main thread.

Callbacks

A callback is a function passed as an argument to another function, executed after an operation completes.

Example:

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

fetchData((data) => {
  console.log(data); // "Data loaded" after 1 second
});

Asynchronous Programming Model

Asynchronous programming allows tasks to run in the background, and results are handled later via callbacks, promises, or async/await.

Example Flow:

  1. Start async operation (fetch, timer, etc.)
  2. Continue executing other code
  3. Receive result when operation completes
console.log("Start");
setTimeout(() => console.log("Async task done"), 1000);
console.log("End");
// Output: Start → End → Async task done

Promises

A Promise is an object representing the eventual completion or failure of an asynchronous operation.

States of a Promise:

  • pending → initial state
  • fulfilled → operation successful
  • rejected → operation failed

Example:

let promise = new Promise((resolve, reject) => {
  let success = true;
  setTimeout(() => {
    success ? resolve("Done") : reject("Error");
  }, 1000);
});

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

Creating & Using Promises

You can create custom promises to wrap asynchronous tasks.

Example:

function fetchUser(id) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if(id) resolve({id: id, name: "Alice"});
      else reject("Invalid ID");
    }, 1000);
  });
}

fetchUser(1)
  .then(user => console.log(user))
  .catch(err => console.error(err));

Promise Combinators

Combine multiple promises for parallel or competitive execution.

MethodDescriptionExample
Promise.all([p1,p2])Waits for all promises, rejects if any failsPromise.all([p1,p2]).then(console.log)
Promise.race([p1,p2])Resolves/rejects as soon as first promise settlesPromise.race([p1,p2]).then(console.log)
Promise.any([p1,p2])Resolves when first promise fulfills, ignores rejectionsPromise.any([p1,p2]).then(console.log)

Example:

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

Promise.all([p1, p2]).then(results => console.log(results)); // [10, 20]

Async/Await

async/await is syntactic sugar over promises, making asynchronous code look synchronous.

Example:

async function getUser() {
  try {
    let user = await fetchUser(1);  // waits for promise
    console.log(user);
  } catch (err) {
    console.error(err);
  }
}

getUser();

Event Loop & Microtasks

The event loop handles asynchronous operations in JavaScript. Microtasks (Promises, queueMicrotask) run before the next event loop tick, while macrotasks (setTimeout, setInterval) run later.

Example: Promises (microtasks) execute before setTimeout (macrotasks), even if timeout is 0.

console.log("Start");

setTimeout(() => console.log("Timeout"), 0);
Promise.resolve().then(() => console.log("Promise"));

console.log("End");
// Output: Start → End → Promise → Timeout

14. Error Handling

JavaScript provides a robust error handling mechanism that allows developers to catch, manage, and debug runtime issues efficiently. Understanding these concepts is essential for writing reliable and maintainable code.

Errors Overview

An error is a signal that something has gone wrong in your code. Errors can be syntax errors, runtime errors, or logical errors.

Types of Errors:

Error TypeDescriptionExample
SyntaxErrorInvalid code syntaxeval('foo bar');
ReferenceErrorUsing an undefined variableconsole.log(x);
TypeErrorOperation on wrong typenull.toString();
RangeErrorValue out of allowed rangenew Array(-1);
URIErrorInvalid URI operationsdecodeURI('%');
EvalErrorRelated to eval() (rare)eval('code');

Example:

console.log(undefinedVar); // ReferenceError: undefinedVar is not defined

try…catch Statement

try…catch allows you to execute code that may throw errors and handle them gracefully without stopping execution.

Syntax:

try {
  // Code that might throw
} catch(error) {
  // Handle the error
}

Example:

try {
  let result = riskyOperation();
  console.log(result);
} catch (err) {
  console.error("Caught an error:", err.message);
}

Notes:

  • The catch block receives an Error object containing:
    • name → Error type
    • message → Error message
    • stack → Stack trace
  • Can use optional finally block that always executes:
try {
  console.log("Executing code");
  throw new Error("Something went wrong");
} catch (err) {
  console.error(err.message);
} finally {
  console.log("Cleanup code runs here");
}

throw Statement

throw allows you to generate your own errors, which can then be caught with try…catch.

Syntax:

throw expression; // Usually an Error object

Example:

function checkAge(age) {
  if(age < 18) throw new Error("Age must be 18 or older");
  return "Access granted";
}

try {
  console.log(checkAge(15));
} catch (err) {
  console.error(err.name, ":", err.message);
}

Custom Errors

Custom errors extend the Error class, allowing specific error types for your application logic.

Example:

class ValidationError extends Error {
  constructor(message) {
    super(message); // Call parent constructor
    this.name = "ValidationError"; // Set custom error name
    this.timestamp = new Date();   // Optional additional property
  }
}

function validateName(name) {
  if(!name) throw new ValidationError("Name is required");
}

try {
  validateName("");
} catch(err) {
  console.error(err.name);      // ValidationError
  console.error(err.message);   // Name is required
  console.error(err.timestamp); // Current timestamp
}

Extending Built-in Errors

You can create specialized error classes by extending built-in errors like TypeError, RangeError, or SyntaxError.

Example:

class CustomTypeError extends TypeError {
  constructor(message, code) {
    super(message);
    this.name = "CustomTypeError";
    this.code = code;
  }
}

try {
  throw new CustomTypeError("Invalid type", 101);
} catch(err) {
  console.log(err.name);    // CustomTypeError
  console.log(err.message); // Invalid type
  console.log(err.code);    // 101
}

Debugging JavaScript Errors

Tools & Techniques:

  1. Console: console.error(err) prints errors to browser console.
  2. Stack Trace: Shows where the error originated.
  3. Breakpoints: Use browser dev tools to pause code execution.
  4. Logging: Add meaningful logs before operations.
  5. Linting: Tools like ESLint catch syntax & potential runtime errors.

Example of Stack Trace Usage:

try {
  undefinedFunction();
} catch(err) {
  console.error(err.stack);
}

Example: Async Error Handling

async function fetchData() {
  try {
    let response = await fetch("<https://api.example.com/data>");
    let data = await response.json();
    console.log(data);
  } catch(err) {
    console.error("Failed to fetch data:", err.message);
  }
}

fetchData();

15. JavaScript Versions & Standards

VersionYearKey Features
ES52009"use strict", JSON, Array methods (map, filter, reduce), Object.keys()
ES62015let/const, Arrow functions, Template literals, Classes, Modules (import/export), Destructuring, Spread/Rest, Promises, Map/Set
ES72016Exponentiation **, Array.includes()
ES82017async/await, Object.values(), Object.entries(), String padStart, padEnd
ES92018Object spread {...obj}, Promise.finally(), for await...of
ES102019Array.flat(), flatMap(), Object.fromEntries(), trimStart/trimEnd
ES112020BigInt 123n, Nullish ??, Optional chaining ?., Promise.allSettled(), globalThis, Dynamic import
ES122021Logical assignment (`
ES132022Top-level await, Object.hasOwn(), arr.at(-1), Class fields & private #methods
ES142023findLast(), findLastIndex(), Immutable array methods (toSorted, with), Hashbang #!
ES152024Set operations (union, intersection, difference), Temporal API, Iterator helpers
ES162025Pipeline operator `

History of JavaScript

  • 1995: Created by Brendan Eich at Netscape (originally called Mocha, then LiveScript).
  • 1997: Standardized as ECMAScript (ECMA-262).
  • 2009 (ES5): First widely adopted stable version.
  • 2015 (ES6): The “modern JavaScript” revolution.
  • 2016 onwards: Annual releases with steady improvements.

Browser Compatibility (IE/Edge)

  • Internet Explorer 11 (last version) → supports ES5 and a bit of ES6. Microsoft ended support in 2022.
  • Microsoft Edge (Chromium, 2020+) → supports all modern JavaScript features with automatic updates.
  • For older browsers, developers rely on Babel, polyfills, and transpilers to bridge the gap.

16. JavaScript Advanced Concepts

Strict Mode

  • Enable with "use strict";
  • Catches silent errors, prevents unsafe actions
  • Disallows undeclared variables, duplicate params

Modules (import/export)

  • Export:

    export const name = "JS";
    export default function greet() {}
    
  • Import:

    import greet, { name } from "./file.js";
    

Debugging (console, debugger)

  • console.log(), console.error(), console.table() for quick checks
  • Use debugger; keyword → pauses execution in DevTools
  • Browser DevTools: inspect variables, set breakpoints, step through code

Performance Optimization

  • Minimize DOM manipulation
  • Use debounce / throttle for events
  • Prefer async/await, Promises over blocking code
  • Use const & let properly (avoid unnecessary globals)
  • Lazy loading & code splitting for large apps

Common Mistakes

  • Forgetting == vs === (always use ===)
  • Misusing scope (var vs let/const)
  • Ignoring async errors (try/catch with async/await)
  • Memory leaks (unused event listeners, timers)

17. JavaScript HTML DOM

DOM Introduction

  • DOM = Document Object Model → HTML as a tree of nodes (elements, attributes, text).
  • JS can read, modify, add, or delete HTML & CSS dynamically.

DOM Document

The root object (document) used to access and interact with the entire HTML document.

  • Entry point for DOM manipulation.

Examples:

document.title      // Page title
document.body       // <body> element
document.URL        // Page URL
document.getElementById("id")

DOM Elements

Individual HTML elements that can be selected, read, modified, or removed using methods like getElementById or querySelector.

  • Select elements:

    document.getElementById("id")
    document.getElementsByClassName("class")
    document.getElementsByTagName("tag")
    document.querySelector(".class")
    document.querySelectorAll("p")
    

DOM HTML (Content)

Methods and properties (innerHTML, textContent) to read or change the content of elements.

  • element.innerHTML = "<b>Hello</b>" → renders HTML.
  • element.textContent = "<b>Hello</b>" → shows plain text.

DOM Forms

Access and manipulate form elements and user inputs via the document.forms collection.

  • Access form fields:
document.forms["myForm"]["username"].value

DOM CSS (Styling)

Control the styles and classes of elements dynamically using style and classList.

  • Change styles directly:

    element.style.color = "red";
    element.style.backgroundColor = "yellow";
    
  • Manage classes:

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

DOM Animations

Create visual changes or motion effects on elements using JavaScript timers (setInterval, requestAnimationFrame) and style changes.

  • Change styles step-by-step:

    setInterval(() => { element.style.left = "100px"; }, 1000);
    requestAnimationFrame(myMove);
    

DOM Events

Actions triggered by user interactions (click, input, load) that can be handled in JavaScript.

  • Ways to handle events:

    <button onclick="myFunc()">Click</button>   <!-- Inline -->
    
    element.onclick = () => alert("Clicked!"); // Property
    element.addEventListener("click", myFunc); // Listener
    

Event Listener

A method (addEventListener) to attach multiple event handlers to elements without overwriting existing ones.

  • addEventListener("event", callback)
  • Multiple handlers allowed.
  • Easier to remove with removeEventListener().

Event Bubbling & Capturing

Event propagation phases; bubbling moves from child to parent (default), capturing moves from parent to child.

Example:

element.addEventListener("click", myFunc, true); // capturing

DOM Navigation

Methods to traverse the DOM tree like parentNode, childNodes, firstChild, lastChild, nextSibling.

  • Move around nodes:

    element.parentNode
    element.childNodes
    element.firstChild
    element.lastChild
    element.nextSibling
    element.previousSibling
    

DOM Nodes (Create, Append, Remove)

Individual nodes in the DOM that can be created, appended, or removed dynamically (createElement, appendChild, removeChild).

  • Create and manage elements:

    let div = document.createElement("div");
    div.textContent = "Hello DOM";
    document.body.appendChild(div);
    document.body.removeChild(div);
    

DOM Collections

Live collections of elements returned by methods like getElementsByTagName or getElementsByClassName that update automatically when the DOM changes.

  • Returned by getElementsByTagName/ClassName.
  • Live list → updates when DOM changes.
  • Must loop with for or for...of.

DOM NodeLists

Static lists of nodes returned by querySelectorAll, which do not update automatically but can be iterated with forEach().

  • Returned by querySelectorAll.
  • Static list → does not auto-update.
  • Supports forEach().

18. JavaScript Browser BOM

Browser BOM: The Browser Object Model allows JavaScript to interact with the browser window, controlling elements outside the page content (like navigation, alerts, and screen info).

Window Object:

Represents the browser window; top-level object for all BOM operations.

alert("Hello!");          // Popup alert
console.log(window.innerWidth); // Window width

Screen Object:

Provides information about the user’s screen.

console.log(screen.width);  // Total screen width
console.log(screen.availHeight); // Available height

Location Object:

Represents the current page URL; can read or change it.

console.log(location.href); // Current URL
location.reload();          // Reload page
location.assign("<https://example.com>"); // Go to another URL

History Object:

Accesses browser history; navigate through it.

history.back();    // Go back
history.forward(); // Go forward
history.go(-2);    // Go back 2 pages

Navigator Object:

Contains browser/system info.

console.log(navigator.userAgent);  // Browser info
console.log(navigator.platform);   // OS info

Popup & Alert:

Dialogs to interact with users.

alert("Hello!");           // Simple message
let result = confirm("Are you sure?");  // OK/Cancel
let name = prompt("Enter your name");  // Input dialog

Timing (setTimeout, setInterval):

Execute code after delay or repeatedly.

setTimeout(() => console.log("Hi after 2s"), 2000); // Once after 2s
let timer = setInterval(() => console.log("Every 1s"), 1000); // Repeats
clearInterval(timer); // Stop interval

Cookies:

Store small data in the browser.

document.cookie = "username=John; expires=Fri, 31 Dec 2025 23:59:59 GMT";
console.log(document.cookie); // Read cookies

19. JavaScript Web APIs

Web API Introduction: Browser-provided interfaces that allow JavaScript to interact with features beyond the core language, like storage, network requests, and device capabilities.

Form Validation API:

Lets you validate form inputs before submission using built-in methods and properties.

const form = document.querySelector("form");
if (!form.checkValidity()) {
  alert("Form is invalid!");
}

History API:

Manipulate browser history without reloading the page.

history.pushState({page: 1}, "Title 1", "?page=1");
history.replaceState({page: 2}, "Title 2", "?page=2");

Storage API:

Store data in the browser.

localStorage.setItem("username", "John"); // Persistent
sessionStorage.setItem("sessionID", "123"); // Session-only
console.log(localStorage.getItem("username"));

Worker API (Web Workers):

Run scripts in background threads to prevent UI blocking.

const worker = new Worker("worker.js");
worker.postMessage("Start");
worker.onmessage = e => console.log(e.data);

Fetch API:

Make network requests easily.

fetch("<https://api.example.com/data>")
  .then(res => res.json())
  .then(data => console.log(data));

Geolocation API:

Get the user’s location (latitude/longitude).

navigator.geolocation.getCurrentPosition(pos => {
  console.log(pos.coords.latitude, pos.coords.longitude);
});

Clipboard API:

Read/write to the system clipboard.

navigator.clipboard.writeText("Hello World");
navigator.clipboard.readText().then(text => console.log(text));

20. JavaScript AJAX

AJAX (Asynchronous JavaScript and XML) allows web pages to communicate with servers without reloading, enabling dynamic content updates.

XMLHttpRequest:

Core object used to make AJAX requests.

const xhr = new XMLHttpRequest();
xhr.open("GET", "data.json", true);
xhr.send();

AJAX Request:

Sending data to the server asynchronously using GET or POST.

xhr.open("POST", "server.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("name=John&age=25");

AJAX Response:

Handle server response with onreadystatechange or onload.

xhr.onload = () => {
  if (xhr.status === 200) console.log(xhr.responseText);
};

AJAX with XML:

Process XML data returned from the server.

let xml = xhr.responseXML;
let items = xml.getElementsByTagName("item");

AJAX with PHP:

Send and receive data from PHP scripts.

xhr.open("GET", "data.php", true);
xhr.send();

AJAX with ASP

Communicate with ASP server-side scripts:

const xhr = new XMLHttpRequest();
xhr.open("GET", "data.asp", true);
xhr.onload = () => {
  if (xhr.status === 200) console.log(xhr.responseText);
};
xhr.send();

AJAX Database Integration

Retrieve or update database data via server-side scripts:

// Example with PHP/MySQL
const xhr = new XMLHttpRequest();
xhr.open("POST", "update.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onload = () => {
  if (xhr.status === 200) console.log(xhr.responseText);
};
xhr.send("id=1&name=John");  // Send data to update DB

AJAX Applications

Common uses include live search, form validation, chat apps, dynamic tables, infinite scrolling.

Live Search: Update search results while typing

const input = document.querySelector("#search");
input.addEventListener("keyup", () => {
  fetch(`search.php?q=${input.value}`)
    .then(res => res.text())
    .then(data => document.querySelector("#results").innerHTML = data);
});

Form Validation: Submit form without reloading

const form = document.querySelector("form");
form.addEventListener("submit", e => {
  e.preventDefault();
  fetch("validate.php", {method: "POST", body: new FormData(form)})
    .then(res => res.text())
    .then(msg => alert(msg));
});

AJAX Examples:

  • Live content update without page reload
  • Fetching JSON from REST APIs
  • Submitting forms asynchronously

21. JavaScript JSON

JSON (JavaScript Object Notation) is a lightweight data-interchange format used to store and exchange data between client and server.

JSON Syntax:

Data is represented as key-value pairs inside {} (objects) or [] (arrays).

{ "name": "John", "age": 30 }

JSON vs XML:

JSON is lighter, easier to read/write, and natively supported in JS. XML is more verbose and requires parsing.

{ "name": "John", "age": 30 }

JSON Data Types:

Strings, Numbers, Boolean, Array, Object, null.

{ "name": "John", "age": 30, "isStudent": true, "subjects": ["Math","English"] }

JSON Parse:

Convert JSON string to JS object.

const obj = JSON.parse('{"name":"John","age":30}');
console.log(obj.name); // John

JSON Stringify:

Convert JS object to JSON string.

const jsonStr = JSON.stringify({name: "John", age: 30});
console.log(jsonStr); // '{"name":"John","age":30}'

JSON Objects:

JSON representation of JS objects; key-value pairs.

{ "name": "John", "age": 30 }

JSON Arrays:

JSON representation of arrays; can contain objects or values.

[{"name":"John"}, {"name":"Jane"}]

JSON with Server:

Used to exchange data asynchronously (AJAX/fetch) between client and server.

fetch("data.php")
  .then(res => res.json())
  .then(data => console.log(data));

JSON with PHP:

PHP can encode/decode JSON using json_encode() and json_decode().

<?php
$data = ["name"=>"John", "age"=>30];
echo json_encode($data);
?>

JSON with HTML:

Dynamically display JSON data in HTML.

const obj = {name:"John"};
document.getElementById("output").textContent = obj.name;

JSONP (JSON with Padding):

Technique to fetch JSON from a different domain using a <script> tag (used before CORS existed).

<script src="<https://example.com/data?callback=myFunc>"></script>
<script>
function myFunc(data) {
  console.log(data);
}
</script>

22. JavaScript vs jQuery

jQuery is a fast, small, and feature-rich JavaScript library that simplifies DOM manipulation, event handling, and AJAX.

// JavaScript
document.getElementById("demo").textContent = "Hello JS";

// jQuery
$("#demo").text("Hello jQuery");

jQuery Selectors:

Used to select HTML elements easily using CSS-style syntax.

// Select by ID
$("#myId").hide();

// Select by class
$(".myClass").css("color", "red");

// Select by tag
$("p").fadeOut();

jQuery HTML Methods:

Methods to get or set HTML content.

// Get HTML
let content = $("#demo").html();

// Set HTML
$("#demo").html("<b>Bold Text</b>");

jQuery CSS Methods:

Methods to get or set CSS styles dynamically.

// Get CSS
let color = $("#demo").css("color");

// Set CSS
$("#demo").css("background-color", "yellow");

jQuery DOM Manipulation:

Simplifies adding, removing, or modifying elements in the DOM.

// Append new element
$("#demo").append("<p>New Paragraph</p>");

// Remove element
$("#demo p").remove();

// Wrap element
$("p").wrap("<div class='wrapper'></div>");

23. JavaScript Graphics & Data Visualization

Graphics in JavaScript:

JavaScript can create 2D/3D graphics and visualizations directly in the browser using APIs and libraries.

// Example: basic canvas drawing
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(10, 10, 100, 50);

Canvas API:

Provides a space (<canvas>) to draw shapes, images, animations, and graphics using JavaScript.

ctx.beginPath();
ctx.arc(75, 75, 50, 0, Math.PI * 2); // Draw a circle
ctx.fillStyle = "blue";
ctx.fill();

Plotly:

A JavaScript library for interactive, high-quality graphs and charts.

Plotly.newPlot('myDiv', [{
  x: [1, 2, 3],
  y: [10, 15, 13],
  type: 'scatter'
}]);

Chart.js:

Lightweight library to create responsive and animated charts.

new Chart(document.getElementById("myChart"), {
  type: 'bar',
  data: {
    labels: ["Red","Blue","Yellow"],
    datasets: [{ label: 'Votes', data: [12,19,3] }]
  }
});

Google Charts:

Google’s tool to create interactive charts that work with real-time data.

google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
  var data = google.visualization.arrayToDataTable([
    ['Color','Votes'], ['Red',12], ['Blue',19], ['Yellow',3]
  ]);
  var chart = new google.visualization.PieChart(document.getElementById('pieChart'));
  chart.draw(data);
}

D3.js:

Powerful library for data-driven documents, creating complex visualizations like graphs, maps, and dynamic charts.

d3.select("body")
  .append("svg")
  .attr("width", 200)
  .attr("height", 100)
  .append("circle")
  .attr("cx", 50).attr("cy", 50).attr("r", 40)
  .style("fill", "green");

 

Article 0 of 0