Clean • Professional
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.
JavaScript (JS) is a lightweight, interpreted programming language used to:
let x ≠ Let x).; (optional but recommended).Example:
let name = "John";
console.log("Hello " + name);
| Method | Example | Usage |
|---|---|---|
| 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) |
| Method | Example | Use 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) |
let, const, varName ≠ nameExample:
let age = 25; // variable
const pi = 3.14; // constant
var city = "Delhi"; // old way (avoid in modern JS)
Statements are instructions for the browser.
let x = 10;)Example:
let x = 5;
let y = 10;
let z = x + y; // statement
// This is a comment/*
This is a
multi-line comment
*/
Variables in JavaScript are containers for storing data.
You can declare variables using var, let, or const depending on your use case.
| Keyword | Scope | Reassign? | Hoisting | Best Use |
|---|---|---|---|---|
| var | Function scope | Yes | Hoisted (initialized as undefined) | Legacy code |
| let | Block scope | Yes | Hoisted (but not initialized) | Modern variable |
| const | Block scope | No | Hoisted (but not initialized) | Fixed values |
Example:
var city = "Delhi"; // Function-scoped
let age = 25; // Block-scoped
const pi = 3.1416; // Constant (cannot be reassigned)
{}.Example:
let x = 10;
x = 20; // allowed
let x = 30; // error (cannot redeclare in same scope)
let.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
| Type | Example | Accessible From |
|---|---|---|
| Global Scope | var a = 10; | Anywhere in code |
| Local Scope (Function) | Declared inside function | Only inside that function |
| Block Scope | let 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
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;
Operators in JavaScript are symbols that perform actions on values or variables.
They are used for assignments, comparisons, arithmetic, logic, and more.
JavaScript has several categories of operators:
typeof, instanceof, ternary ? :Assignment operators are used to assign values to variables.
| Operator | Meaning | Example | Result |
|---|---|---|---|
= | Assign | x = 10 | x = 10 |
+= | Add and assign | x += 5 | x = x + 5 |
-= | Subtract and assign | x -= 3 | x = x - 3 |
*= | Multiply and assign | x *= 2 | x = x * 2 |
/= | Divide and assign | x /= 4 | x = x / 4 |
%= | Modulus and assign | x %= 4 | x = x % 4 |
**= | Exponent and assign | x **= 3 | x = x ** 3 |
Example:
let a = 10;
a += 5; // 15
a *= 2; // 30
Used to perform mathematical operations.
| Operator | Example | Result |
|---|---|---|
+ | 5 + 2 | 7 |
- | 5 - 2 | 3 |
* | 5 * 2 | 10 |
/ | 5 / 2 | 2.5 |
% | 5 % 2 | 1 (remainder) |
** | 2 ** 3 | 8 (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)
x++) → Uses the current value first, then increases it by 1.++x) → Increases the value by 1 first, then uses the new value.Used to compare values and return true or false.
| Operator | Example | Result |
|---|---|---|
== | 5 == "5" | true (checks value only) |
=== | 5 === "5" | false (checks value + type) |
!= | 5 != "5" | false |
!== | 5 !== "5" | true |
> | 10 > 5 | true |
< | 10 < 5 | false |
>= | 5 >= 5 | true |
<= | 3 <= 5 | true |
Example:
let age = 18;
console.log(age >= 18); // true
Used to combine conditions.
| Operator | Example | Meaning |
|---|---|---|
&& (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");
}
Operate on binary values (0s and 1s).
| Operator | Example | Result (Binary) |
|---|---|---|
& (AND) | 5 & 1 | 1 |
| ` | ` (OR) | `5 |
^ (XOR) | 5 ^ 1 | 4 |
~ (NOT) | ~5 | -6 |
<< (Left Shift) | 5 << 1 | 10 |
>> (Right Shift) | 5 >> 1 | 2 |
>>> (Unsigned Right Shift) | -5 >>> 1 | A large positive number |
Example:
console.log(5 & 1); // 1
console.log(5 | 1); // 5
console.log(5 ^ 1); // 4
Determines the order of execution when multiple operators are used.
Highest → Lowest order:
() → Parentheses++, - → Increment/Decrement* → Exponentiation/, % → Multiplication, Division, Modulus+, → Addition, Subtraction<, >, <=, >= → Comparisons==, ===, !=, !== → Equality&& → Logical AND|| → Logical OR= → AssignmentExample:
let result = 5 + 3 * 2; // 5 + (3*2) = 11
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:
Includes: String, Number, BigInt, Boolean, Undefined, Null, Symbol
Includes: Object, Array, Date, Function
Strings are text values wrapped in quotes.
let str1 = "Hello";
let str2 = 'World';
let str3 = `Template`;
.length, .toUpperCase(), .toLowerCase(), .slice(), .replace(), .trim().indexOf(), .includes(), .startsWith(), .endsWith()| Method | Example | Result |
|---|---|---|
.length | "Hello".length | 5 |
.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
.indexOf("text") → Finds position..includes("word") → Returns true/false..startsWith("prefix") → Checks beginning..endsWith("suffix") → Checks ending.Example:
"JavaScript".includes("Script"); // true
Use backticks (``) with ${} for variables.
let name = "John";
console.log(`Hello, ${name}!`);
All integers and floating-point values.
let x = 10;
let y = 10.5;
let z = 1e6;
| Method | Example | Result |
|---|---|---|
.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.MAX_VALUE → Largest number.Number.MIN_VALUE → Smallest number.Number.POSITIVE_INFINITY → Infinity.Number.NaN → Not a Number.JavaScript has a built-in Math object.
| Method | Description | Example |
|---|---|---|
Math.PI | Returns the value of π | 3.14159 |
Math.E | Returns Euler’s number e | 2.718 |
Math.sqrt(x) | Returns square root of x | Math.sqrt(9) → 3 |
Math.pow(x, y) | Returns x raised to the power y | Math.pow(2,3) → 8 |
Math.abs(x) | Returns absolute value of x | Math.abs(-5) → 5 |
Math.round(x) | Rounds to nearest integer | Math.round(4.6) → 5 |
Math.floor(x) | Rounds down | Math.floor(4.9) → 4 |
Math.ceil(x) | Rounds up | Math.ceil(4.1) → 5 |
Math.random() | Returns random number 0 ≤ x < 1 | Math.random() → 0.234 |
Math.floor(Math.random()*n) | Random integer 0 to n-1 | 0–9 |
Random Numbers:
Math.random(); // 0 to <1
Math.floor(Math.random() * 10); // 0 to 9
Used for very large integers.
let big = 123456789012345678901234567890n;
Boolean has two values: true or false.
let isOnline = true;
let isLoggedIn = false;
let a; // undefined
let b = null; // null
Checks data type of a value.
typeof "Hello"; // "string"
typeof 123; // "number"
typeof null; // "object" (special case)
typeof []; // "object"
JavaScript automatically converts data types during operations.
"5" + 2; // "52"
"5" - 2; // 3
Developer manually converts data type using functions.
Number("123"); // 123
String(123); // "123"
Boolean(0); // false
Converts a value to string.
let num = 10;
num.toString(); // "10"
Collection of key–value pairs.
let person = { name: "Alice", age: 25 };
Arrays hold multiple values in one variable.
let fruits = ["Apple", "Banana", "Mango"];
| Method | Example | Result |
|---|---|---|
.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" |
.indexOf("Banana") → 1.includes("Apple") → true.find(x => x > 10) → First matchlet nums = [40, 100, 1, 5];
nums.sort(); // [1,100,40,5] (wrong for numbers)
nums.sort((a,b)=>a-b); // [1,5,40,100]
.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]
You can declare arrays with const, but you can modify elements.
const cars = ["BMW","Audi"];
cars[0] = "Tesla"; // allowed
cars = ["Honda"]; // error
JavaScript Date object handles time and date.
let d = new Date();
console.log(d.toDateString());
"2025-09-03" → ISO format."09/03/2025" → Short date."September 3, 2025" → Long date.getFullYear() → YeargetMonth() → Month (0–11)getDate() → Day of monthgetDay() → WeekdaysetFullYear(2030)setMonth(11)setDate(25)getDate(), getMonth(), getDay()setDate(), setMonth(), setFullYear()Functions are objects in JS.
function greet() {
return "Hello";
}
Control flow defines the order in which code executes. It helps you make decisions and repeat actions based on conditions.
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.");
}
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 are used to repeat a block of code multiple times until a condition is false.
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);
}
The while loop keeps running as long as the condition is true.
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
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);
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]);
}
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);
}
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
A code block { } groups multiple statements together so they run as a unit.
{
let x = 10;
let y = 20;
console.log(x + y); // 30
}
Functions in JavaScript are blocks of code designed to perform specific tasks. They make code reusable, organized, and easy to maintain.
Functions can be defined using the function keyword.
function greet() {
console.log("Hello World!");
}
Call it with:
greet(); // Hello World!
function add(a, b) { // parameters
return a + b;
}
console.log(add(5, 3)); // arguments → 5, 3
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 (...) → 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
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!");
})();
Shorter syntax for writing functions. They don’t bind their own this.
const add = (a, b) => a + b;
console.log(add(5, 3)); // 8
Functions can be stored inside variables.
const multiply = function(x, y) {
return x * y;
};
console.log(multiply(4, 5)); // 20
Functions without a name, often used as callbacks.
setTimeout(function() {
console.log("Hello after 2 seconds");
}, 2000);
function outer() {
let count = 0;
function inner() {
count++;
return count;
}
return inner;
}
let counter = outer();
console.log(counter()); // 1
console.log(counter()); // 2
this Keywordthis refers to the object that called the function.this refers to the parent scope.const person = {
name: "Alice",
greet: function() {
console.log("Hello, " + this.name);
}
};
person.greet(); // Hello, Alice
These methods control the value of this.
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();
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
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;
}
};
Objects can be created in different ways:
The simplest way to create an object using curly braces {} with key–value pairs.
let car = { brand: "Tesla", model: "Model 3" };
new Object()Creates an empty object using the built-in Object constructor, then properties can be added.
let obj = new Object();
obj.name = "Alice";
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!
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;
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; }
};
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 }
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
Converts object into JSON string.
console.log(JSON.stringify(obj)); // {"x":10,"y":20}
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);
thisThe 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.
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
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
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 }
Built-in methods to create, copy, and check objects.
Object.assign() → Copy & MergeThe 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 }
...)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
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.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
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)
A copy where only the first level of properties is cloned; nested objects still share references.
let copy1 = Object.assign({}, obj1);
let copy2 = { ...obj1 };
A copy where all levels of the object are cloned, creating a completely independent duplicate.
let deepCopy = JSON.parse(JSON.stringify(obj1));
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
Classes are blueprints for objects that encapsulate data (fields) and behavior (methods).
class keyword.Example:
class Animal {
constructor(type) {
this.type = type;
}
}
let dog = new Animal("Dog");
console.log(dog.type); // Dog
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).
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!
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
The constructor() method is automatically executed when a new object is created.
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
A mechanism that allows one class to inherit properties and methods from another class, promoting reusability.
extendsThe 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
superThe 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 keyword.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.
Fields define properties inside a class.
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 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
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
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.
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}
new Set([1, 2, 3])new Set()let numbers = new Set([10, 20, 30]);
let emptySet = new Set();
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).
| Method | Description | Example |
|---|---|---|
add(value) | Adds value | mySet.add(5) |
delete(value) | Removes value | mySet.delete(2) |
has(value) | Checks if exists | mySet.has(1) → true |
clear() | Removes all values | mySet.clear() |
size | Returns size | mySet.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 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));
Unlike arrays, JS doesn’t have built-in operations, but we can implement them.
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}
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}
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}
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
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}
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);
new Map()let map1 = new Map([["a", 1], ["b", 2]]);
console.log(map1.get("a")); // 1
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.
| Method | Description | Example |
|---|---|---|
set(key, value) | Add/update entry | map.set("x", 10) |
get(key) | Retrieve value | map.get("x") |
has(key) | Check key | map.has("x") |
delete(key) | Remove entry | map.delete("x") |
clear() | Remove all | map.clear() |
size | Get total entries | map.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 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]]
set, get, has, delete.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
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
let original = new Map([["x", 10], ["y", 20]]);
let copy = new Map(original);
console.log(copy); // Map(2) { "x" => 10, "y" => 20 }
...)let original = new Map([["p", 100], ["q", 200]]);
let copy = new Map([...original]);
console.log(copy); // Map(2) { "p" => 100, "q" => 200 }
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.
An iterable is any object that can be looped over using a for…of loop.
Symbol.iterator method, which returns an iterator.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
}
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
}
An iterator is an object returned by the Symbol.iterator method.
.next() method..next() returns an object with two properties:
value → current elementdone → boolean (true if iteration finished)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 }
function*)A generator is a special function that can pause execution (yield) and resume later.
function* syntax..next() continues execution until the next yield.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 }
for…ofGenerators 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
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!"
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
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
Regular Expressions (RegEx) in JavaScript are patterns used to match character combinations in strings. They are essential for searching, validating, and replacing text efficiently.
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
Flags modify the behavior of a RegExp.
Common Flags:
| Flag | Meaning | Example |
|---|---|---|
g | Global search (all matches) | /cat/g |
i | Case-insensitive | /cat/i |
m | Multi-line search | /^cat/m |
s | Dot matches newline | /a.b/s |
u | Unicode support | /\\u{1F600}/u |
y | Sticky match | /cat/y |
Example:
let text = "Cat cat CAT";
let regex = /cat/gi;
console.log(text.match(regex)); // ["Cat", "cat", "CAT"]
Character classes allow matching specific types of characters.
| Symbol | Definition | Example |
|---|---|---|
\\d | Digit [0-9] | /\\d/.test("5") → true |
\\D | Non-digit | /\\D/.test("a") → true |
\\w | Word character [a-zA-Z0-9_] | /\\w/.test("_") → true |
\\W | Non-word character | /\\W/.test("@") → true |
\\s | Whitespace | /\\s/.test(" ") → true |
\\S | Non-whitespace | /\\S/.test("a") → true |
. | Any character except newline | /./.test("\\n") → false |
Metacharacters are special characters that control how patterns match.
| Symbol | Meaning | Example |
|---|---|---|
^ | 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 |
Assertions match patterns without consuming characters, useful for lookahead and lookbehind.
| Assertion | Meaning | Example |
|---|---|---|
(?=...) | 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 |
Quantifiers define how many times a character or group can repeat.
| Symbol | Meaning | Example |
|---|---|---|
* | 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 |
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
JavaScript RegExp object stores a pattern and its properties.
Example:
let regex = /hello/g;
console.log(regex.source); // "hello"
console.log(regex.flags); // "g"
These are built-in methods to test, match, and manipulate strings using RegEx.
| Method | Description | Example |
|---|---|---|
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" |
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.
Typed Arrays are array-like objects that provide a mechanism to read and write raw binary data in memory buffers.
Common Typed Arrays:
| Type | Bytes per element | Range |
|---|---|---|
Int8Array | 1 | -128 to 127 |
Uint8Array | 1 | 0 to 255 |
Uint8ClampedArray | 1 | 0 to 255 (clamped) |
Int16Array | 2 | -32,768 to 32,767 |
Uint16Array | 2 | 0 to 65,535 |
Int32Array | 4 | -2³¹ to 2³¹-1 |
Uint32Array | 4 | 0 to 2³²-1 |
Float32Array | 4 | ±1.18e−38 to ±3.4e38 |
Float64Array | 8 | ±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 Arrays provide methods similar to regular arrays but optimized for numeric operations.
| Method | Description | Example |
|---|---|---|
set() | Copy values into typed array | let arr = new Int8Array(4); arr.set([1,2]); console.log(arr) → [1,2,0,0] |
subarray() | Creates a new view into the array | arr.subarray(1,3) → view [2,0] |
slice() | Returns a shallow copy of a portion | arr.slice(1,3) → [2,0] |
map() | Applies a function to each element | arr.map(x => x*2) → [2,4,0,0] |
forEach() | Iterates over elements | arr.forEach(x => console.log(x)) |
reduce() | Reduces array to a single value | arr.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 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:
| Property | Description |
|---|---|
buffer | The underlying ArrayBuffer |
byteLength | Length in bytes |
length | Number of elements |
byteOffset | Offset from start of buffer |
Example:
console.log(view.buffer); // ArrayBuffer { byteLength: 8 }
console.log(view.byteLength); // 8
console.log(view.length); // 1
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.
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 allows tasks to run in the background, and results are handled later via callbacks, promises, or async/await.
Example Flow:
console.log("Start");
setTimeout(() => console.log("Async task done"), 1000);
console.log("End");
// Output: Start → End → Async task done
A Promise is an object representing the eventual completion or failure of an asynchronous operation.
States of a Promise:
pending → initial statefulfilled → operation successfulrejected → operation failedExample:
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));
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));
Combine multiple promises for parallel or competitive execution.
| Method | Description | Example |
|---|---|---|
Promise.all([p1,p2]) | Waits for all promises, rejects if any fails | Promise.all([p1,p2]).then(console.log) |
Promise.race([p1,p2]) | Resolves/rejects as soon as first promise settles | Promise.race([p1,p2]).then(console.log) |
Promise.any([p1,p2]) | Resolves when first promise fulfills, ignores rejections | Promise.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 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();
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
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.
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 Type | Description | Example |
|---|---|---|
SyntaxError | Invalid code syntax | eval('foo bar'); |
ReferenceError | Using an undefined variable | console.log(x); |
TypeError | Operation on wrong type | null.toString(); |
RangeError | Value out of allowed range | new Array(-1); |
URIError | Invalid URI operations | decodeURI('%'); |
EvalError | Related to eval() (rare) | eval('code'); |
Example:
console.log(undefinedVar); // ReferenceError: undefinedVar is not defined
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:
catch block receives an Error object containing:
name → Error typemessage → Error messagestack → Stack tracefinally 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 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 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
}
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
}
Tools & Techniques:
console.error(err) prints errors to browser console.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();
| Version | Year | Key Features |
|---|---|---|
| ES5 | 2009 | "use strict", JSON, Array methods (map, filter, reduce), Object.keys() |
| ES6 | 2015 | let/const, Arrow functions, Template literals, Classes, Modules (import/export), Destructuring, Spread/Rest, Promises, Map/Set |
| ES7 | 2016 | Exponentiation **, Array.includes() |
| ES8 | 2017 | async/await, Object.values(), Object.entries(), String padStart, padEnd |
| ES9 | 2018 | Object spread {...obj}, Promise.finally(), for await...of |
| ES10 | 2019 | Array.flat(), flatMap(), Object.fromEntries(), trimStart/trimEnd |
| ES11 | 2020 | BigInt 123n, Nullish ??, Optional chaining ?., Promise.allSettled(), globalThis, Dynamic import |
| ES12 | 2021 | Logical assignment (` |
| ES13 | 2022 | Top-level await, Object.hasOwn(), arr.at(-1), Class fields & private #methods |
| ES14 | 2023 | findLast(), findLastIndex(), Immutable array methods (toSorted, with), Hashbang #! |
| ES15 | 2024 | Set operations (union, intersection, difference), Temporal API, Iterator helpers |
| ES16 | 2025 | Pipeline operator ` |
"use strict";Export:
export const name = "JS";
export default function greet() {}
Import:
import greet, { name } from "./file.js";
console.log(), console.error(), console.table() for quick checksdebugger; keyword → pauses execution in DevToolsdebounce / throttle for eventsconst & let properly (avoid unnecessary globals)== vs === (always use ===)var vs let/const)try/catch with async/await)The root object (document) used to access and interact with the entire HTML document.
Examples:
document.title // Page title
document.body // <body> element
document.URL // Page URL
document.getElementById("id")
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")
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.Access and manipulate form elements and user inputs via the document.forms collection.
document.forms["myForm"]["username"].value
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");
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);
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
A method (addEventListener) to attach multiple event handlers to elements without overwriting existing ones.
addEventListener("event", callback)removeEventListener().Event propagation phases; bubbling moves from child to parent (default), capturing moves from parent to child.
Example:
element.addEventListener("click", myFunc, true); // capturing
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
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);
Live collections of elements returned by methods like getElementsByTagName or getElementsByClassName that update automatically when the DOM changes.
for or for...of.Static lists of nodes returned by querySelectorAll, which do not update automatically but can be iterated with forEach().
forEach().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
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));
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:
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>
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>");
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");