What I Learned Today:
Scope:
A variable's scope determines where it can be recognized and accessed within the code.
Types of Scope:
- Global Scope: Variables declared outside any function are accessible throughout the program.
- Local Scope: Variables declared inside a function are only accessible within that function.
Closures:
A closure is created when a function is defined inside another function, and the inner function has access to the variables and scope of the outer function.
Key Benefit: Closures help keep variables private, as they are encapsulated within the function.
Example:
function outerFunction() {
let outerVariable = "I'm private!";
return function innerFunction() {
console.log(outerVariable);
};
}
const myClosure = outerFunction();
myClosure(); // Output: I'm private!
Hoisting:
Hoisting allows certain declarations to be used before they are initialized in the code.
Key Points:
Only function declarations are fully hoisted, meaning they can be used before their actual definition in the code.
Variables declared using var
are partially hoisted but remain undefined until initialized. Variables declared with let or const are not hoisted in the same way.
Example:
sayHello(); // Output: Hello, World!
function sayHello() {
console.log("Hello, World!");
}
console.log(myVar); // Output: undefined
var myVar = 10;
It's getting better on a daily basis
Day 9 is about to be crushed.
Top comments (0)