Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 46b781e

Browse files
committed
Hoisting Complete
1 parent f35306f commit 46b781e

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

‎01-Javascript-Engine.md

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -267,3 +267,41 @@ console.log(age); // Output: 23
267267
**So what exactly happened here?**
268268
269269
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+
let num = 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+
let number = 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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /