File tree 4 files changed +110
-2
lines changed
4 files changed +110
-2
lines changed Original file line number Diff line number Diff line change
1
+ function greet ( whatToSay ) {
2
+ return function ( name ) {
3
+ console . log ( `${ whatToSay } : ${ name } ` )
4
+ }
5
+ }
6
+
7
+ greet ( 'Hi' ) ( 'ashfaq' ) ;
8
+
9
+ var sayHi = greet ( 'Hi' ) ;
10
+ // function have access to the variable{whatToSay} of outer scope event it is invoked outside of the scope{execution context}
11
+
12
+ sayHi ( "Kranthi" ) ;
13
+
14
+
15
+
16
+
17
+ function build ( ) {
18
+ var arr = [ ] ;
19
+ for ( var i = 0 ; i < 3 ; i ++ ) {
20
+ arr . push (
21
+ function ( ) {
22
+ console . log ( i )
23
+ }
24
+ )
25
+ }
26
+ return arr ;
27
+ }
28
+
29
+ var fs = build ( ) ;
30
+
31
+ fs [ 0 ] ( ) ; //3
32
+ fs [ 1 ] ( ) ; //3
33
+ fs [ 2 ] ( ) ; //3
34
+
35
+
36
+ // solution1 Old school By using IIFE
37
+ function build2 ( ) {
38
+ var arr = [ ] ;
39
+ for ( var i = 0 ; i < 3 ; i ++ ) {
40
+ arr . push (
41
+ ( function ( j ) {
42
+ return function ( ) {
43
+ console . log ( j )
44
+ }
45
+ } ( i ) )
46
+ )
47
+ }
48
+ return arr ;
49
+ }
50
+
51
+ var fs2 = build2 ( ) ;
52
+
53
+ fs2 [ 0 ] ( ) ; //3
54
+ fs2 [ 1 ] ( ) ; //3
55
+ fs2 [ 2 ] ( ) ; //3
56
+
57
+
58
+ // ES6 solution By using let
59
+
60
+
61
+ function build3 ( ) {
62
+ var arr = [ ] ;
63
+ for ( let i = 0 ; i < 3 ; i ++ ) {
64
+ arr . push (
65
+ function ( ) {
66
+ console . log ( i )
67
+ }
68
+ )
69
+ }
70
+ return arr ;
71
+ }
72
+
73
+ var fs3 = build3 ( ) ;
74
+
75
+ fs3 [ 0 ] ( ) ; //3
76
+ fs3 [ 1 ] ( ) ; //3
77
+ fs3 [ 2 ] ( ) ; //3
Original file line number Diff line number Diff line change
1
+ // Function declaration or Function statement
2
+ function greet ( name ) {
3
+ console . log ( `Hello ${ name } ` ) ;
4
+ }
5
+ greet ( 'ashfaq' )
6
+
7
+
8
+
9
+ // Function Expression { function is created on the fly}
10
+ // Expression Returns something
11
+ var greetName = function ( name ) {
12
+ console . log ( `Hello ${ name } ` ) ;
13
+ } ;
14
+
15
+ greetName ( 'ansari' ) ;
16
+
17
+ // IIFE Immediately invoking function expression
18
+ //VERSION 1
19
+ ( function ( name ) {
20
+ console . log ( `Hello ${ name } ` ) ;
21
+ } ( 'Walter' ) ) ;
22
+
23
+ //VERSION 2
24
+
25
+ ( function ( name ) {
26
+ console . log ( `Hello ${ name } ` ) ;
27
+ } ) ( 'Walter' ) ;
28
+
29
+
30
+
31
+
Original file line number Diff line number Diff line change 6
6
< meta charset ="utf-8 "/>
7
7
8
8
<!-- <script src="collection.js"></script> -->
9
- < script src ="semiColonInjection .js "> </ script >
9
+ < script src ="closures .js "> </ script >
10
10
</ body >
11
11
</ html >
Original file line number Diff line number Diff line change 1
1
function returnsNothing ( ) {
2
- return //Automatic Semicolon (;) will be injected By syntax Parser.
2
+ return //Automatic Semicolon (;) will be injected By syntax Parser.
3
3
{
4
4
key : 'value'
5
5
}
You can’t perform that action at this time.
0 commit comments