- Refers to the current execution context.
- In global →
this
iswindow
(in browsers). - Inside objects → refers to that object.
Example:
let person = {
name: "Ali",
greet: function() {
console.log("Hello " + this.name);
}
};
person.greet(); //
this
is window
(in browsers).Example:
let person = {
name: "Ali",
greet: function() {
console.log("Hello " + this.name);
}
};
person.greet(); //
Answer:
this
is window
(in browsers).Example:
let person = {
name: "Ali",
greet: function() {
console.log("Hello " + this.name);
}
};
person.greet(); //
forEach()
→ Executes a function on each item, but returns undefined.map()
→ Transforms elements and returns a new array.Example:
let arr = [1, 2, 3];
arr.forEach(x => console.log(x * 2)); // prints 2, 4, 6
console.log(arr.map(x => x * 2)); // [2, 4, 6]
Example:
console.log("Start");
setTimeout(() => console.log("Callback"), 0);
console.log("End");
// Output: Start → End → Callback
Even with 0ms
, the async callback runs after synchronous code.
var
→ Function scoped.let
& const
→ Block scoped {}
.Example:
if (true) {
var x = 1; // accessible outside
let y = 2; // block scope
const z = 3; // block scope
}
console.log(x); // 1
// console.log(y); // error
this
.let add = (a, b) => a + b;
console.log(add(5, 3)); // 8
Example:
console.log("Start");
setTimeout(() => console.log("Async Task"), 2000);
console.log("End");
// Output: Start → End → (after 2 sec) Async Task
undefined
→ variable declared but not assigned.null
→ assigned value, meaning “nothing”.Example:
let a; // undefined
let b = null; // null
Example:
// Declaration
function greet() { return "Hello"; }
// Expression
let sayHi = function() { return "Hi"; };
Example:
console.log(a); // undefined
var a = 5;
var
is hoisted (declared but not initialized).let
and const
, hoisting happens too, but they remain in a temporal dead zone until declared.