Variables in JS have scope: var is function-scoped, let and const are
block-scoped.
function test() {
if (true) {
var x = 10; // function scoped
let y = 20; // block scoped
}
console.log(x); // ✅ 10
console.log(y); // ❌ ReferenceError
}
JS hoists declarations (not initializations). var is hoisted as undefined, but
let and const are not accessible before declaration.
console.log(a); // undefined var a = 5; console.log(b); // ReferenceError let b = 10;
A closure is when a function remembers its outer variables even after that outer function has finished executing.
function outer() {
let count = 0;
return function inner() {
count++;
return count;
}
}
const counter = outer();
console.log(counter()); // 1
console.log(counter()); // 2
The value of this depends on how a function is called. Arrow functions do not bind
this, they inherit it from their lexical scope.
const obj = {
name: 'JavaScript',
greet() {
console.log('Hello, ' + this.name);
},
};
obj.greet(); // Hello, JavaScript
Functions passed as arguments to be executed later.
function greet(name, callback) {
console.log('Hi ' + name);
callback();
}
greet('Dev', function() {
console.log('Welcome!');
});
Shorthand function syntax with no own this.
const add = (a, b) => a + b;
Backtick syntax for multiline and embedded expressions.
const name = 'Dev';
console.log(`Hello, ${name}!`);
Unpack values from arrays or properties from objects.
const [x, y] = [1, 2];
const {name} = {name: 'JS'};