├── LICENSE
├── Notes
├── 1-ExecutionContext.md
├── 10-Closures.md
├── 11-setTimeout-closures.md
├── 12-JSInterview-Closures.md
├── 14-Functions.md
├── 15-Callbacks-EventListeners.md
├── 16-Async-EventLoops.md
├── 17-JSEngine-ChromeV8.md
├── 17-setTimeout().md
├── 2-Execution-CallStack.md
├── 3-Hoisting.md
├── 4-Fun-VarEnv.md
├── 5-Window-this.md
├── 6-Undef-NotDef.md
├── 7-Scope-LexEnv.md
├── 8-letConst-deadzone-errors.md
├── 9-BlockScope-Shadowing.md
└── README.md
└── README.md
/LICENSE:
--------------------------------------------------------------------------------
1 | Creative Commons Legal Code
2 |
3 | CC0 1.0 Universal
4 |
5 | CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
6 | LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
7 | ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
8 | INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
9 | REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
10 | PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
11 | THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
12 | HEREUNDER.
13 |
14 | Statement of Purpose
15 |
16 | The laws of most jurisdictions throughout the world automatically confer
17 | exclusive Copyright and Related Rights (defined below) upon the creator
18 | and subsequent owner(s) (each and all, an "owner") of an original work of
19 | authorship and/or a database (each, a "Work").
20 |
21 | Certain owners wish to permanently relinquish those rights to a Work for
22 | the purpose of contributing to a commons of creative, cultural and
23 | scientific works ("Commons") that the public can reliably and without fear
24 | of later claims of infringement build upon, modify, incorporate in other
25 | works, reuse and redistribute as freely as possible in any form whatsoever
26 | and for any purposes, including without limitation commercial purposes.
27 | These owners may contribute to the Commons to promote the ideal of a free
28 | culture and the further production of creative, cultural and scientific
29 | works, or to gain reputation or greater distribution for their Work in
30 | part through the use and efforts of others.
31 |
32 | For these and/or other purposes and motivations, and without any
33 | expectation of additional consideration or compensation, the person
34 | associating CC0 with a Work (the "Affirmer"), to the extent that he or she
35 | is an owner of Copyright and Related Rights in the Work, voluntarily
36 | elects to apply CC0 to the Work and publicly distribute the Work under its
37 | terms, with knowledge of his or her Copyright and Related Rights in the
38 | Work and the meaning and intended legal effect of CC0 on those rights.
39 |
40 | 1. Copyright and Related Rights. A Work made available under CC0 may be
41 | protected by copyright and related or neighboring rights ("Copyright and
42 | Related Rights"). Copyright and Related Rights include, but are not
43 | limited to, the following:
44 |
45 | i. the right to reproduce, adapt, distribute, perform, display,
46 | communicate, and translate a Work;
47 | ii. moral rights retained by the original author(s) and/or performer(s);
48 | iii. publicity and privacy rights pertaining to a person's image or
49 | likeness depicted in a Work;
50 | iv. rights protecting against unfair competition in regards to a Work,
51 | subject to the limitations in paragraph 4(a), below;
52 | v. rights protecting the extraction, dissemination, use and reuse of data
53 | in a Work;
54 | vi. database rights (such as those arising under Directive 96/9/EC of the
55 | European Parliament and of the Council of 11 March 1996 on the legal
56 | protection of databases, and under any national implementation
57 | thereof, including any amended or successor version of such
58 | directive); and
59 | vii. other similar, equivalent or corresponding rights throughout the
60 | world based on applicable law or treaty, and any national
61 | implementations thereof.
62 |
63 | 2. Waiver. To the greatest extent permitted by, but not in contravention
64 | of, applicable law, Affirmer hereby overtly, fully, permanently,
65 | irrevocably and unconditionally waives, abandons, and surrenders all of
66 | Affirmer's Copyright and Related Rights and associated claims and causes
67 | of action, whether now known or unknown (including existing as well as
68 | future claims and causes of action), in the Work (i) in all territories
69 | worldwide, (ii) for the maximum duration provided by applicable law or
70 | treaty (including future time extensions), (iii) in any current or future
71 | medium and for any number of copies, and (iv) for any purpose whatsoever,
72 | including without limitation commercial, advertising or promotional
73 | purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
74 | member of the public at large and to the detriment of Affirmer's heirs and
75 | successors, fully intending that such Waiver shall not be subject to
76 | revocation, rescission, cancellation, termination, or any other legal or
77 | equitable action to disrupt the quiet enjoyment of the Work by the public
78 | as contemplated by Affirmer's express Statement of Purpose.
79 |
80 | 3. Public License Fallback. Should any part of the Waiver for any reason
81 | be judged legally invalid or ineffective under applicable law, then the
82 | Waiver shall be preserved to the maximum extent permitted taking into
83 | account Affirmer's express Statement of Purpose. In addition, to the
84 | extent the Waiver is so judged Affirmer hereby grants to each affected
85 | person a royalty-free, non transferable, non sublicensable, non exclusive,
86 | irrevocable and unconditional license to exercise Affirmer's Copyright and
87 | Related Rights in the Work (i) in all territories worldwide, (ii) for the
88 | maximum duration provided by applicable law or treaty (including future
89 | time extensions), (iii) in any current or future medium and for any number
90 | of copies, and (iv) for any purpose whatsoever, including without
91 | limitation commercial, advertising or promotional purposes (the
92 | "License"). The License shall be deemed effective as of the date CC0 was
93 | applied by Affirmer to the Work. Should any part of the License for any
94 | reason be judged legally invalid or ineffective under applicable law, such
95 | partial invalidity or ineffectiveness shall not invalidate the remainder
96 | of the License, and in such case Affirmer hereby affirms that he or she
97 | will not (i) exercise any of his or her remaining Copyright and Related
98 | Rights in the Work or (ii) assert any associated claims and causes of
99 | action with respect to the Work, in either case contrary to Affirmer's
100 | express Statement of Purpose.
101 |
102 | 4. Limitations and Disclaimers.
103 |
104 | a. No trademark or patent rights held by Affirmer are waived, abandoned,
105 | surrendered, licensed or otherwise affected by this document.
106 | b. Affirmer offers the Work as-is and makes no representations or
107 | warranties of any kind concerning the Work, express, implied,
108 | statutory or otherwise, including without limitation warranties of
109 | title, merchantability, fitness for a particular purpose, non
110 | infringement, or the absence of latent or other defects, accuracy, or
111 | the present or absence of errors, whether or not discoverable, all to
112 | the greatest extent permissible under applicable law.
113 | c. Affirmer disclaims responsibility for clearing rights of other persons
114 | that may apply to the Work or any use thereof, including without
115 | limitation any person's Copyright and Related Rights in the Work.
116 | Further, Affirmer disclaims responsibility for obtaining any necessary
117 | consents, permissions or other rights required for any use of the
118 | Work.
119 | d. Affirmer understands and acknowledges that Creative Commons is not a
120 | party to this document and has no duty or obligation with respect to
121 | this CC0 or use of the Work.
122 |
--------------------------------------------------------------------------------
/Notes/1-ExecutionContext.md:
--------------------------------------------------------------------------------
1 | # Episode 1 : Execution Context
2 |
3 | ### Everything in JS happens inside the execution context.
4 |
5 | Assume execution context to be a big box where everything takes place. It has 2 components in it:
6 |
Memory : The place where all the variables and functions are stored as (key:value) pairs. Memory component is also known as variable environment.
7 |
Code : The place where code is executed one line at a time. Code component is also known as Thread of Execution
8 |
9 | ### JS is a synchronous single-threaded language.
10 |
By single threaded, we mean JS can only run 1 command at a time
11 |
By synchronous single threaded, we mean it can run 1 command at a time, in a specific order
12 |
--------------------------------------------------------------------------------
/Notes/10-Closures.md:
--------------------------------------------------------------------------------
1 | # Episode 10 : Closures in JS
2 |
3 | ### Important Interview Question
4 |
5 | **Closure :** Function bundled together with its lexical environment/scope.
6 |
7 | ```
8 | JS is a weird language. You can pass functions as parameters to another function, assign a variable to an entire function, or even return a function.
9 | eg:
10 |
11 | function x() {
12 | var a = 7;
13 | function y() {
14 | console.log(a);
15 | }
16 | return y; // instead of y();
17 | }
18 | var z = x();
19 | console.log(z); // value of z is entire code of function y.
20 |
21 | ```
22 |
23 | When functions are returned from another fun, they still maintain their lexical
24 | scope.
25 |
26 | - When y is returned, not only is the fun returned but the entire closure (fun
27 | y + its lexical scope) is returned and put inside z. So when z is used
28 | somewhere else in program, it still remembers var a inside x()
29 | - Closure is a very powerful concept of JS, just because this function remembers
30 | things even if they are not in their lexical scope
31 |
32 | ### Uses of Closure
33 |
34 | Module Design Pattern, Currying, Functions like once(fun that can be run only
35 | once), memoize, maintaining state in async world, setTimeout, iterators...
36 |
--------------------------------------------------------------------------------
/Notes/11-setTimeout-closures.md:
--------------------------------------------------------------------------------
1 | # Episode 11 : setTimeout + Closures Interview Question
2 |
3 | #### Time, tide and Javascript wait for none
4 |
5 | ```
6 | function x() {
7 | var i = 1;
8 | setTimeout(function() {
9 | console.log(i);
10 | }, 3000);
11 | console.log("This is Hari");
12 | }
13 | x();
14 |
15 | ```
16 | > This is Hari
17 |
18 | > 1 //after waiting 3 seconds (3000ms)
19 |
20 | We expect JS to wait 3 sec, print 1 and then go down and print the string. But JS prints string immediately, waits 3 sec and then prints 1.
21 |
22 | - The fun inside setTimeout forms a closure (remembers reference to i). So wherever fun goes it carries this ref along with it.
23 | - setTimeout takes this callback function & attaches timer of 3000ms and stores it. Goes to next line without waiting and prints string.
24 | - After 3000ms runs out, JS takes function, puts it into call stack and runs it.
25 |
26 | #### Print 1 after 1 sec, 2 after 2 sec till 5 : Tricky interview question
27 |
28 | We assume this has a simple approach as below
29 |
30 | ```
31 | function x() {
32 | for(var i = 1; i<=5; i++){
33 | setTimeout(function() {
34 | console.log(i);
35 | }, i*1000);
36 | }
37 | console.log("This is Hari");
38 | }
39 | x();
40 |
41 | ```
42 |
43 | > This is Hari
44 |
45 | > 6
46 |
47 | > 6
48 |
49 | > 6
50 |
51 | > 6
52 |
53 | > 6
54 |
55 | - This happens because of closures. When setTimeout stores the function somewhere and attaches timer to it, the fun remembers its reference to i, **not value of i**
56 | - All 5 copies of fun point to same reference of i.
57 | - JS stores these 5 functions, prints string and then comes back to the functions. By then the timer has run fully. And due to looping, the i value became 6. And when the
58 | callback fun runs the variable i = 6. So same 6 is printed in each log
59 | - **To stop this from happening, use let instead of var** as let has black scope. For each iteration, the i is a new variable altogether(new copy of i).
60 | - Everytime setTimeout is run, the inside fun forms closure with new variable i
61 |
62 | #### Using let instead of var is the best option. But if asked to use var only..?
63 |
64 | ```
65 | function x() {
66 | for(var i = 1; i<=5; i++){
67 | function close(i) {
68 | setTimeout(function() {
69 | console.log(i);
70 | }, i*1000);
71 | // put the setT fun inside new function close()
72 | }
73 | close(i); // everytime you call close(i) it creates new copy of i. Only this time, it is with var itself!
74 | }
75 | console.log("This is Hari");
76 | }
77 | x();
78 |
79 | ```
80 |
81 |
--------------------------------------------------------------------------------
/Notes/12-JSInterview-Closures.md:
--------------------------------------------------------------------------------
1 | ## Only the important new concepts
2 |
3 | - Closures are used in encapsulation and data hiding.
4 |
5 | ```
6 | (without closures)
7 | var count = 0;
8 |
9 | function increment(){
10 | count++;
11 | }
12 |
13 | in this code, anyone can access count and change it.
14 |
15 | (with closures) -> put everything into a function
16 |
17 | function counter() {
18 | var count = 0;
19 |
20 | function increment(){
21 | count++;
22 | }
23 | }
24 | console.log(count); // this will give referenceError as count can't be accessed.
25 |
26 | (inc with function using closure)
27 |
28 | function counter() {
29 | var count = 0;
30 | return function increment(){
31 | count++;
32 | console.log(count);
33 | }
34 | }
35 | var counter1 = counter(); //counter fun has closure with count var.
36 | counter1(); // increments counter
37 |
38 | Above code is not good and scalable for say, when you plan to implement decrement counter at a later stage.
39 | To address this issue, we use constructors
40 |
41 | Adding decrement counter and refactoring code:
42 |
43 | function Counter() { //constructor function. Good coding would be to capitalize first letter of ctor fun.
44 | var count = 0;
45 | this.incrementCounter = function(){ //anonymous function
46 | count++;
47 | console.log(count);
48 | }
49 | this.decrementCounter = function(){
50 | count--;
51 | console.log(count);
52 | }
53 | }
54 |
55 | var counter1 = new Counter(); // new keyword for ctor fun
56 | counter1.incrementCounter();
57 | counter1.incrementCounter();
58 | counter1.decrementCounter();
59 |
60 | // returns 1 2 1
61 |
62 | ```
63 | ### Disadvantages of closure
64 | - Overconsumption of memory when using closure as everytime as those closed over variables are not garbage collected till program expires.
65 | So when creating many closures, more memory is accumulated and this can create memory leaks if not handled.
66 | - **Garbage collector** : Program in JS engine or browser that frees up unused memory. In highlevel languages like C++ or JAVA, garbage collection is left to the
67 | programmer, but in JS engine its done implicitly.
68 |
69 | ```
70 | function a() {
71 | var x = 0;
72 | return function b() {
73 | console.log(x);
74 | }
75 | }
76 |
77 | var y = a(); // y is a copy of b()
78 | y();
79 |
80 | Once a() is called, its element x should be garbage collected ideally. But fun b has closure over var x. So mem of x cannot be freed.
81 | Like this if more closures formed, it becomes an issue. To tacke this, JS engines like v8 and Chrome have smart garbage collection mechanisms.
82 | Say we have var x = 0, z = 10 inabove code. When console log happens, x is printed as 0 but z is removed automatically.
83 |
84 | ```
--------------------------------------------------------------------------------
/Notes/14-Functions.md:
--------------------------------------------------------------------------------
1 | # Episode 14 : First class and Anonymous functions
2 |
3 | (there is no Episode 13 idk why lol)
4 |
5 | #### Function statement : Just your normal function definition
6 |
7 | ```
8 | function a() {
9 | console.log("a called");
10 | }
11 | a();
12 |
13 | ```
14 |
15 | #### Function Expression : Assigning a function to a variable. Function acts like a value
16 |
17 | ```
18 | var b = function() {
19 | console.log("b called");
20 | }
21 | b();
22 |
23 | ```
24 |
25 | **Difference btw function statement and expression is Hoisting**
26 | - You can put "a();" before "function a()" and it will still work. But putting "b();" before "var b = function()" throws a typeError.
27 | - Why? During mem creation phase a is created in memory and function assigned to a. But b is created like a variable (b:undefined) and until code reaches the function()
28 | part, it is still undefined. So it cannot be called.
29 |
30 | #### Function Declaration : Exactly same as function statement
31 |
32 | #### Anonymous Function : A function without a name
33 | - They don't have their own identity. So an anony function without code inside it results in an error.
34 | - Anony functions are used when functions are used as values eg. the code sample for function expression above
35 |
36 | #### Named Function Expression : Same as Function Expression but function has a name instead of being anonymous
37 | ```
38 | var b = function xyz() {
39 | console.log("b called");
40 | }
41 | b(); // prints "b called" properly
42 | xyz(); // Throws ReferenceError:xyz is not defined.
43 |
44 | ```
45 | > xyz function is not created in global scope. So it can't be called.
46 |
47 | #### Parameters vs Arguments
48 | ```
49 | var b = function(param1, param2) { // labels/identifiers that get the arg values
50 | console.log("b called");
51 | }
52 | b(arg1, arg2); // arguments - values passed inside function call
53 |
54 | ```
55 | #### First Class Function aka First Class Citizens
56 | - You can pass functions inside a function as arguments(WOW!)
57 |
58 | ```
59 | var b = function(param1) {
60 | console.log(param1); // prints " f() {} "
61 | }
62 | b(function(){
63 |
64 | });
65 |
66 | this can also be done:
67 |
68 | var b = function(param1) {
69 | console.log(param1);
70 | }
71 | function xyz(){
72 |
73 | }
74 | b(xyz); // same thing as prev code
75 |
76 | you can return a function from a function:
77 |
78 | var b = function(param1) {
79 | return function() {
80 |
81 | }
82 | }
83 | console.log(b()); //we log the entire fun within b.
84 |
85 | ```
86 | #### Arrow Functions (latest in ES6 (ECMAScript 2015) -> coming in future lecture
87 |
88 |
--------------------------------------------------------------------------------
/Notes/15-Callbacks-EventListeners.md:
--------------------------------------------------------------------------------
1 | # Episode 15 : Callbacks and Event Listeners
2 |
3 | **Callback Function :** Functions are first class citizens (see prev lecture) ie. take a fun A and pass it to another fun B. Here, A is a callback function
4 | - JS is a synchronous and singlethreaded language. But due to callbacks, we can do async things in JS.
5 |
6 | > setTimeout(function () {}, 1000) -> here the anony function is a callback function as it is passed to setT and called sometime later in code after certain time (here 1000ms).
7 | - This is how we do async things. JS is a synch language, but it doesn't wait 1 sec for setT to finish before going to code below it. It stores the function, attaches timer
8 | and goes down the code.
9 |
10 | ```
11 | setTimeout(function () {
12 | console.log("timer");
13 | }, 5000);
14 |
15 | function x(y) {
16 | console.log("x");
17 | y();
18 | }
19 |
20 | x(function y() {
21 | console.log("y");
22 | });
23 | ```
24 |
25 | > x
26 |
27 | > y
28 |
29 | > timer
30 |
31 | - In the call stack, first x and y are present. After completion, they go away and stack is empty. Then after 5 seconds(from beginning) anonymous suddenly pops up in stack ie. setTimeout
32 | - All 3 functions are executed through call stack. If any operation blocks the call stack, its called **blocking the main thread**
33 | - Say if x() takes 30 sec to run, then JS has to wait for it to finish as it has only 1 call stack/1 main thread. *Never block main thread*.
34 | - **Always use async for functions that take time eg. setTimeout**
35 |
36 | **Event Listener**
37 |
38 | - When we create a button in HTML and attack a clickListener in JS :
39 | ```
40 | in index.html
41 |
42 |
43 |
44 | in index.js
45 |
46 | document.getElementById("clickMe").addEventListener("click", function xyz(){ //when event click occurs, this callback function is called into callstack
47 | console.log("Button clicked");
48 | });
49 | ```
50 | Suppose we want to increase count by 1 each time button clicked.
51 | - Use global variable (not good as anyone can change it)
52 |
53 | ```
54 | let count = 0;
55 | document.getElementById("clickMe").addEventListener("click", function xyz(){
56 | console.log("Button clicked", ++count);
57 | });
58 | ```
59 | - Use closures for data abstraction
60 |
61 | ```
62 | function attachEventList() { //creating new fun for closure
63 | let count = 0;
64 | document.getElementById("clickMe").addEventListener("click", function xyz(){
65 | console.log("Button clicked", ++count); //now callback fun forms closure with outer scope(count)
66 | });
67 | }
68 | attachEventList();
69 | ```
70 |
71 | #### Garbage Collection and removeEventListeners
72 | - Event listeners are heavy as they form closures. So even when call stack is empty, EventListener won't free up memory allocated to *count* as it doesn't know
73 | when it may need *count* again.
74 | - **So we remove event listeners when we don't need them (garbage collected)**
75 | - onClick, onHover, onScroll all in a page can slow it down heavily.
76 |
--------------------------------------------------------------------------------
/Notes/16-Async-EventLoops.md:
--------------------------------------------------------------------------------
1 | # Episode 16 : Asynchronous JS and Event Loops
2 |
3 | > Note that call stack will execeute any execeution context which enters it. Time, tide and JS waits for none. TLDR : Call stack has no timer
4 |
5 | **Browser has JS Engine which has Call Stack which has Global exec context, local exec context etc**
6 | - But browser has many other *superpowers* - Local storage space, Timer, place to enter URL, Bluetooth access, Geolocation access and so on
7 | - Now JS needs some way to connect the callstack with all these superpowers. This is done using **Web APIs**
8 |
9 | ### WebAPIs
10 | None of the below are part of Javascript! These are extra superpowers that browser has. Browser gives access to JS callstack to use these powers.
11 | > setTimeout(), DOM APIs, fetch(), localstorage, console (yes, even console.log is not JS!!), location and so many more..
12 |
13 | - setTimeout() : Timer function
14 | - DOM APIs : eg.Document.xxxx ; Used to access HTML