0% found this document useful (0 votes)
3K views21 pages

Namaste JS

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3K views21 pages

Namaste JS

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Execution Context

25 June 2024 11:49

• When we run Javascript, an execution context is created


• A global execution context is created
Memory Code
• It is created in two phases
• Variable Environment Thread of execution ○ Memory creation phase
Key value pair Lines of code  Allocates the memory to all the variables and the functions
□ For variables: Stores the spatial value known as undefined

□ For functions: Literally stores the whole code inside the memory
square

• Javascript is a synchronous single-threaded language


• It means Javascript can execute one command at a time in
a specific order □


○ Code execution phase
 Once again runs through the whole code line by line
 The 2 is now allocated inside in the identifier


 When a function is invoked or executed, a new execution context is
created

Namaste JS Page 1
Call Stack
25 June 2024 11:55

• Whenever any JavaScript code is executed an execution context is created and it is the Global Execution Context.
• An Execution Context is basically a box which has two components called Memory Component(Variable Environment)
and Code Component(Thread Of Execution).
• The Execution context is created in two phases
○ Memory Creation Phase : In this Phase, Memory is allocated to all the variables and functions which are present in
the global scope. Special keyword Undefined in case of variables and literally the whole function in case of
functions.
○ Code Execution Phase : In this Phase, code is executed line by line.
• Whenever there is a function invocation an all new execution context is created and same process is followed again.
• If there is any function parameter then it is also allocated memory while creating the execution context of the function.
• Whenever return keyword is encountered , it means the task of function is over and it returns back the control of the
program back to the place where it was invoked. and with this this execution context is deleted from stack.
• Call Stack is basically a stack which maintains the order of execution of execution context. Whenever a code is executed
the Global Execution Context is pushed into the stack first and later on as per the function invocation the execution
context is pushed into the stack. When the function code is done executing the execution context is popped out and last
the Global Execution Context s also deleted.

Namaste JS Page 2
Hoisting
03 July 2024 11:01

• Hoisting in JavaScript is a process in which all the Variables, Functions and • In JS, before the code is executed, the variables get initialized to undefined.
Class definition are declared BEFORE execution of the code. • Arrow functions enact as variables and get "undefined" during the memory
• Variables are initialised to UNDEFINED when they are declared and creation phase while functions actually get run.
Function definition is stored AS IT IS. • Hoisting: Mechanism in JS where the variable declarations are moved to the
• They are declared in Memory Allocation Phase in the Memory Component top of the scope before execution. Therefore it is possible to call a function
of Execution Context, so we can use them even BEFORE they are declared. before initializing it.
• UNDEFINED means Variable has been declared but value is not ASSIGNED • Whenever a JS program is run, a global execution block is created, which
but NOT DEFINED means Variables is NOT DECLARED. comprises of 2: Memory creation and Code execution.
• When we assign Variable to a Function definition, we CAN NOT call this • Variable declarations are scanned and are made undefined.
Variable as Function BEFORE declaration as it will behave as Variable with • Function declarations are scanned and are made available
UNDEFINED value.

• Variable declarations are scanned and are made undefined.


• Function declarations are scanned and are made available

Namaste JS Page 3
How Functions work in Javascript
03 July 2024 11:07

• We learnt how functions work in JS.


• At first a global execution context is created, which consists of Memory and code and has 2 phases:
Memory allocation phase and code execution phase.
• In the first phase, the variables are assigned "undefined" while functions have their own code.
• Whenever there is a function declaration in the code, a separate local execution context gets created
having its own phases and is pushed into the call stack.
• Once the function ends, the EC is removed from the call stack.
• When the program ends, even the global EC is pulled out of the call stack.

• The higher level of the GEC on the stack, higher its preference.
• GEC is created as the function is invoked and destroyed as its execution is completed.
• Same variable names but different scope of execution separates the variable values
• The GEC term is used to simplify understanding the execution of main function, same
execution context is created if function is created inside the global function, as its stack
priority is high, given its preference and worked under the main (GEC) context same thing
happens when you create function > inside a function > inside a function (consider it as
staircase where upper step person is taller than person in lower step and hence it has
given preference ) local execution context introduced when inner function is in execution.

Namaste JS Page 4
Window and this
03 July 2024 11:12

