Module 1: Objects & Modern Syntax
Object Basics
let user = { name: "Chiru", age: 25, isAdmin: true };
user.name; // dot notation → "Chiru"
user["age"]; // bracket notation → 25
let key = "name";
user[key]; // bracket notation with a dynamic key → "Chiru"
user.email = "chiru@example.com"; // add a property
user.age = 26; // update a property
delete user.email; // remove a property
let counter = {
count: 0,
increment() { // shorthand method syntax
this.count++;
}
};
counter.increment();
console.log(counter.count); // 1
Object.keys(user); // array of keys
Object.values(user); // array of values
Object.entries(user); // array of [key, value] pairs
Destructuring
let user = { name: "Chiru", age: 25, city: "Delhi" };
let { name, age } = user; // pulls values into their own variables
let { name: fullName } = user; // rename while destructuring
let { country = "India" } = user; // default value if property doesn't exist
// Very common in function parameters
function printUser({ name, age }) {
console.log(name, age);
}
printUser(user);
let [first, second] = ["red", "green", "blue"]; // array destructuring, by position
Spread & Rest Operators
Both use ..., in opposite directions:
// Spread — expands an array/object out
let nums = [1, 2, 3];
let more = [...nums, 4, 5]; // [1, 2, 3, 4, 5]
let obj1 = { a: 1, b: 2 };
let obj2 = { ...obj1, c: 3 }; // { a: 1, b: 2, c: 3 }
let copy = [...nums]; // copy without mutating the original
// Rest — gathers remaining items INTO an array
function total(...numbers) {
return numbers.reduce((sum, n) => sum + n, 0);
}
total(1, 2, 3, 4); // 10
let [first, ...rest] = [1, 2, 3, 4];
console.log(rest); // [2, 3, 4]
Optional Chaining & Nullish Coalescing
let user = { profile: null };
// Optional chaining — safely reads nested properties, no error if missing
user.profile?.name; // undefined, no crash
user.profile?.address?.city; // undefined, safely stops at the first missing link
// Nullish coalescing — falls back only on null/undefined
let value = user.profile ?? "No profile"; // "No profile"
Date, Math, JSON & RegExp
// Date
let now = new Date();
now.getFullYear();
now.getMonth(); // 0-indexed! January is 0
now.getDate();
now.toISOString();
// Math
Math.round(4.7); // 5
Math.floor(4.7); // 4
Math.ceil(4.1); // 5
Math.max(1, 5, 3); // 5
Math.min(1, 5, 3); // 1
Math.random(); // 0 to 1
// JSON — converting between objects and text (crucial for APIs, covered more in Module 2)
JSON.stringify({ name: "Chiru" }); // '{"name":"Chiru"}'
JSON.parse('{"name":"Chiru"}'); // { name: "Chiru" }
// Regular Expressions — pattern matching in text
let pattern = /^[\w.]+@[\w.]+\.\w+$/; // a simple email pattern
pattern.test("chiru@example.com"); // true
"Hello World".replace(/o/g, "0"); // "Hell0 W0rld"