Loading...
Loading...
JavaScript (JS) ek lightweight, interpreted programming language hai jo web pages ko interactive banane ke liye use hoti hai. Originally Netscape ne 1995 mein banaya tha — aaj ye front-end, back-end (Node.js), mobile apps, aur even AI mein use hoti hai.
Browser ke andar:
HTML → Structure
CSS → Style
JS → Behaviour (interactivity)
// var — avoid karo (old way)
var name = "Rahul";
var name = "Priya"; // allowed — confusing!
// let — use karo for mutable values
let age = 20;
age = 21; // OK
// const — use karo for fixed values
const PI = 3.14159;
// PI = 3; // Error!
// Primitive types
let str = "Hello"; // String
let num = 42; // Number
let float = 3.14; // Number (float bhi Number hai)
let bool = true; // Boolean
let nothing = null; // Null (intentional empty)
let undef = undefined; // Undefined (declared but no value)
let big = 9007199254740991n; // BigInt
let sym = Symbol("id"); // Symbol (unique)
// Reference types
let arr = [1, 2, 3]; // Array
let obj = { name: "Raj", age: 21 }; // Object
let fn = function() {}; // Function
typeof "hello" // "string"
typeof 42 // "number"
typeof true // "boolean"
typeof undefined // "undefined"
typeof null // "object" ← JS ka famous bug!
typeof [] // "object"
typeof {} // "object"
typeof function(){}// "function"
Array.isArray([1,2,3]) // true — better for arrays
// Arithmetic
5 + 3 // 8
10 - 4 // 6
3 * 4 // 12
10 / 3 // 3.333...
10 % 3 // 1 (remainder)
2 ** 8 // 256 (exponentiation)
// Comparison
5 == "5" // true (loose equality — type convert karta hai)
5 === "5" // false (strict equality — type bhi check)
5 != "5" // false
5 !== "5" // true ← always use === and !==
// Logical
true && false // false (AND)
true || false // true (OR)
!true // false (NOT)
// Nullish Coalescing (ES2020)
let user = null;
let name = user ?? "Guest"; // "Guest" (null/undefined hone par)
// Optional Chaining (ES2020)
let city = user?.address?.city; // undefined (no error)
let marks = 75;
if (marks >= 90) {
console.log("A Grade");
} else if (marks >= 75) {
console.log("B Grade");
} else if (marks >= 60) {
console.log("C Grade");
} else {
console.log("Fail");
}
// Output: B Grade
let age = 18;
let status = age >= 18 ? "Adult" : "Minor";
console.log(status); // "Adult"
let day = "Monday";
switch(day) {
case "Monday":
case "Tuesday":
console.log("Weekday"); break;
case "Saturday":
case "Sunday":
console.log("Weekend"); break;
default:
console.log("Mid-week");
}
// for loop
for (let i = 0; i < 5; i++) {
console.log(i); // 0 1 2 3 4
}
// while loop
let count = 0;
while (count < 3) {
console.log(count++);
}
// for...of (arrays, strings)
let fruits = ["apple", "banana", "mango"];
for (let fruit of fruits) {
console.log(fruit);
}
// for...in (object keys)
let student = { name: "Raj", age: 20, gpa: 8.5 };
for (let key in student) {
console.log(key, ":", student[key]);
}
// forEach (array method)
fruits.forEach((fruit, index) => {
console.log(index, fruit);
});
// Function declaration (hoisted)
function greet(name) {
return `Hello, ${name}!`;
}
// Function expression (not hoisted)
const add = function(a, b) {
return a + b;
};
// Arrow function (ES6) — shorter syntax
const multiply = (a, b) => a * b;
// Default parameters
function power(base, exp = 2) {
return base ** exp;
}
power(3); // 9 (exp defaults to 2)
power(2, 8); // 256
// Rest parameters
function sum(...nums) {
return nums.reduce((total, n) => total + n, 0);
}
sum(1, 2, 3, 4, 5); // 15
// Spread operator
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let combined = [...arr1, ...arr2]; // [1, 2, 3, 4, 5, 6]
let nums = [3, 1, 4, 1, 5, 9, 2, 6];
// map — transform karo
let doubled = nums.map(n => n * 2);
// [6, 2, 8, 2, 10, 18, 4, 12]
// filter — filter karo
let evens = nums.filter(n => n % 2 === 0);
// [4, 2, 6]
// reduce — single value mein compress karo
let total = nums.reduce((acc, n) => acc + n, 0);
// 31
// find — pehla match
let first5 = nums.find(n => n === 5); // 5
// some / every
nums.some(n => n > 8); // true (koi ek bhi)
nums.every(n => n > 0); // true (sab)
// sort (mutates!)
[...nums].sort((a, b) => a - b); // [1, 1, 2, 3, 4, 5, 6, 9]
// flat / flatMap
[[1,2],[3,4]].flat(); // [1, 2, 3, 4]
// Object creation
const student = {
name: "Priya",
age: 20,
branch: "CS",
cgpa: 8.9,
greet() {
return `Hi, I'm ${this.name}`;
}
};
// Access
student.name; // dot notation
student["branch"]; // bracket notation
// Destructuring
const { name, cgpa } = student;
console.log(name, cgpa); // "Priya" 8.9
// Rename while destructuring
const { name: studentName } = student;
// Array destructuring
const [first, second, ...rest] = [10, 20, 30, 40, 50];
// first=10, second=20, rest=[30,40,50]
// Object spread (shallow copy)
const updated = { ...student, cgpa: 9.2, year: 3 };
class Animal {
#name; // private field (ES2022)
constructor(name, sound) {
this.#name = name;
this.sound = sound;
}
speak() {
return `${this.#name} says ${this.sound}`;
}
get name() { return this.#name; }
}
class Dog extends Animal {
constructor(name) {
super(name, "Woof");
this.tricks = [];
}
learn(trick) {
this.tricks.push(trick);
return this;
}
}
const dog = new Dog("Tommy");
dog.learn("sit").learn("shake");
console.log(dog.speak()); // "Tommy says Woof"
console.log(dog.tricks); // ["sit", "shake"]
Closure = function jo apne outer scope ke variables ko yaad rakhti hai even after outer function return ho jaye.
function makeCounter() {
let count = 0; // private!
return {
increment() { count++; },
decrement() { count--; },
getCount() { return count; }
};
}
const counter = makeCounter();
counter.increment();
counter.increment();
counter.increment();
counter.decrement();
console.log(counter.getCount()); // 2
// count directly access nahi ho sakta — encapsulated hai!
// Old way — nested callbacks :(
getUser(id, function(user) {
getPosts(user.id, function(posts) {
getComments(posts[0].id, function(comments) {
// deeply nested — hard to read!
});
});
});
// Promise — 3 states: pending, fulfilled, rejected
const fetchData = new Promise((resolve, reject) => {
setTimeout(() => {
const data = { id: 1, name: "Raj" };
resolve(data); // success
// reject(new Error("Failed")); // error
}, 1000);
});
fetchData
.then(data => console.log(data))
.catch(err => console.error(err))
.finally(() => console.log("Done"));
async function loadUserData(userId) {
try {
const user = await fetch(`/api/users/${userId}`);
const data = await user.json();
const posts = await fetch(`/api/posts?userId=${userId}`);
const postData = await posts.json();
return { user: data, posts: postData };
} catch (error) {
console.error("Error:", error);
throw error;
}
}
// Parallel requests (faster!)
async function loadAll(userId) {
const [user, posts] = await Promise.all([
fetch(`/api/users/${userId}`).then(r => r.json()),
fetch(`/api/posts?userId=${userId}`).then(r => r.json()),
]);
return { user, posts };
}
// Select elements
const heading = document.getElementById("title");
const buttons = document.querySelectorAll(".btn");
const form = document.querySelector("form");
// Modify
heading.textContent = "New Title";
heading.style.color = "blue";
heading.classList.add("highlight");
heading.classList.toggle("active");
// Create and append
const li = document.createElement("li");
li.textContent = "New item";
document.querySelector("ul").appendChild(li);
// Event listeners
document.querySelector("#btn").addEventListener("click", function(e) {
e.preventDefault();
console.log("Clicked!", e.target);
});
// Event delegation (efficient for dynamic content)
document.querySelector("#list").addEventListener("click", function(e) {
if (e.target.tagName === "LI") {
e.target.classList.toggle("done");
}
});
// math.js — export
export const PI = 3.14159;
export function add(a, b) { return a + b; }
export default class Calculator {
// ...
}
// app.js — import
import Calculator, { PI, add } from "./math.js";
import * as MathUtils from "./math.js";
| Question | Answer | |---|---| | == vs === | == type coercion karta hai, === nahi | | null vs undefined | null = intentional empty, undefined = not assigned | | Hoisting | var declarations aur function declarations top pe move hoti hain | | Event bubbling | Event child se parent ki taraf propagate hota hai | | this keyword | Context pe depend karta hai — arrow functions mein lexical this hota hai | | Prototype chain | JS mein inheritance prototype ke through hoti hai | | Microtask queue | Promises macrotask se pehle resolve hote hain |
class TodoApp {
#todos = [];
add(text) {
this.#todos.push({ id: Date.now(), text, done: false });
this.render();
}
toggle(id) {
const todo = this.#todos.find(t => t.id === id);
if (todo) todo.done = !todo.done;
this.render();
}
delete(id) {
this.#todos = this.#todos.filter(t => t.id !== id);
this.render();
}
render() {
const list = document.querySelector("#todo-list");
list.innerHTML = this.#todos.map(t => `
<li class="${t.done ? 'done' : ''}">
<span onclick="app.toggle(${t.id})">${t.text}</span>
<button onclick="app.delete(${t.id})">×</button>
</li>
`).join("");
}
}
const app = new TodoApp();
No! JavaScript aur Java bilkul alag hain. Java ek compiled, strongly-typed language hai. JavaScript ek interpreted, dynamically-typed scripting language hai jo mainly browsers mein chalti hai.
var — function-scoped, hoisted, can be redeclared. let — block-scoped, not hoisted, can be reassigned. const — block-scoped, must be initialized, cannot be reassigned (but objects/arrays can be mutated).
A closure is a function that remembers its outer scope even after the outer function has returned. It gives inner functions access to variables from their containing scope.
Git & GitHub Complete Guide — Version Control for Students (2026)
20 min · Beginner
DatabaseSQL Complete Guide — Database Queries for B.Tech & Placements (2026)
30 min · Intermediate
PythonPython for Beginners: 15-Day Complete Learning Plan
15 min · Beginner
ReactReact Hooks Explained: useState, useEffect, useContext & More
14 min · Intermediate
DSAData Structures and Algorithms: Full Fundamentals + Interview Prep
35 min · Intermediate
JavaTop 50 Java Interview Questions — B.Tech Placements 2026
18 min · Advanced
Your feedback helps us improve notes and tutorials.