Difference between var and let keyword in JavaScript - 3#

Опубликовано: 20 Март 2024
на канале: Everyday Be Coding
12
2

In JavaScript, both var and let are used for variable declarations, but they have some differences in terms of scope and hoisting.

Scope:

Variables declared with var are function-scoped. This means they are visible throughout the function in which they are declared, regardless of block scopes within that function.
Variables declared with let are block-scoped. This means they are only visible within the block (enclosed by curly braces {}) in which they are declared, such as if, for, or while blocks.
Hoisting:

Variables declared with var are hoisted to the top of their scope and initialized with undefined. This means you can access the variable before it's declared in the code, but its value will be undefined.
Variables declared with let are hoisted to the top of their block scope but are not initialized. Accessing them before the actual declaration will result in a ReferenceError.
Here's a simple example to illustrate these differences:

function example() {
console.log(x); // Output: undefined
var x = 5;
console.log(x); // Output: 5
}

function anotherExample() {
console.log(y); // ReferenceError: Cannot access 'y' before initialization
let y = 10;
console.log(y); // Output: 10
}

example();
anotherExample();
In the example() function, var x is hoisted to the top, so the first console.log(x) prints undefined. In contrast, in the anotherExample() function, let y is hoisted but not initialized, so trying to access it before its declaration results in a ReferenceError.

Chapter :
00:00 Difference between var and let keyword in JavaScript
00:20 Scope
01:08 Hoisting
01:45 Examples


Thank you
EVERYDAY BE CODING


Смотрите видео Difference between var and let keyword in JavaScript - 3# онлайн без регистрации, длительностью часов минут секунд в хорошем качестве. Это видео добавил пользователь Everyday Be Coding 20 Март 2024, не забудьте поделиться им ссылкой с друзьями и знакомыми, на нашем сайте его посмотрели 1 раз и оно понравилось людям.