Namaste JS
Namaste JS
□ For functions: Literally stores the whole code inside the memory
square
□
○ 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.
Namaste JS Page 3
How Functions work in Javascript
03 July 2024 11:07
• 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 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
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
• 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
Namaste JS Page 10
setTimeout & Closures Interview Question
05 July 2024 14:57
Namaste JS Page 11
First Class Functions & Anonymous Functions
10 July 2024 11:14
• Arrow Functions
○ Part of ES6 - 2016
Namaste JS Page 12
Callback Functions, Event Listeners
10 July 2024 12:32
})
○ 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!!!");
})
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
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.
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
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.
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);
Namaste JS Page 21