Jul 11, 2024
function funcOne() {
var age = 29;
function funcTwo() {
console.log(age);
}
return funcTwo;
}
var newFunc = funcOne();
newFunc(); // prints 29
function outer() {
let age = 29;
function inner() {
console.log(age);
}
age = 30;
return inner;
}
const innerFunc = outer();
innerFunc(); // prints 30
function createElementCreator(type) {
return function() {
return document.createElement(type);
}
}
const createDiv = createElementCreator('div');
const createSpan = createElementCreator('span');
const divEl = createDiv();
const spanEl = createSpan();
let
vs var
in loops
var
behavior:
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
// Prints 3, 3, 3
let
behavior:
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
// Prints 0, 1, 2
var
has function scope, leading to a single i
variable shared across all iterations.let
has block scope, creating a new i
for each iteration.