• window object is created by the JS engines of the respective browsers when global • Reserves the memory space specifically for GEC to be created
execution context is created. in stack.
• whenever an execution context is created a "this" variable is also created. • GEC is created
• at the global level "this" points to the global object( window object in case of • Creates a 'Window': a javascript 'global object' which 'runs
browsers). with GEC' with an object whose values are in global scope(can
• anything that is not inside a function is the "global space". be accessed by using any of the key in 1:37 )
• whenever we create any variables or functions in the "global space", they get • js object 'this' is created (really the name is 'this') and this
attached to the global object( window object in case of browsers). so to access the level this=== windo
variables/function defined in the global space , we can use any of the below: • Then our script starts execution The variable in javascript
console.log(window.a); console.log(a); console.log(this.a) //at the global space level, always assigns its value from Global level (unless specified
where this points to the window object. earlier 'in the script' itself or in function) and if you defined a
variable (eg. a=10) : this.a===10; global.a===10;

• Shortest Program in JS: Empty file. Still, browsers make global EC and global space along
with Window object.
• Global Space: Anything that is not in a function, is in the global space.
• Variables present in a global space can be accessed by a "window" object. (like window.a)
• In global space, (this === window) object.

Namaste JS Page 5
Undefined vs not defined
03 July 2024 11:30

• Undefined is like a placeholder till a variable is not assigned a value.


• undefined !== not defined
• JS- weakly typed language since it doesn't depend on data type declarations.

• Undefined is a Special Placeholder which is used to reserve memory for the variables
in the memory creation phase. Even before a single line of code is executed JS engine
assigns undefined to the variables.
• Not Defined means if we try to console or access any variable which is not declared in
the code then we get Not Defined error.
• JS is a loosely typed language or weakly typed language means it does not attaches its
variables to specific data types like in C++ and java.
• Remember undefined !== not defined.

Namaste JS Page 6
Scope, Lexical Environment and Scope chain
03 July 2024 11:33
• Lexical environment = EC's Local Memory + Reference to Lexical Environment of its
parent.
• Scope of a variable is directly dependent on the lexical environment. • Lexical Environment of its parent is the scope where a function is physically present
• Whenever an execution context is created, a lexical environment is or defined. So, suppose a function x(), is defined and invoked in the GEC, when
created. Lexical environment is the local memory along with the lexical function x()'s EC is pushed in the call stack, it stores a reference to its parent's lexical
environment of its parent. Lexical as a term means in hierarchy or in environment i.e. the GEC's memory.
sequence. • Whenever a new Execution Context is pushed in the Call Stack it holds a reference to
• Having the reference of parent's lexical environment means, the child the Lexical Environment of its parent, i.e. the EC's memory from where it was
or the local function can access all the variables and functions defined invoked.
in the memory space of its lexical parent. • Global execution context holds reference to null.
• The JS engine first searches for a variable in the current local memory • Javascript engine first looks for the variable/function being accessed in the local
space, if its not found here it searches for the variable in the lexical scope of the function, and if not found, it keeps on searching the lexical environment
environment of its parent, and if its still not found, then it searches of its parent until it finds the variable/function being accessed.
that variable in the subsequent lexical environments, and the sequence • The mechanism mentioned in point 4 above is called SCOPE CHAIN.
goes on until the variable is found in some lexical environment or the • If the variable accessed is not found in the Scope Chain, then you will get the variable
lexical environment becomes NULL. is not defined error in the browser's console.
• The mechanism of searching variables in the subsequent lexical • Scope means where we can access specific function or variable in our code.
environments is known as Scope Chain. If a variable is not found
anywhere, then we say that the variable is not present in the scope
chain.

Namaste JS Page 7
Let, const and Temporal Dead Zone
03 July 2024 11:36

• let and const declarations are hoisted but very differently than variable • When to use var, let and const
• These are in the temporal dead zone ○ Always use const - first priority - whenever possible
• TEMPORAL DEAD ZONE: ○ Try let if not const - so we don't run into TDZ
○ It is the time since when let variable was hoisted and till the value is initialized. ○ Don't use var - use very consciously
○ let and const are hoisted in a separate space other than global
○ The phase from hoisting and the initialization is TDZ.
○ We can't access the variable if it is in TDZ
○ Reference error: can't access before initialization
• The var are attached to the window object. So we can access them using window.variable_name to print
• But const and let are not attached to the window object. They are maintained in the reserved space and
not global space
• Let is stricter than var • How to avoid temporal dead zone
○ We can't duplicate / reinitialize again the same let or const - syntax error ○ Always put declarations and
○ We can't name same for both let and var initializations on the top
○ We can do duplicate/reinitialize both var ○ We are shrinking the TDZ to zero if we
○ Const also behaves almost same as let but the difference is follow above step
 Const is even more strict than let.
 Let allows to declare without initializing and we can initialize let at any time in the code
 But const doesn't allow to do it - SYNTAX ERROR - MISSIN initializer in const declaration
 We definitely have to put some value if we declare const and can't do it later.
 If we try to change the const value by refining it we get - TYPE ERROR

