-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhoisting.js
More file actions
66 lines (51 loc) · 1.14 KB
/
hoisting.js
File metadata and controls
66 lines (51 loc) · 1.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*
What is hoisting?
- Moving something to the top of its scope.
In case of variable hoisting, variable declaration will be moved to the top of its scope.
In case of function hoisting, function definition will be moved to the top of its scope.
*/
"use strict"
// variable hoisting.
console.log(a);
var a = 100;
/*
The above code will be converted as below by JS engine.
var a;
console.log(a);
a = 100;
*/
// function hoisting
fun();
function fun() {
console.log('Its so much fun!');
}
/*
Internally:
function fun() {
console.log('Its so much fun!');
}
fun();
*/
// more variable hoisting
function foo() {
console.log(b);
var b = 'bar';
}
// console.log(b);
/*
The above statement throws an error because variables are hoisted to the top of its scope.
Scope of b is that enclosing foo function not the window. That's why access b outside it scope causes JS to throw error.
*/
// more hoisting
// c(); // This throws an error
var c = function () {
console.log('What the c?');
}
/*
Internally:
var c;
c();
c = function () {
console.log('What the c?');
}
*/