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
#### Q - What will be the output of the below code and why
2
+
3
+
```js
4
+
var number =10
5
+
vardisplay=function () {
6
+
console.log(number)
7
+
var number =20
8
+
}
9
+
display()
10
+
```
11
+
12
+
#### Ans - The output of the above code is not 10 but it’s undefined
13
+
14
+
#### Explanations
15
+
16
+
This is because of hoisting in Javascript.
17
+
Hoisting is JavaScript’s default behavior of moving declarations to the top of the current scope or block.
18
+
So the above code will be converted to below code
19
+
20
+
```js
21
+
var number =10
22
+
vardisplay=function () {
23
+
var number
24
+
console.log(number)
25
+
number =20
26
+
}
27
+
display()
28
+
```
29
+
30
+
As you can see only the declaration is moved to the start of the function and value is not hoisted so the console.log prints undefined because number does not have any value assigned inside the function before the console.log statement.
0 commit comments