• Difference between SYNTAX, TYPE and REFERENCE ERRORS


○ syntax error is similar to compile error.
○ while type and reference error falls under run time error.
○ syntax error ... violation of JS syntax
○ type error ... while trying to re-initialize const variable
○ reference error ... while trying to access variable which is not there in global
memory.

Namaste JS Page 8
Block Scope & Shadowing
{ // Compound statement
03 July 2024 14:37
Var a= 10;
Consloe.log(a);
• Block
}
○ Block is known as compound statement.
○ Block is used to combine multiple Javascript Statements into a single group
○ We need to group these multiple statements because we can use it where Javascript expects to see
a single statement

• Block Scope
○ What all var and functions we can access inside this block.
○ var is in global scope but let, const are in Block scope
○ Once the execution ends the block scope, it will be deleted
○ So, the let and const can only be accessible within the block

• Shadowing
○ The variable inside the block will shadow the outer variable.
○ If there are two variables with same name in Javascript one in block and other in global
 The block variable will shadow the global var.
 And it also modify the value of global var. So, once outside block also we have same value of
the variable as the blocked var.
○ But if we are doing the same for let & const, then the block let will shadow only in the block and
once the let is accessed outside that block, the global let will be accessed
○ SO, a separate space called script is created for let and const that are outside the block. Not in
global space
○ The shadowing behaves the same in the functions also.

• Illegal Shadowing
○ We cannot shadow a let/const variables with var inside the block
○ We can shadow let using a let
○ We can shadow var using let
○ Var is a functioned scope, so it is not considered illegal.

• Lexical scope
○ It is cope inside the scope. It follows block scope
○ The variable will try to access the nearest var

• Same rules work for arrow functions also

• Block :- It is used to combine multiple statement into one statement so that we can use it
at those places where Javascript expects to have single statement.
• Scope :- scope of a variable or a function is the place where these are accessible.
• Block scope :- The variables and function present within the scope of a block section. And
block follows the lexical scope chain pattern while accessing the variable.
• Shadowing :- Providing same name to the variable as of those variable which are present
in outer scope.

Namaste JS Page 9
Closures
05 July 2024 11:57

• Closure
○ A function bundled together with its lexical environment.
○ Function along with its lexical scope bundled together forms closure.
• We can pass the functions inside the function as a parameter
• We can return the functions outside of the functions
• Functions when returned also contains their lexical scope, so we can access
the variables
• In right picture, though x() will be removed for call stack and memory erased
it still y() remembers its lexical scope where it came from and binding etc.
• So when we execute z() anywhere in the program, it still remembers the function x(){
reference to a and try to find out value of a. let a = 10;
function y(){
• Corner cases console.log(a);
○ If we returned y() in beside code, the }
a=100;
Value of a,b wouldn't be return y;
garbage but they would retain }
its original values. It is closure var z = x();
z(); // a = 100 because the function
access reference not the value
• Uses/Advantages of Closures
○ Module Design Pattern
○ Currying
○ Functions like once - function only run once
○ Memoize
○ Maintaining state in async world Closure :Function bundled with its lexical environment is known as a closure. Whenever
○ setTimeouts function is returned, even if its vanished in execution context but still it remembers the
○ Iterators reference it was pointing to. Its not just that function alone it returns but the entire
○ Many more ……… closure and that's where it becomes interesting

1. An inner function can be directly called using two parenthesis ()().


2. Even parameters can be passed this way (Remember that the function needs to be returned
to do this)
3. Closures can also be used for data hiding and encapsulation. So other code cannot access this
value. 4. Unused variables are automatically deleted in High Level Programming language by
garbage collector. Closures allocate a lot of memory which cannot be deleted so this acts as a
disadvantage.
5. Some browsers now have smart garbage collectors that automatically deletes variables that
are not used outside closures.

