Objects, Methods, Scope & Hoisting
Objects store key-value pairs in { }. Keys are strings (or symbols); values can be any type.
Object Literals
Objects store key-value pairs in { }. Keys are strings (or symbols); values can be any type.
Real-life example: A student file — name, roll, class — all details on one card.
const user = {
name: "Asha",
age: 16,
city: "Delhi",
};
console.log(user.name); // dot notation
console.log(user["city"]); // bracket notationProperties and Methods
A property holds data. A method is a function inside an object.
Real-life example: A phone object — brand (property), call() (method you can use).
const calc = {
brand: "Simple",
add(a, b) {
return a + b;
},
};
console.log(calc.add(2, 3)); // 5this (brief)
Inside a method, this refers to the object that owns the method.
Real-life example: When you say "my phone", "my" points to you — this points to the object calling the method.
const shop = {
name: "Rishtaara",
welcome() {
return "Welcome to " + this.name;
},
};
console.log(shop.welcome());Scope — global, function, block
Scope is where a variable can be used. Global — whole program. Function — inside that function. Block — inside { } with let/const.
Real-life example: Global = school notice board (everyone sees). Function = one classroom diary. Block = one desk drawer.
const globalVar = "everywhere";
function demo() {
const fnVar = "inside function";
if (true) {
const blockVar = "inside block";
console.log(blockVar); // OK
}
// console.log(blockVar); // Error
}Hoisting (brief)
var declarations and function declarations are moved to the top of their scope in memory — but only var is initialized as undefined until the line runs.
let and const are hoisted but not usable before the line — Temporal Dead Zone.
Real-life example: Hoisting is like reserving a seat name before the person sits — var seat exists empty early; let seat is locked until arrival.
console.log(x); // undefined (var hoisted)
var x = 5;
// console.log(y); // Error — let not initialized yet
let y = 10;