
📦 Basics
// Declare variables
let x = 10; // Block scoped (ES6)
const y = 5; // Constant, also block scoped
var z = 3; // Function scoped (legacy, avoid using)
// Data types
let name = "John"; // string
let age = 30; // number
let isOnline = true; // boolean
let person = { name, age }; // object
let fruits = ["apple", "banana"]; // array
let nothing = null; // null
let notDefined; // undefined
💡 TIP
Prefer let
and const
over var
to avoid scope-related bugs.
🔁 Operators
// Arithmetic
+, -, *, /, %, **
// Comparison
==, ===, !=, !==, >, <
// Logical
&&, ||, !
// Assignment
=, +=, -=, *=, /=
// Nullish & Optional
?? // Nullish Coalescing (if null or undefined)
?. // Optional Chaining
🧠 NOTE
Always use ===
instead of ==
to avoid unexpected type coercion.
🧠 Control Flow
if (condition) {
// ...
} else if (anotherCondition) {
// ...
} else {
// ...
}
switch (value) {
case 1:
break;
default:
break;
}
for (let i = 0; i < 5; i++) { }
while (true) { }
do {
// runs at least once
} while (false);
// Ternary
let result = condition ? "yes" : "no";
💡 TIP
Use switch
when checking against multiple fixed values.
🧰 Functions
function greet(name) {
return `Hello, ${name}`;
}
const greet = (name) => `Hello, ${name}`;
// Closure Example
function outer() {
let count = 0;
return function inner() {
count++;
return count;
};
}
const counter = outer();
counter(); // 1
counter(); // 2
🔍 NOTE
Closures are key in JavaScript. They let functions retain access to variables even after the outer function exits.
🧱 Arrays (Common Methods)
const arr = [1, 2, 3, 4];
arr.push(5); // ➕ Add to end
arr.pop(); // ➖ Remove from end
arr.unshift(0); // ➕ Add to start
arr.shift(); // ➖ Remove from start
arr.includes(3); // 🔍 Check if value exists
arr.indexOf(2); // 🔍 Index of value
arr.slice(1, 3); // 📦 Copy part of array
arr.splice(1, 1); // 🔧 Remove/replace at index
// Iteration
arr.forEach(n => console.log(n));
// Transformation
const doubled = arr.map(n => n * 2);
// Filtering
const even = arr.filter(n => n % 2 === 0);
// Reducing
const sum = arr.reduce((a, b) => a + b, 0);
// Finding
const found = arr.find(n => n > 2);
arr.sort((a, b) => a - b); // 🔃 Sort
arr.reverse(); // 🔁 Reverse
💬 TIP
Prefer .map
, .filter
, .reduce
for cleaner, functional-style programming.
🔤 Strings (Common Methods)
const str = "Hello, World!";
str.length;
str.toUpperCase();
str.toLowerCase();
str.includes("World");
str.indexOf("l");
str.lastIndexOf("l");
str.substring(0, 5);
str.slice(-6);
str.split(", ");
str.trim();
str.replace("World", "JS");
str.startsWith("Hello");
str.endsWith("!");
📝 NOTE
Strings are immutable in JS. All methods return a new string.
📚 Objects
const user = {
name: "Alice",
age: 25,
greet() {
return `Hi ${this.name}`;
}
};
user.name;
user["age"];
user.city = "NYC";
Object.keys(user);
Object.values(user);
Object.entries(user);
Object.hasOwn(user, 'age');
Object.assign({}, user);
💡 TIP
Use Object.entries()
+ forEach()
for key-value iteration.
⏳ Promises & Async/Await
const getData = () => {
return new Promise((resolve, reject) => {
setTimeout(() => resolve("Done"), 1000);
});
};
getData()
.then(console.log)
.catch(console.error);
// Async/Await
async function fetchData() {
try {
const res = await getData();
console.log(res);
} catch (e) {
console.error(e);
}
}
✅ TIP
Prefer async/await
for better readability in async code.
🔁 Loops with Arrays
for (let item of arr) {
console.log(item);
}
for (let index in arr) {
console.log(arr[index]);
}
arr.forEach(item => console.log(item));
⚠️ NOTE
Avoid using for...in
on arrays; it's better for objects.
🧪 Type Checking
typeof 42; // "number"
typeof null; // "object" (quirk!)
Array.isArray([]); // true
if (val == null) {
// true for null or undefined
}
val !== null && typeof val === 'object';
🔍 TIP
Use Array.isArray()
to distinguish between objects and arrays.
🕹️ DOM
// Selecting elements
const el = document.getElementById("id");
const all = document.querySelectorAll("div");
// Modifying elements
el.textContent = "Hello";
el.innerHTML = "<strong>Hi</strong>";
el.style.color = "red";
// Events
el.addEventListener("click", () => alert("Clicked!"));
🧠 TIP
Always add event listeners after DOM has loaded or inside DOMContentLoaded
.
🕵 Event Loop
console.log("Start");
setTimeout(() => console.log("Timeout"), 0);
Promise.resolve().then(() => console.log("Microtask"));
console.log("End");
// Output:
// Start
// End
// Microtask
// Timeout
📌 NOTE
Microtasks (Promises) are executed before macrotasks (setTimeout).
🧵 Storage
localStorage.setItem("name", "John");
localStorage.getItem("name");
sessionStorage.setItem("id", "123");
document.cookie = "user=Ali; path=/; expires=Fri, 31 Dec 2025 23:59:59 GMT";
🔐 TIP
LocalStorage persists until manually cleared; sessionStorage clears on tab close.
🌍 Fetch API
fetch("https://api.example.com")
.then(res => res.json())
.then(data => console.log(data));
async function fetchUser() {
const res = await fetch("https://api.example.com/user");
const user = await res.json();
console.log(user);
}
🧠 TIP
Always check .ok
in response for error handling.
🔐 ES6+ Features
const { name, age } = user; // Object Destructuring
const [a, b] = [1, 2]; // Array Destructuring
const add = (x, y = 0) => x + y;
const nums = [1, 2];
const more = [...nums, 3];
const obj1 = { a: 1 };
const obj2 = { ...obj1, b: 2 };
// Optional chaining
user?.address?.city;
// Nullish coalescing
let val = name ?? "Guest";
// Object.hasOwn
Object.hasOwn(user, 'name');
// Template literals
const greetMsg = `Hello, ${name}`;
💡 TIP
Use spread/rest to keep code short and immutable.
📦 Modules
// export.js
export const name = "Imtiyaz";
export default function greet() { }
// import.js
import greet, { name } from "./export.js";
📦 NOTE
ES Modules must use .mjs
or "type": "module"
in package.json
.
🧩 Misc
// Symbol
const sym = Symbol("id");
// Set
const set = new Set([1, 2, 2]);
set.add(3);
set.has(2);
set.delete(1);
// Map
const map = new Map();
map.set("name", "Ali");
map.get("name");
map.has("name");
🧠 TIP
Use Set
for uniqueness and Map
for complex key-value storage.
📘 Resources
✨ FINAL NOTE
JavaScript evolves quickly. Stay up-to-date, and keep experimenting!
Comments
Leave a Comment