Namaste JS Page 10
setTimeout & Closures Interview Question
05 July 2024 14:57

• setTimeout function x(){ C:\Program Files


○ The statements after Javascript doesn’t wait for the var i = 10; \nodejs\node.exe .
execution of setTimeout. They will be executed first setTimeout(function () { \index.js
○ Because the function forms a closure -> remembers console.log(i); Statement after
reference to i. }, 2000); setTimeout.
○ The setTimeout function do is it stores the callback function console.log("Statement 10
and stores it into some place and attaches a timer to it. The after setTimeout.")
Javascript proceeds to next line. }
○ Once the timer expires, setTimeout function takes back the x();
function from where it stored and puts it in the callStack and function x(){ C:\Program Files\nodejs\node.exe .\index.js
runs it. for(var i=1;i<=5;i++){ Statement after setTimeout
setTimeout(function () { 6
• The Function behaves this way because of the closures. As console.log(i); 6
mentioned earlier Javascript doesn’t wait for anything, the }, i * 1000); 6
for loop will be run first after that the setTimeout will be } 6
performed. console.log("Statement 6
• The closure remembers the reference of i not the value of after setTimeout")
i. So, the reference to the i will be the last updated value }
i.e. 6 x();

• USING let function x(){ C:\Program Files\nodejs\node.exe .\index.js


○ To fix it, we can use let instead of var because let has for(var i=1;i<=5;i++){ Statement after setTimeout
a block scope. So for each loop iteration, the i is new setTimeout(function () { 1
copy of i / new variable. That means the function console.log(i); 2
forms a closure with the new variable itself. }, i * 1000); 3
○ So each time the function is called, the i is in different } 4
memory location console.log("Statement 5
after setTimeout")
}
• USING var only x();
○ To fix the problem using var itself, we have to
wrap/enclose the setTimeout inside a new function x(){ C:\Program Files\nodejs\node.exe .\index.js
function say close(). for(var i=1;i<=5;i++){ Statement after setTimeout
○ We will be forming closure. And we have to function close(x){ 1
supply the new value of i every time. setTimeout(function (){ 2
console.log(x); 3
}, x*1000); 4
} 5
close(i)
}
console.log("Statement after
setTimeout");
}
x();

Namaste JS Page 11
First Class Functions & Anonymous Functions
10 July 2024 11:14

• Function Statement • 1. What is Function Statement ?


function a(){ ○ A. A normal function that we create using Naming convention.
Console.log("a called") & By this we can do the Hoisting. For Ex - function xyz()
} { console.log("Function Statement"); }
a(); • 2. What is Function Expression ?
○ A. When we assign a function into a variable that is Function
• Function Expression Expression. & We cannot do Hoisting by this because it acts
○ Assigning function to the var. like variable. For Ex - var a = function(){ console.log("Function
○ Function acts like a value Expression"); }
var b = function (){ • 3. What is Anonymous Function ?
Console.log("b called") ○ A. A Function without the name is known as Anonymous
} Function. & It is used in a place where function are treated as
b(); // undefined if called before assigning value. For Ex - function(){ }
• 4. What is Named Function Expression ?
○ The major difference between function statement and function expression is ○ A. A function with a name is known as Named Function
Hoisting. Expression. For Ex - var a = function xyz(){ console.log("Names
Function Expression"); }
• Function Declaration • 5. Difference b/w Parameters and Arguments ?
○ Function statement is also known as function declaration. ○ A. When we creating a function & put some variables in this ( )
that is our Parameters. For Ex - function ab( param1, param2 )
• Anonymous Function { console.log(" } & When we call this function & pass a variable
○ A function without name is called anonymous function. in this ( ) that is our Arguments For Ex - ab( 4, 5 );
○ It doesn’t have its own identity. • 6. What is First Class Function Or First class citizens?
function(){ ○ A. The Ability of use function as value, * Can be passed as an
Argument, * Can be executed inside a closured function & *
} Can be taken as return form. For Ex - var b = function(param)
○ Syntax error - No name/ requires a name { return function xyz(){ console.log(" F C F "); } }
○ Uses: • 7. Function are heart of JS. They are called first class citizens or first
 Used in a place where functions are used as values. class functions because they have the ability to be stored in the
 Can assign to a variable - used in function expression. variables, passed as parameters and arguments. They can also be
returned in the function.
• Named Function expression
○ It is same as function expression but instead of using anonymous function we use
named function.
var a = function xyz(){
console.log("Named function expression ")
}
xyz();
○ But if we call the function xyz(), we get an error - Reference Error
○ Because xyz() is not created in global scope but created as local scope.

• Difference between Parameters & Arguments


○ Parameters:
 We put values while creating a function those are called parameters.
var a = function (param1, param2){
console.log("....")
}
 These params are local variables inside these functions and we can't access
them outside the function.
○ Arguments:
 The values we pass while calling the function are known as arguments.
a(5,7);
 We pass inside the function is called arguments.

• First Class Functions


○ The ability to use functions as values is known as first class functions
○ For example, a function can be passed an argument inside a function and a function
can be returned like a variable inside a function.
○ A function to assigned into variable
○ It is also known as First Class Citizens.

• Arrow Functions
○ Part of ES6 - 2016

Namaste JS Page 12
Callback Functions, Event Listeners
10 July 2024 12:32

• Callback Function 1. Function that is passed on as argument to another function


○ The functions are first class citizens, so we can take a function and pass it into another is called call-back function.
function. The function which we are passing is known as callback function. 2. setTimeout helps turn JS which is single threaded and
○ Callback functions give us access to the whole asynchronous world in a synchronous single synchronous into asynchronous.
threaded language. 3. Event listeners can also invoke closures with scope.
function x(y){ 4. Event listeners consume a lot of memory which can
} potentially slow down the website therefore it is good
x(function y(){ practice to remove if it is not used.

})
○ The function y() is known as callback function. So the function y() will be called back later
at anytime in the code.
○ In setTimeout function, the function we pass as param is callback function.
setTimeout(function (){
console.log("TIMER...")
}, 4000)
function x(y){
console.log("x")
y();
}
x(function y(){
console.log("y")
});
○ Without callbacks and setTimeout functions we can't achieve asynchronous functions.
○ If we block the CallStack for some time without asynchronous function then it is known as
Blocking the main thread.

• Event Listeners

document.getElementById("clickMe").addEventListener("click",
function xyz(){
console.log("Button Clicked!!!");
})

• Closures along with Event Listeners


function attachEventListeners(){
let count=0;
document.getElementById("clickMe").addEventListener("click",fun
ction xyz(){
console.log("Button Clicked!", ++count);
})
}
attachEventListeners();

• Garbage collection & Remote Event Listeners


○ We should remove event listeners because they are heavy i.e. it takes memory.
○ Whenever we attach event listener, it forms closure. So we cannot free up the extra
memory. That is the reason we remove event listeners when we are not using them.
○ If a page contains 100s of EventListeners, buttons etc, it slows down because it consumes
lot of memory (closures). So, good practice is to free up them.
○ So, when we remove the event listeners, the variables are garbage collected.

Namaste JS Page 13
Asynchronous Javascript & Event Loop
10 July 2024 17:46
• Local storage
• Timers
• Url writer
• Netflix servers
• Display to UI
• Can access
bluetooth, etc

• To access all the above mentioned things we need WebAPIs.


• Web API
○ setTimeout() is not part a of Javascript.
○ Even DOM elements like document.get…() etc, are also not
Javascript.
○ fetch(), local Storage, console are also not part of
Javascript.
○ The mentioned above all are part of browser. Browser
gives the access to CallStack(Javascript Engine) to use all
these superpowers.
○ We can all use them because of global object. The global
object is window. So browser gives Javascript the ability
use all these using keyword call window.
○ So, if we do window.localStorage() here , it gives access console.log("Start");
to local storage. Similar for all web APIs. setTimeout(function xy(){
○ Since these are global object, we can access it without console.log("callback");
writing window specifically. },3000);
console.log("Stop");
• Event Loop & CallBack Queue
○ We know how setTimeout() works,
 First GEC is pushed into CallStack.
 Next "Start" is printed inside the console using web API.
 Next "function xy()" will be registered in a separate storage and a timer is
attached to it with the help of setTimeout Web API.
 Next "Stop" is printed inside the console using web API.
 GEC is removed from the CallStack as code is finished.
 After the timer is completed, the function xy() will be somehow needed in the
CallStack with the help of Event Loop & CallBack Queue.
 It will go through the CallStack through the CallBack Queue.
 The job of the Event Loop is to check the CallBack Queue and the functions
into the CallStack. So it acts like a gate keeper.
 When xy() enters CallStack, it is quickly executed by creating EC and repeats
the same process.
console.log("Start");
○ How Event Listeners work document.getElementById("btn")
 Again, a GEC is created in callStack. .addEventListener("click",function cb(){
 Next "Start" is printed inside the console using web API. console.log("Callback")
 document.getElementID() is given by browser to Javascript engine through the });
window object in form of a web API which is the DOM API, which fetches DOM console.log("Stop");
which is like Document Object Model which is like HTML source code, and tries
to find something and returns it.
 And if we do .addEventListener(), it also registers a callBack on an event (here
it is click). So, it basically registers a callback inside the Web APIs environment
and event is attached to it.
 Then it moves on with next line, i.e. "Stop" is printed inside the console using
web API.
 Next GEC is popped of the callStack.
 But the Event Listener will stay in the Web API environment unless we
specifically removes it or close the browser.
 And when the user clicks on the button, the callback method is pushed inside
the callback queue and it waits for its turn to get executed.

○ Event Loop working


 The only job of Event Loop is to continuously monitor the CallStack and
CallBack Queue.
 If the callStack is empty and if callback queue has any function, then it pushes console.log("Start");
the function from that queue to stack. Then it will be quickly executed. setTimeout(function cbT(){
 Instead of directly sending callback function to callStack, we use callback queue console.log("CB Timeout");
because in real life there will be a lot of callback functions, event listeners, etc. }, 4000);
so they need a chance to be executed, so a queue is required fetch("https://api.netflix.com")
.then(function cbF(){
○ fetch() function working console.log("CB Netflix");
 fetch() basically goes and requests an API call. });
 fetch() returns a promise and we have to pass a callback function which will be console.log("Stop");
executed once the promise is resolved. promise means once the data is
returned we execute the function.

Namaste JS Page 14
○ fetch() function working console.log("CB Netflix");
 fetch() basically goes and requests an API call. });
 fetch() returns a promise and we have to pass a callback function which will be console.log("Stop");
executed once the promise is resolved. promise means once the data is
returned we execute the function.
 Process is same, first GEC is pushed in callstack. Next Start is printed in console
 Then function cbT() is registered in web APIs and timer of 4000ms is attached
to it.
 Then function cbF() is also registered in webAPI because of fetch()
 The cbT() function is waiting for timer to expire so that it can be pushed into
callback queue. And cbF() function is waiting for the data to be returned from
Netflix servers.
 Suppose the servers return the data to fetch within 50ms, then we have a
Microtask Queue. This microtask Queue has higher priority than callback
queue.
 The cbF() function, which is a callback function in case of network calls will go
to the microtask queue.
 If there are millions of LOC, then cbF() and cbT() functions are ready to be
executed while the execution of the entire code is still pending. But the code is
executed first, the event loop will check the callstack, and if it is empty then it
will check any functions pending in microtask queue then at last checks 1. When does the event loop actually start? -
callback queue. Event loop, as the name suggests, is a single-thread, loop that is
 So first "CB Netflix" is printed then "CB Timeout" is printed later in console `almost infinite`. It's always running and doing its job.

○ What are Microtask and what can come under Microtask queue 2. Are only asynchronous web API callbacks are registered in the web
 All the callback functions which comes through promises will go inside the API environment? -
microtask queue and mutation observer. YES, the synchronous callback functions like what we pass inside
 Mutation Observer : Mutation observer will keep on checking if there is any map, filter, and reduce aren't registered in the Web API
mutation in the DOM tree or not. If there is a mutation in DOM tree, then it environment. It's just those async callback functions that go
execute some callback function. through all this.
 But all other callback functions like which come from setTimeout(), DOM APIs 3. Does the web API environment stores only the callback function
etc. goes inside the callback queue. and pushes the same callback to queue/microtask queue? -
 callback queue is also known as Task Queue. Yes, the callback functions are stored, and a reference is
 For example, if there are 3 pending functions in microtask queue and 1 scheduled in the queues. Moreover, in the case of event
pending function in callback queue, the event loop will give chance to the listeners(for example click handlers), the original callbacks stay
callback queue only after all the tasks are completed in the microtask queue. in the web API environment forever, that's why it's advised to
 If a microtask creates a new microtask in itself when executed and if it repeats explicitly remove the listeners when not in use so that the
then the task inside the callback queue will never get a chance to execute in a garbage collector does its job.
long time. This is known as Starvation of Functions in callback queue. 4. How does it matter if we delay for setTimeout would be 0ms.
Then callback will move to queue without any wait? No, there
are trust issues with setTimeout(). The callback function needs
to wait until the Call Stack is empty. So the 0 ms callback might
have to wait for 100ms also if the stack is busy.

Namaste JS Page 15
Javascript Runtime Environment • List of Javascript engines
11 July 2024 11:57 These are new generation ECMAScript engines for web browsers, all implementing just-in-time
compilation (JIT) or variations of that idea. The performance benefits for just-in-time
• Javascript runtime environment has all things to run Javascript compilation make it much more suitable for web applications written in JavaScript.
○ Javascript Engine • Carakan: A JavaScript engine developed by Opera Software ASA, included in the 10.50 release of
the Opera web browser, until switching to V8 with Opera 15 (released in 2013).[1][2][3]
○ Set of APIs - To connect to outer environment • Chakra (JScript9): A JScript engine used in Internet Explorer. It was first previewed at MIX 10 as part of
○ Event Loop the Internet Explorer 9 Platform Preview.[4]
○ callback queue • Chakra: A JavaScript engine previously used in older versions of Microsoft Edge, before being replaced by
○ microtask queue V8.[5]
• • SpiderMonkey: A JavaScript engine in Mozilla Gecko applications, including Firefox. The engine currently
These are all the things in the container to run the Javascript code.
includes the IonMonkey compiler and OdinMonkey optimization module, has previously included the
• Javascript engine is heart of Javascript runtime environment. TraceMonkey compiler (first JavaScript JIT) and JägerMonkey.
• Browser can only execute Javascript code because it has JRE. • JavaScriptCore: A JavaScript interpretter and JIT originally derived from KJS. It is used in
• The APIs can be different in different places like the WebKit project and applications such as Safari. Also known as Nitro, SquirrelFish, and SquirrelFish
○ There is local storage in browser but not in NodeJS. Extreme.[6]
• Also APIs can have same name in different JREs • JScript .NET: A .NET Framework JScript engine used in ASP.NET based on Common Language
○ like console, setTimeout() in both nodeJs and browser. Runtime and COM Interop. Support was dropped with .NET Core and CoreCLR so its future looks
questionable for ASP.NET Core.
○ But they are implemented different internally • Tamarin: An ActionScript and ECMAScript engine used in Adobe Flash.
• V8: A JavaScript engine used in Google Chrome and other Chromium-based browsers, Node.js, Deno, and
• Javascript engine is not a machine V8.NET.
• Javascript engine is a code/software written in low level From <https://en.wikipedia.org/wiki/List_of_ECMAScript_engines>
languages.

• Javascript Engine architecture


○ Javascript takes the code and passes through three steps:-
 Parsing
□ The code is broken into tokens.
□ Syntax Parser: It takes the code and converts it into AST (Abstract Syntax Tree)
 Compilation astexplorer.ne
□ Interpretter t
 It takes the code and starts executing line by line in the order
 it doesn't know what happens in the next line
 Executed faster
□ Compiler
 The whole code is first compiled before executing.
 After compilation, a new code is formed which is optimized version of the code.
 Then that code is executed.
 More efficiency
□ Just In Time Compilation (JIT Compilation)
 JIT Compilation means using the combination of both interpretter and compiler. • Javascript can work as both
 It takes best of both interpreted language and
□ The interpretter converts the AST into byte code and sends it to next phase - execution. compiled language
□ While doing this it takes compiler help to optimize the code. • The original first Javascript
□ So the job of compiler is to optimize the code as much as it can in the run-time. engine is interpretter
□ In some JSE, there are AOT(Ahead Of Time) compilation, the compiler takes a piece of because it used to run on
code that is going to be executed later and tries to optimize it and later converted to byte browser.
code. • Now, browser combines both
 Execution compiler & interpretter.
□ Two components of JSE that are required to execute the code are:-
 Memory Heap
◊ The place where all the variables, functions are assigned memory
◊ It is constantly in sync with the callstack, garbage collector, etc.
 Call Stack
◊ Call Stack is basically a stack which maintains the order of execution of
execution context.
◊ Whenever a code is executed the Global Execution Context is pushed into the
stack first and later on as per the function invocation the execution context is
pushed into the stack.
◊ When the function code is done executing the execution context is popped out
and last the Global Execution Context s also deleted.
 Garbage Collector
◊ It tries to free up memory space whenever possible.
◊ Like if a function is not being used, clear setTimeout() then it basically collects
all the garbage and sweeps it.
◊ It uses an algorithm known as Mark & Sweep Algorithm.
• Mark Phase: The algorithm starts by marking all reachable objects. It
begins with the "root" objects, such as global variables and local variables
on the stack, and recursively marks all objects that are referenced by
these roots. This creates a "graph" of all reachable objects.
• Sweep Phase: Once all reachable objects are marked, the algorithm scans
through memory and collects all objects that were not marked. These
unmarked objects are considered unreachable and are therefore
collected (freed up for future use).
 Also compiler does optimizations such as:-
◊ Inlining
• Inlining is an optimization technique used by compilers and interpretters
to replace a function call with the actual code of the function. This can

Namaste JS Page 16
to replace a function call with the actual code of the function. This can
reduce the overhead associated with function calls, such as the cost of
setting up the call stack, which can improve performance.
◊ Copy Elision
• Copy elision is an optimization technique where the compiler avoids
creating temporary copies of objects. This can reduce the overhead
associated with copying objects and improve performance.
◊ Inline caching
• Inline caching is a technique used by JavaScript engines to optimize
property access. It speeds up repeated access to object properties by
caching the type information of objects and their properties.
• When a property is accessed, the JavaScript engine can cache the
location of the property for a given object type. On subsequent accesses,
the engine can quickly retrieve the property from the cache instead of
performing a full property lookup.
• Garbage collectors
○ Currently the fastest JSE is V8 engine by google. ○ Oil pan
 It's interpretter is known as Ignition. ○ Orinoco
 Its compiler is called Turbo Fan optimizing compiler  uses Mark & sweep algorithm
○ V8 Javascript engine Architecture

Namaste JS Page 17
Trust Issues with setTimeout()
11 July 2024 16:50

• Concurrency model in Javascript


○ In this example, if there are million LOC present and
if it takes 10s to execute and callback function cb()
takes only 5000ms to complete, then also only after
the code is executed, the event loop pushed the
cb() into callstack.
○ setTimeout() doesn’t guarantee that it takes exactly
5000ms but it guarantees that it wait minimum
5000ms to execute.
○ Main thread or callstack shouldn’t be blocked at
anytime.

• We use setTimeout() to 0ms when we want to differ that


code like if it is not important, then it can be executed at
last.

Namaste JS Page 18
Inheritance is basically one object trying
Prototypal Inheritance to access methods and properties of
11 July 2024 19:00 other objects.

• Whenever we create an object, Javascript automatically puts hidden properties into an


object and this is object is attached to our original object.
• To access them, for eg, if we create an array arr, then arr.__proto__. // access to
everything
• Prototype chain

Namaste JS Page 19
Functional Programming
11 July 2024 18:12

function x(){
console.log("example");
• Higher Order Function }
○ A function which takes a function as an argument or returns a function y(x){
function is known as HOF. x();
○ Functional programming is not possible without help of higher }
order functions.
○ Here the function y() is a HOF and x() is the callback function.

• DRY Principle
○ Don't Repeat Yourself

• Functional Programming
○ Reusability
○ Modularity
Right
○ Higher order function
○ Pure functions Wrong
○ Composition of functions

• Map() is a HOF
• Here, we implemented our own map function
• It is kinda pollyfil for map
const radius = [3,1,4,2];
const area = function(radius){
return Math.PI * radius * radius;
}
Array.prototype.calculateArea = function (logic){
const output = [];
for(let i=0;i<this.length;i++){
output.push(logic(this[i]));
}
return output;
};
console.log(radius.calculateArea(area));

Namaste JS Page 20
map, filter & reduce
12 July 2024 10:55
const arr = [5,1,3,2,6];
function binary(x){
• Map return x.toString(2);
}
○ It is basically used to transform an array.
const output = arr.map(binary);
○ Transformation of array means getting an new array from the existing array with a logic. console.log(output);

(5) ['101', '1', '11', '10', '110']

Namaste JS Page 21

You might also like