Skip to content

Commit 2140152

Browse files
committed
adding tricky questions
1 parent beda320 commit 2140152

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
#### Q - What will be the output of the below code and why
2+
3+
```js
4+
var number = 10
5+
var display = 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+
var display = 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

Comments
 (0)