You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
In the above code, we have a function called hoisting() where we did not declare a variable using let/var/const and another variable declared with let. As mentioned above, _assigning the undeclared variable to the global scope is done by JavaScript_. Hence, age variable is availabe even outsode of scope(globally) but the scope of name variable is within the function, so we get the ReferenceError.
270
+
271
+
### Hoisting with let/cosnt
272
+
273
+
In ES6, _let_ does not allow us to use undeclard variables and throws a ReferenceError. This makes sure that we always declare our variable first.
274
+
275
+
**Example 1:**
276
+
277
+
```js
278
+
console.log(num);
279
+
//OUTPUT: ReferenceError: Cannot access 'num' before initialization
280
+
281
+
letnum=20;
282
+
283
+
console.log(num); //OUTPUT: 20
284
+
```
285
+
286
+
Let's have a look at another example:
287
+
**Example 2:**
288
+
289
+
```js
290
+
console.log(number2);
291
+
//OUTPUT: ReferenceError: number2 is not defined.
292
+
293
+
letnumber=20;
294
+
```
295
+
296
+
**_Do you notice something different in example 1 and 2?_**
297
+
298
+
The error in example 1 says: _ReferenceError: Cannot access 'num' before initialization_ but the error in example 2 is _ReferenceError: number2 is not defined_
299
+
300
+
The error "is not defined" means our JavaScript engine has no idea what _number2_ variable is because we never defined it.
301
+
But the error "cannot access before initialization" means our JS engine knows the "num" variable since "num" is hoisted to the top of global scope.
302
+
303
+
_To summarize, variables declared with **let** or **const** are hoisted **without** a default initialization but the variables declared with **var** are hoisted **with** default initialization of undefined._
304
+
305
+
#### Temproal Dead Zone
306
+
307
+
This is a period during execution where _let/const_ variables are hoisted but not accessible.
0 commit comments