-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathFunction Declarations and Expressions.js
More file actions
52 lines (23 loc) · 1.26 KB
/
Function Declarations and Expressions.js
File metadata and controls
52 lines (23 loc) · 1.26 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
// Good Read
// Functions in JavaScript are first class objects. That means they can be passed around like any other value. One common use of this feature is to pass an
// anonymous function as a callback to another, possibly an asynchronous function.
// The above function gets hoisted before the execution of the program starts; thus, it is available everywhere in the scope it was defined, even if called
// before the actual definition in the source.
// foo(); // Works because foo was created before this code runs
// function foo() {
// console.log('yup !');
// }
console.log(foo);
// foo(); // this raises a TypeError
var foo = function() {
// return true;
};
// But since assignments only happen at runtime, the value of foo will default to undefined before the corresponding code is executed.
// Named Function Expression
// Another special case is the assignment of named functions.
var foo = function bar() {
bar(); // Works
}
// bar(); // ReferenceError
// Here, bar is not available in the outer scope, since the function only gets assigned to foo; however, inside of bar, it is available.
// This is due to how name resolution in JavaScript works, the name of the function is always made available in the local scope of the function itself.