<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Mohammed Ali</title>
    <description>The latest articles on Forem by Mohammed Ali (@mahf001).</description>
    <link>https://forem.com/mahf001</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F928126%2F8fc70245-0313-4a86-92b4-a178ad5ffb67.jpeg</url>
      <title>Forem: Mohammed Ali</title>
      <link>https://forem.com/mahf001</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/mahf001"/>
    <language>en</language>
    <item>
      <title>Objects in JavaScript</title>
      <dc:creator>Mohammed Ali</dc:creator>
      <pubDate>Thu, 19 Sep 2024 14:10:26 +0000</pubDate>
      <link>https://forem.com/mahf001/objects-in-javascript-4bdo</link>
      <guid>https://forem.com/mahf001/objects-in-javascript-4bdo</guid>
      <description>&lt;p&gt;has key-value pairs, separated by colon. The key is also known as property&lt;br&gt;
Similarity: index of arrays are replaced by keys in objects.&lt;br&gt;
Object literal syntax is directly writing properties inside {}&lt;br&gt;
Order during retrieval does not matter in case of objects whereas order matters in arrays.&lt;/p&gt;

&lt;p&gt;Arrays: used for structured data&lt;br&gt;
Objects: used for unstructured data&lt;/p&gt;

&lt;p&gt;Property lookup methods in objects:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;using dot notation&lt;/li&gt;
&lt;li&gt;using brackets notation: key is defined as string in [] inside quotes, the key name can be an expression also.
Ex. obj['firstName'];
Ex. obj[2+3];
Putting an expression won't work with dot notation. We need to use the final property name, and not the computed property name.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Hence, when we have a computed property name its recommended to use brackets notation.&lt;/p&gt;

&lt;p&gt;undefined will be returned if a property doesn't exist and we try to access it.&lt;/p&gt;

&lt;p&gt;obj['insta-id'] = '&lt;a class="mentioned-user" href="https://dev.to/juju"&gt;@juju&lt;/a&gt;';&lt;/p&gt;

&lt;p&gt;Refer operator precedence table on MDN for more info.&lt;/p&gt;
&lt;h2&gt;
  
  
  Object Methods
&lt;/h2&gt;

&lt;p&gt;Fns are a type of value. Hence, we can create key-value pair in which the value is a fn. Means, we can add fns to objects.&lt;br&gt;
Fn expression becomes methods inside objects i.e a fn attached to an object as a value for a key.&lt;br&gt;
Fn declaration inside an object won't work.&lt;br&gt;
method is also a property on the object which holds a fn value.&lt;br&gt;
We can have values in the form of : array, string, boolean, fn etc.&lt;br&gt;
obj.propName(); // will get the fn value and execute it using the ()&lt;/p&gt;

&lt;p&gt;'this' : refers to the object on which its called&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const person = {
  fName: 'Raja',
  lName: 'Rajeshwar',
  bYear: 1970,
  job: 'King',
  friends: ["Billu","Penchu","Ramesh"],

  calcAge: function(){
    // this will be the object which has called this method.
    // Its used to reference the object, and not hardcode it.
    console.log(this);
    // a new property is created on the person object named 'age'
    this.age = 2024 - this.bYear
    return this.age;
  }
}

person.calcAge(1970);
// age property will only exist if this fn was called atleast once else it won't exist.
person.age;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Arrays, Fns are all under the hood objects in JS. Hence, they have their own methods.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>es6</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Intro to DSA &amp; Big O Notation</title>
      <dc:creator>Mohammed Ali</dc:creator>
      <pubDate>Thu, 19 Sep 2024 10:59:42 +0000</pubDate>
      <link>https://forem.com/mahf001/intro-to-dsa-big-o-notation-5gm9</link>
      <guid>https://forem.com/mahf001/intro-to-dsa-big-o-notation-5gm9</guid>
      <description>&lt;h2&gt;
  
  
  Notes to master DSA:
&lt;/h2&gt;

&lt;p&gt;Master DSA to be "eligible" for high paying salaries offered to S/w Ers.&lt;br&gt;
DSA is the major chunk of Software Engineering.&lt;br&gt;
Before writing code, make sure you understand the bigger picture and then drill down into details.&lt;br&gt;
Its all about understanding the concepts visually, and then translating those concepts into code via any l/g as DSA is language agnostic.&lt;br&gt;
Every upcoming concept is somehow linked to previous concepts. Hence, don't hop topics or move forward unless you have mastered the concept thoroughly by practicing it.&lt;br&gt;
When we learn concepts visually, we get deeper understanding of the material which inturn helps us to retain the knowledge for longer duration.&lt;br&gt;
If you follow these advices, you'll have nothing to lose.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Linear DS:
Arrays
LinkedList(LL) &amp;amp; Doubly LL (DLL)
Stack
Queue &amp;amp; Circular Queue

Non-linear DS:
Trees
Graphs
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Big O Notation
&lt;/h2&gt;

&lt;p&gt;It is essential to understand this notation for perf comparison of algos.&lt;br&gt;
Its a mathematical way for comparing efficiency of algos.&lt;/p&gt;
&lt;h2&gt;
  
  
  Time Complexity
&lt;/h2&gt;

&lt;p&gt;The faster the code runs, the lower it will be&lt;br&gt;
V. impt for most of the interviews.&lt;/p&gt;
&lt;h2&gt;
  
  
  Space Complexity
&lt;/h2&gt;

&lt;p&gt;Considered rarely as compared to time complexity due to low storage cost.&lt;br&gt;
Need to be understood, as an interviewer may ask you from this also.&lt;/p&gt;
&lt;h2&gt;
  
  
  Three Greek Letters:
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Omega&lt;/li&gt;
&lt;li&gt;Theta&lt;/li&gt;
&lt;li&gt;Omicron i.e Big-O [seen most often]&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;
  
  
  Cases for algo
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Best case [represented using Omega]&lt;/li&gt;
&lt;li&gt;Avg case [represented using Theta]&lt;/li&gt;
&lt;li&gt;Worst case [represented using Omicron]&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Technically there is no best case of avg case Big-O. They are denoted using omega &amp;amp; theta respectively.&lt;br&gt;
We are always measuring worst case.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;## O(n): Efficient Code
Proportional
Its simplified by dropping the constant values.
An operation happens 'n' times, where n is passed as an argument as shown below.
Always going to be a straight line having slope 1, as no of operations is proportional to n.
X axis - value of n.
Y axis - no of operations 

// O(n)
function printItems(n){
  for(let i=1; i&amp;lt;=n; i++){
    console.log(i);
  }
}
printItems(9);

// O(n) + O(n) i.e O(2n) operations. As we drop constants, it eventually becomes O(n)
function printItems(n){
  for(let i=0; i&amp;lt;n; i++){
    console.log(i);
  }
  for(let j=0; j&amp;lt;n; j++){
    console.log(j);
  }
}
printItems(10);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;## O(n^2):
Nested loops.
No of items which are output in this case are n*n for a 'n' input.
function printItems(n){
  for(let i=0; i&amp;lt;n; i++){
    console.log('\n');
    for(let j=0; j&amp;lt;n; j++){
      console.log(i, j);
    }
  }
}
printItems(4);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;## O(n^3):
No of items which are output in this case are n*n*n for a 'n' input.
// O(n*n*n)
function printItems(n){
  for(let i=0; i&amp;lt;n; i++){
    console.log(`Outer Iteration ${i}`);
    for(let j=0; j&amp;lt;n; j++){
      console.log(`  Mid Iteration ${j}`);
      for(let k=0; k&amp;lt;n; k++){
        //console.log("Inner");
        console.log(`    Inner Iteration ${i} ${j} ${k}`);
      }
    }
  }
}
printItems(3);


## Comparison of Time Complexity:
O(n) &amp;gt; O(n*n)


## Drop non-dominants:
function xxx(){
  // O(n*n)
  Nested for loop

  // O(n)
  Single for loop
}
Complexity for the below code will O(n*n) + O(n) 
By dropping non-dominants, it will become O(n*n) 
As O(n) will be negligible as the n value grows. O(n*n) is dominant term, O(n) is non-dominnat term here.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;## O(1):
Referred as Constant time i.e No of operations do not change as 'n' changes.
Single operation irrespective of no of operands.
MOST EFFICIENT. Nothing is more efficient than this. 
Its a flat line overlapping x-axis on graph.


// O(1)
function printItems(n){
  return n+n+n+n;
}
printItems(3);


## Comparison of Time Complexity:
O(1) &amp;gt; O(n) &amp;gt; O(n*n)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;## O(log n)
Divide and conquer technique.
Partitioning into halves until goal is achieved.

log(base2) of 8 = 3 i.e we are basically saying 2 to what power is 8. That power denotes the no of operations to get to the result.

Also, to put it in another way we can say how many times we need to divide 8 into halves(this makes base 2 for logarithmic operation) to get to the single resulting target item which is 3.

Ex. Amazing application is say for a 1,000,000,000 array size, how many times we need to cut to get to the target item.
log(base 2) 1,000,000,000 = 31 times
i.e 2^31 will make us reach the target item.

Hence, if we do the search in linear fashion then we need to scan for billion items in the array.
But if we use divide &amp;amp; conquer approach, we can find it in just 31 steps.
This is the immense power of O(log n)

## Comparison of Time Complexity:
O(1) &amp;gt; O(log n) &amp;gt; O(n) &amp;gt; O(n*n)
Best is O(1) or O(log n)
Acceptable is O(n)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;O(n log n) : 
Used in some sorting Algos.
Most efficient sorting algo we can make unless we are sorting only nums.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Tricky Interview Ques: Different Terms for Inputs.
function printItems(a,b){
  // O(a)
  for(let i=0; i&amp;lt;a; i++){
    console.log(i);
  }
  // O(b)
  for(let j=0; j&amp;lt;b; j++){
    console.log(j);
  }
}
printItems(3,5);

O(a) + O(b) we can't have both variables equal to 'n'. Suppose a is 1 and b is 1bn.
Then both will be very different. Hence, it will eventually be O(a + b) is what can call it.
Similarly if these were nested for loops, then it will become O(a * b)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;## Arrays
No reindexing is required in arrays for push-pop operations. Hence both are O(1).
Adding-Removing from end in array is O(1)

Reindexing is required in arrays for shift-unshift operations. Hence, both are O(n) operations, where n is no of items in the array.
Adding-Removing from front in array is O(n)

Inserting anywhere in array except start and end positions:
myArr.splice(indexForOperation, itemsToBeRemoved, ContentTobeInsterted)
Remaining array after the items has to be reindexed.
Hence, it will be O(n) and not O(0.5 n) as Big-O always meassures worst case, and not avg case. 0.5 is constant, hence its droppped.
Same is applicable for removing an item from an array also as the items after it has to be reindexed.


Finding an item in an array:
if its by value: O(n)
if its by index: O(1)

Select a DS based on the use-case.
For index based, array will be a great choice.
If a lot of insertion-deletion is perform in the begin, then use some other DS as reindexing will make it slow.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Comparison of Time Complexity for n=100:
&lt;/h2&gt;

&lt;p&gt;O(1) = 1&lt;br&gt;
O(log 100) = 7&lt;br&gt;
O(100) = 100&lt;br&gt;
O(n^2) = 10,000&lt;/p&gt;

&lt;h2&gt;
  
  
  Comparison of Time Complexity for n=1000:
&lt;/h2&gt;

&lt;p&gt;O(1) = 1&lt;br&gt;
O(log 1000) = ~10&lt;br&gt;
O(1000) = 1000&lt;br&gt;
O(1000*1000) = 1,000,000&lt;/p&gt;

&lt;p&gt;Mainly we will focus on these 4:&lt;br&gt;
Big O(n*n): Nested Loops&lt;br&gt;
Big O(n): Proportional&lt;br&gt;
Big O(log n): Divide &amp;amp; conquer&lt;br&gt;
Big O(1): Constant&lt;/p&gt;

&lt;p&gt;O(n!) usually happens when we deliberately write bad code.&lt;br&gt;
O(n*n) is horrible Algo&lt;br&gt;
O(n log n) is acceptable and used by certain sorting algos&lt;br&gt;
O(n) : Acceptable&lt;br&gt;
O(log n), O(1) : Best&lt;/p&gt;

&lt;p&gt;Space complexity is almost same for all DS i.e O(n). &lt;br&gt;
Space complexity will vary from O(n) to O(log n) or O(1) with sorting algos&lt;/p&gt;

&lt;p&gt;Time complexity is what varies based on algo&lt;/p&gt;

&lt;p&gt;Best time complexity for sorting other than numbers like string is O(n log n) which is in Quick, Merge, Time, heap sorts.&lt;/p&gt;

&lt;h2&gt;
  
  
  Best way to apply your learning is to code as much as you can.
&lt;/h2&gt;

&lt;p&gt;Selecting which DS to choose in which problem statement based on Pros-Cons of each DS.&lt;/p&gt;

&lt;p&gt;For more info, refer to: bigocheatsheet.com&lt;/p&gt;

</description>
      <category>datastructures</category>
      <category>javascript</category>
      <category>webdev</category>
      <category>es6</category>
    </item>
    <item>
      <title>Execution Context &amp; Call Stack</title>
      <dc:creator>Mohammed Ali</dc:creator>
      <pubDate>Wed, 18 Sep 2024 14:29:24 +0000</pubDate>
      <link>https://forem.com/mahf001/execution-context-call-stack-29kp</link>
      <guid>https://forem.com/mahf001/execution-context-call-stack-29kp</guid>
      <description>&lt;p&gt;Creation of global execution context for the top level code i.e code which not inside any fn. Hence, code outside the fn is executed first.&lt;br&gt;
Code inside fn body of fn-decln/exprsn is only executed when its called.&lt;/p&gt;
&lt;h2&gt;
  
  
  Execution Context(EC)
&lt;/h2&gt;

&lt;p&gt;Environment in which piece of JS is executed.&lt;br&gt;
Stores all the necessary information for some code to be executed like local variables, args passed to a fn.&lt;br&gt;
JS code always runs inside an EC.&lt;br&gt;
Exactly one global EC irrespective of the size of JS project.&lt;br&gt;
Default context, created for code not inside any fn.&lt;br&gt;
Then the code is executed inside the global EC&lt;br&gt;
After the top level code is executed, execution of fns &amp;amp; waiting for C/bs&lt;br&gt;
For each fn call, a new EC is created to exectute that fn. Same goes for methods, as they are also fns attached to objects.&lt;br&gt;
All these ECs together make up the Call Stack.&lt;br&gt;
When all fns are executed, engine waits for CBs to arrive &amp;amp; execute them. Ex. click event callback, provided by the event loop.&lt;/p&gt;
&lt;h2&gt;
  
  
  What is inside EC
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Variable Environment consisting of&lt;/li&gt;
&lt;li&gt;let, const, var declarations&lt;/li&gt;
&lt;li&gt;Functions&lt;/li&gt;
&lt;li&gt;&lt;p&gt;arguments object : stores all the args passed to the fn in its EC.&lt;br&gt;
Each fn gets its own EC as its called. And variables declared end up in variable environment&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Scope Chain:&lt;br&gt;
Fns can access variables outside of fns using scope chain.&lt;br&gt;
Contains references to the variables located outside of the current fn and to keep track of the scope chain, it is stored in each EC.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Each EC also get the 'this' keyword.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;All these three above are generated during "Creation Phase", right before execution. These the things necessary to run the code in top level.&lt;/p&gt;
&lt;h2&gt;
  
  
  For arrow fns EC:
&lt;/h2&gt;

&lt;p&gt;We won't be having: arguments object, this keyword. Arrow fns use from their closest regular fn, the above two.&lt;/p&gt;

&lt;p&gt;arguments: array like object, containing all the arguments passed into the regular fn, not arrow fn.&lt;/p&gt;
&lt;h2&gt;
  
  
  Call Stack + Memory Heap = JS Engine
&lt;/h2&gt;
&lt;h2&gt;
  
  
  Call Stack
&lt;/h2&gt;

&lt;p&gt;Place where ECs get stacked on top of each other, to keep track of where we are in the execution. The topmost EC is the one we are running. As the execution is over, its removed from the top of stack and the control is trasferred to the underlying EC.&lt;br&gt;
If there is a nested fn call, the outer fn call will be paused so as to return the result of the execution of inner fn on call stack as JS has only one thread of execution. Now the prev EC will become the active EC&lt;br&gt;
Then the top-most EC is popped out of Call Stack as its returned.&lt;br&gt;
Lowest in Call Stack will be global EC, on top it will be fn calls as they occur in order.&lt;br&gt;
Ensures order of execution never gets lost.&lt;br&gt;
In the end, program will be finished and global EC will also be popped out the Call Stack.&lt;/p&gt;
&lt;h2&gt;
  
  
  JS code runs inside an EC, which are placed on Call Stack.
&lt;/h2&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Hence, we can say that each EC has:
1. Variable environment
2. Scope chain
3. 'this' keyword
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h2&gt;
  
  
  Scoping
&lt;/h2&gt;

&lt;p&gt;How our program variables are organized and accessed by JS Engine.&lt;br&gt;
Where do variables live&lt;br&gt;
Where can we access a certain variables and where not.&lt;/p&gt;
&lt;h2&gt;
  
  
  Lexical Scoping:
&lt;/h2&gt;

&lt;p&gt;JS has leical scoping which means scoping is controlled by placement of fns and blocks in the code.&lt;br&gt;
Ex. A nested fn has access to variables of its parent fn.&lt;/p&gt;
&lt;h2&gt;
  
  
  Scope:
&lt;/h2&gt;

&lt;p&gt;Space or env in which a certain variable is declared(variable environment in case of fns). Its the variable env which is stored in fns EC.&lt;br&gt;
For fns, Var env &amp;amp; scope both are same.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Three scopes in JS are:
1. Global scope
2. Fn scope
3. Block scope [ES6]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Scope is a place where variables are declared. Hence, true for Fns also as fns are just values stored in variables.&lt;/p&gt;

&lt;h2&gt;
  
  
  Scope of a Variable
&lt;/h2&gt;

&lt;p&gt;Region of our code where a certain variable can be accessed.&lt;/p&gt;

&lt;h2&gt;
  
  
  Scope is different from scope of a variable with subtle differences.
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;## Global Scope:
For top level code
For variables declared outside of any fn or block which are accessible from everywhere
Variables in this scope are at the top of scope chain. Hence, can be used by every nested scope.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;## Fn Scope:
Each fn has creates its own scope
Variables are accessible ONLY inside fn, NOT outside. Else Reference Error
Also called local scope
Fn decln, exprsn, arrow all three create their own scopes.
Only way to create scope using ES5 which had only fn &amp;amp; global scope.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;## Block Scope:
Introduced in ES6, not only fn but {} also create a scope known as block scope which work only for ES6 variables i.e let-const types. DOesn't work for variables declared with 'var' as its fn scoped.
Variables accessible only inside block i.e {} 
This only applies to variables declared with let-const only.
Fns are also block scoped in ES6 (only in strict mode, should be used)
variables declared using 'var' will be accessible outside the block
Scoped to the current fn or the global scope.
var variables only care about fn, they ignore blocks. They end up in nearest fn scope.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Every nested scope has access to variables from its outer scope &amp;amp; the global scope. Same is applicable to fn arguments also.
&lt;/h2&gt;

&lt;p&gt;If a fn doesn't find the variable in its scope, it looks up the scope chain to find out the varibles in its outer scopes. This process is called variable lookup in scope chain. This doesn't work the other way around i.e we cannot access nested fn variables or scopes from outside the fn or outer scopes.&lt;br&gt;
Sibling scopes cannot access each other's variables&lt;br&gt;
Only the innermost scope can access its outer scopes, not the reverse.&lt;/p&gt;

&lt;p&gt;One EC for each fn in the exact order a fn is called is placed on Call Stack with its variables inside the EC. Global EC is at the bottom of the Call Stack&lt;/p&gt;

&lt;p&gt;Scope chain: &lt;br&gt;
Its all about the order in which fns are written in the code.&lt;br&gt;
Has nothing to do with order in which fns were called.&lt;br&gt;
Scope chain gets the variable environment from the EC.&lt;br&gt;
Order of fn calls is not relevant to the scope chain at all.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const a = 'Alice';
first();

function first(){
  const b = "Hello";
  second();

  function second(){
    const c = "Hi";
    third();
  }
}

function third(){
  const d = "Hey";
  console.log(d + c + b + a); // Reference Error
}

## Call Stack order:
third() EC - top
second() EC
first() EC
global EC - bottom


Scope Chain:
second() --nested inside--&amp;gt; first() --nested inside--&amp;gt; global scope.
third() is independently defined inside gloabal scope.

Reference Error occurred because both 'c' as well as 'b' cannot be accessed using the scope chain.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Summary:&lt;br&gt;
E-C, Var Env, Cl-Sk, Scope, Scope-chain are all different but related concepts. &lt;br&gt;
Scoping asks the questions where do variables live, where can we access the variables and where not.&lt;br&gt;
Lexical Scoping in JS: Rules of where we can access variables are based exactly where in the code fns and blocks are written.&lt;br&gt;
Every scope has access to all the variables from all its outer scopes. This is scope chain which is a one-way street. An outer scope can never access variables of inner scope.&lt;br&gt;
Scope chain of a certain scope is equal to adding together all the Var Envs of all the parent scopes.&lt;br&gt;
Scope chain has nothing to do with the order in which fns are called. It does not affect the scope chain at all.&lt;br&gt;
When a variable is not found in current scope, engine looks up the scope chain until it finds the variable its looking for. This is called variable look-up.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>es6</category>
      <category>advanced</category>
    </item>
    <item>
      <title>Math Namespace &amp; BigInt</title>
      <dc:creator>Mohammed Ali</dc:creator>
      <pubDate>Fri, 13 Sep 2024 13:09:19 +0000</pubDate>
      <link>https://forem.com/mahf001/math-namespace-bigint-21gd</link>
      <guid>https://forem.com/mahf001/math-namespace-bigint-21gd</guid>
      <description>&lt;h2&gt;
  
  
  Math.sqrt i.e sqrt is a part of Math namespace.
&lt;/h2&gt;

&lt;p&gt;// 2 ways to get square root.&lt;br&gt;
Math.sqrt(100); // 10, Method 1&lt;br&gt;
100*&lt;em&gt;(1/2); // 10, Method 2&lt;br&gt;
8&lt;/em&gt;*(1/3); // 2, works for cubic root also&lt;/p&gt;

&lt;h2&gt;
  
  
  Math.max() &amp;amp; Math.min():
&lt;/h2&gt;

&lt;p&gt;Math.max(23,54,12,6,32,98,87,34,11); // 98&lt;br&gt;
// Does type coercion also&lt;br&gt;
Math.min(23,54,12,'6',32,98,87,34,11); // 6&lt;br&gt;
// Does not do parsing&lt;br&gt;
Math.min(23,54,12,'6px',32,98,87,34,11); // NaN&lt;/p&gt;

&lt;h2&gt;
  
  
  Inbuilt constants on Math object:
&lt;/h2&gt;

&lt;p&gt;Math.PI * (Number.parseFloat('10px')**(2)); // Getting area&lt;/p&gt;

&lt;h2&gt;
  
  
  Generate a no b/w 1-6:
&lt;/h2&gt;

&lt;p&gt;Math.trunc(Math.random() * 6) + 1;&lt;/p&gt;

&lt;h2&gt;
  
  
  Generatate a random no b/w an upper-lower limit:
&lt;/h2&gt;

&lt;p&gt;const randomInt = (min, max) =&amp;gt; Math.floor(Math.random() * (max-min)) + 1 + min;&lt;br&gt;
randomInt(10,20);&lt;/p&gt;

&lt;p&gt;// All of these Math.method() do type coercion.&lt;br&gt;
Math.trunc(25.4); // 25&lt;br&gt;
Math.round(25.4); // 25&lt;br&gt;
Math.floor(25.4); // 25&lt;br&gt;
Math.ceil(25.4); // 26&lt;/p&gt;

&lt;h2&gt;
  
  
  Math.floor is a better choice for negative numbers.
&lt;/h2&gt;

&lt;p&gt;Math.trunc(-25.4); // -25&lt;br&gt;
Math.floor(-25.4); // -26&lt;/p&gt;

&lt;p&gt;// Rounding decimals: .toFixed returns a string, not a number&lt;br&gt;
(2.5).toFixed(0); // '3'&lt;br&gt;
(2.5).toFixed(3); // '2.500'&lt;br&gt;
(2.345).toFixed(2); // '2.35'&lt;/p&gt;

&lt;p&gt;// Add a unary + sign to convert it to a no.&lt;br&gt;
+(2.345).toFixed(2); // 2.35&lt;/p&gt;

&lt;p&gt;// Number is a primitive, hence they don't have methods. SO behind the scene, JS will do boxing, i.e transform primitive into a no object, perform the operation and then when operation is finished, transform it back to primitive.&lt;/p&gt;

&lt;h2&gt;
  
  
  Modular or Remainder Operator:
&lt;/h2&gt;

&lt;p&gt;5 % 2; // 1&lt;/p&gt;

&lt;p&gt;8 % 3; // 2&lt;br&gt;
8 / 3; //  2.6666666666666665&lt;/p&gt;

&lt;p&gt;// Odd or Even&lt;br&gt;
const isEven = n =&amp;gt; n%2 === 0;&lt;br&gt;
isEven(20);&lt;br&gt;
isEven(21);&lt;br&gt;
isEven(22);&lt;/p&gt;

&lt;p&gt;Usecase: Used to work with all odd rows, even rows, nth time etc.&lt;/p&gt;

&lt;h2&gt;
  
  
  Numeric Separators: [ES2021]
&lt;/h2&gt;

&lt;p&gt;Used for representing really large numbers&lt;br&gt;
These are underscores which can be placed between numbers. The engine ignores these underscores, its reduces the confusion for devs.&lt;br&gt;
Ex. const diameter = 287_460_000_000;&lt;br&gt;
diameter; // 287460000000&lt;/p&gt;

&lt;p&gt;const price = 342_25;&lt;br&gt;
price; // 34225&lt;/p&gt;

&lt;p&gt;const fee1 = 1_500;&lt;br&gt;
const fee2 = 15_00;&lt;br&gt;
fee1 === fee2; // true&lt;/p&gt;

&lt;p&gt;Underscore can be placed ONLY between numbers.&lt;br&gt;
It cannot be placed adjacent to a dot of decimal.&lt;br&gt;
It also cannot be placed at the begining or the end of the no.&lt;/p&gt;

&lt;p&gt;const PI = 3.14_15;&lt;br&gt;
PI; // 3.1415&lt;/p&gt;

&lt;h2&gt;
  
  
  All are invalid example of numeric separators
&lt;/h2&gt;

&lt;p&gt;const PI = &lt;em&gt;3.1415; // Cannot be placed in the begining.&lt;br&gt;
const PI = 3.1415&lt;/em&gt;; // Cannot be placed in the end.&lt;br&gt;
const PI = 3_.1415; // Cannot be placed adjacent to a decimal dot.&lt;br&gt;
const PI = 3.&lt;em&gt;1415; // Cannot be placed adjacent to a decimal dot.&lt;br&gt;
const PI = 3.&lt;/em&gt;_1415; // Two in a row cannot be placed.&lt;/p&gt;

&lt;h2&gt;
  
  
  Converting Strings to Numbers:
&lt;/h2&gt;

&lt;p&gt;Number('2500'); // 2500&lt;br&gt;
Number('25_00'); // NaN , Hence we can only use when directly numbers are assigned to a variable. Hence, if a no is stored in the string or getting a no from an API, then to avoid error don't use '_' numeric separator.&lt;br&gt;
Similar goes for parseInt i.e anything after _ is discarded as shown below:&lt;br&gt;
parseInt('25_00'); // 25&lt;/p&gt;

&lt;h2&gt;
  
  
  BigInt
&lt;/h2&gt;

&lt;p&gt;Special type of integers, introduced in ES2020&lt;br&gt;
Numbers are represented internally as 64 bits i.e 64 1s or 0s to represent any number. Only 53 are used to store the digits, remaining are used to store the position of decimal point and the sign. Hence, there is a limit on the size of the number i.e ((2*&lt;em&gt;53) - 1). This is the biggest no which JS can safely represent. The base is 2, because we are working in binary form while storing.&lt;br&gt;
2&lt;/em&gt;*53 - 1;                // 9007199254740991&lt;br&gt;
Number.MAX_SAFE_INTEGER;  // 9007199254740991&lt;/p&gt;

&lt;p&gt;Anything larger than this is not safe i.e it cannot be represented accurately. Precision will be lost for numbers larger than this as shown in last digit. Sometimes it might work, whereas sometimes it won't.&lt;br&gt;
Number.MAX_SAFE_INTEGER + 1;  // 9007199254740992&lt;br&gt;
Number.MAX_SAFE_INTEGER + 2;  // 9007199254740992&lt;br&gt;
Number.MAX_SAFE_INTEGER + 3;  // 9007199254740994&lt;br&gt;
Number.MAX_SAFE_INTEGER + 4;  // 9007199254740996&lt;/p&gt;

&lt;p&gt;Incase we get a larger no from an API larger than this, then JS won't be able to deal with it. So to resolve the above issue, BigInt a new primitive data type was introduces in ES2020. This can store integers as large as we want.&lt;/p&gt;

&lt;p&gt;An 'n' is added at the end of the no to make it a BigInt. Ex.&lt;br&gt;
const num = 283891738917391283734234324223122313243249821n;&lt;br&gt;
num;     // 283891738917391283734234324223122313243249821n&lt;/p&gt;

&lt;p&gt;BigInt is JS way of displaying such huge numbers.&lt;br&gt;
Another way using Constructor Fn for creating BigInt number.&lt;br&gt;
const x = BigInt(283891738917391283734234324223122313243249821);&lt;br&gt;
x;            // 283891738917391288062871194223849945790676992n&lt;/p&gt;

&lt;p&gt;Operations: All arithmetic operators work the same with BigInt;&lt;br&gt;
const x = 100n + 100n;&lt;br&gt;
x; // 200n&lt;/p&gt;

&lt;p&gt;const x = 10n * 10n;&lt;br&gt;
x; // 100n&lt;/p&gt;

&lt;h2&gt;
  
  
  Avoid mixing BigInt numbers with regular numbers
&lt;/h2&gt;

&lt;p&gt;const x = 100n;&lt;br&gt;
const y = 10;&lt;br&gt;
z = x*y; // Error&lt;/p&gt;

&lt;p&gt;To make it work, use BigInt constructor Fn:&lt;br&gt;
z = x * BigInt(y); &lt;br&gt;
z;              // 1000n&lt;/p&gt;

&lt;h2&gt;
  
  
  Exception to it are comparsion operators &amp;amp; unary + operator.
&lt;/h2&gt;

&lt;p&gt;20n &amp;gt; 19; // true&lt;br&gt;
20n === 20; // false, === prevents JS from doing type coercion. Both the LHS &amp;amp; RHS have different primitive types, hence results in 'false'.&lt;/p&gt;

&lt;p&gt;typeof 20n; // 'bigint'&lt;br&gt;
typeof 20;  // 'number'&lt;/p&gt;

&lt;p&gt;20n == 20; // true, as JS does type coercion to compare only the values and not the types by converting BigInt to a regular number.&lt;br&gt;
Same goes for this also: 20n == '20'; // true&lt;/p&gt;

&lt;h2&gt;
  
  
  Exception:
&lt;/h2&gt;

&lt;p&gt;BigInt number is not converted to string on using + operator.&lt;br&gt;
const num = 248923874328974239473829n&lt;br&gt;
"num is huge i.e. " + num; // 'num is huge i.e. 248923874328974239473829'&lt;/p&gt;

&lt;p&gt;Note:&lt;br&gt;
Math.sqrt doesn't work with BigInt.&lt;br&gt;
During division of BigInts, it discards the decimal part.&lt;br&gt;
10 / 3;    // 3.3333333333333335&lt;br&gt;
10n / 3n;  // 3n&lt;br&gt;
12n / 3n;  // 4n&lt;/p&gt;

&lt;p&gt;This new primitive type adds some new capabilities to JS language to make it work with huge no.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>es6</category>
    </item>
    <item>
      <title>Ultimate Guide for DOM API</title>
      <dc:creator>Mohammed Ali</dc:creator>
      <pubDate>Fri, 06 Sep 2024 10:32:02 +0000</pubDate>
      <link>https://forem.com/mahf001/ultimate-guide-for-dom-api-3bfo</link>
      <guid>https://forem.com/mahf001/ultimate-guide-for-dom-api-3bfo</guid>
      <description>&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Selecting Elements: document is not the real DOM element.
document.documentElement; // Select the entire page
document.head; // Select the head
document.body; // Select the body

document.querySelector('.header');    // return first match
const allSections = document.querySelectorAll('.section'); // return all-matches in a static NodeList

document.getElementById('id-name');        // 
document.getElementsByClassName('');        // return all-matches in an live HTMLCollection
const allBtns = document.getElementsByTagName('button');   // return all-matches in an live HTMLCollection

// Creating &amp;amp; Inserting Elements: insertAdjacentHTML
const msg = document.createElement('div'); // create a DOM element, stores it into msg
msg.classList.add('cookie-msg');
// msg.textContent = 'We use cookies for improved functionality &amp;amp; analytics';
msg.innerHTML = 'We use cookies for improved functionality &amp;amp; analytics &amp;lt;button class="btn"&amp;gt;Got it&amp;lt;/button&amp;gt;';
header.append(msg);

// prepend: Adds the element as the first child.
// append: Adds the element as the last child.
// DOM element is unique, it can exist at only one place at a time.

// To insert multiple copies of the same element, true refers all childNodes will also be copied.
header.append(msg.cloneNode(true));

header.before(msg); // insert before header element as a sibling.
header.after(msg); // insert after header element as a sibling.

// Delete Elements: document.querySelector will also work, but below is another way.
// remove() is a recent method, earlier we could only remove child elements by selecting the parent element first, then removing the child. Ex msg.parentElement.removeChild(msg);
document.querySelector('btn-close').addEventListener('click', function(){
  msg.remove();
});


// Styles: will be applied as inline styles.
msg.style.backgroundColor = '#37383d';
msg.style.width = '120%';

msg.style.height; // won't show anything. This works only for properties which we have explicitly set like the above properties.

getComputedStyle(msg).color; // will show a huge object containing all styles.
getComputedStyle(msg).height;

// Increase height by 10px
msg.style.height = Number.parseFloat(getCOmputedStyle(msg).height,10) + 40 + 'px';

document.documentElement.style.setProperty('--color-primary','orangered');

// Attributes
const logo = document.querySelector('.nav__logo');
logo.alt;
logo.className;

// Setting an attribute using JS.
logo.alt = 'Beautiful minimalist logo'

// won't work as its not a standard attribute for that element.
logo.designer; 

// Now it will work.
logo.getAttribute('designer'); 
logo.setAttribute('company', 'Google');

logo.src; // absolute path
logo.getAttribute('src'); // relative path

// Both will be same as they are absolute in both cases.
link.href;
link.getAttribute('href');

// Data-attributes written in 
// HTML as data-version-number
// JS as logo.dataset.versionNumber;
// such special attributes are always stored in dataset object.


// Classes
logo.classList.add()     // Can take multiple classes as args
logo.classList.remove()  // Can take multiple classes as args
logo.classList.toggle()
logo.classList.contains()

// Overwrite all existing classes, replace with the bottom class mentioned.
logo.className = 'xyz'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Notes:&lt;br&gt;
Click on anchor link will make the page jump to top. This is prevented by using e.preventDefault()&lt;br&gt;
NodeList is not an array, but it has forEach method.&lt;br&gt;
Ex btnOpenModal.forEach(btn =&amp;gt; btn.addEventListener('click', openModal));&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>api</category>
    </item>
    <item>
      <title>Array</title>
      <dc:creator>Mohammed Ali</dc:creator>
      <pubDate>Thu, 05 Sep 2024 12:40:29 +0000</pubDate>
      <link>https://forem.com/mahf001/array-2jmn</link>
      <guid>https://forem.com/mahf001/array-2jmn</guid>
      <description>&lt;p&gt;Methods are fns which can be called on objects&lt;br&gt;
Arrays are objects, hence they also have methods in JS.&lt;/p&gt;
&lt;h2&gt;
  
  
  slice(begin): extract part of array in a new array, without mutating the original array.
&lt;/h2&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let arr = ['a','b','c','d','e'];

// Usecase: Extract till index passed as argument
arr.slice(2); // [ 'c', 'd', 'e' ]

// Usecase: Extract from [first index] to [second index-1] value.
arr.slice(2,4); // [ 'c', 'd' ] i.e Length of array will be end-begin or 4-2 = 2 

// Usecase: Extract last 2 elements
arr.slice(-2); // [ 'd', 'e' ]

// Usecase: Extract the last element.
arr.slice(-1);  // [ 'e' ]  

// Usecase: Extract from index passed to leaving the last two elements.
arr.slice(1,-2);  // [ 'e' ]  

// Usecase: Create a shallow copy of an array
arr.slice(); // 1st way
[...arr]; // 2nd way
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h2&gt;
  
  
  splice: mutates the original array
&lt;/h2&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// splice: remove the elements begining from the index passed. Mutates the orig. array.
// returns: part of the removed array
let arr = ['a','b','c','d','e'];
// arr.splice(2); // [ 'c', 'd', 'e' ]
// arr; // [ 'a', 'b' ]

// Usecase: Remove last element of the array
// arr.splice(-1); // [ 'e' ]
// arr; // [ 'a', 'b', 'c', 'd' ]

// Usecase: Delete no of elements. splice(index, deleteCount)
arr.splice(1, 3); // [ 'b', 'c', 'd' ]
arr; // [ 'a', 'e' ]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h2&gt;
  
  
  reverse: mutates the original array.
&lt;/h2&gt;

&lt;p&gt;returns: reversed array&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let arr = ['a','b','c','d','e'];
let arr2 = arr.reverse();
arr;
arr2;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  concat: joins two arrays.
&lt;/h2&gt;

&lt;p&gt;returns: joined array&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let arr1 = ['a','b','c','d','e'];
let arr2 = ['f','g','h','i','j'];

[...arr1, ...arr2];       // 1st way
arr2 = arr1.concat(arr2); // 2nd way
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  join: joins two arrays.
&lt;/h2&gt;

&lt;p&gt;returns: joined array&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let arr1 = ['a','b','c','d','e'];
let arr2 = ['f','g','h','i','j'];
const x = arr1.concat(arr2);
x.join('-'); // 'a-b-c-d-e-f-g-h-i-j'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;"As time progresses, you'll remember them based on their usage."&lt;/p&gt;

&lt;h2&gt;
  
  
  at: starts counting from the end, begining with index as -1
&lt;/h2&gt;

&lt;p&gt;Suports method chaining. Works on arrays, strings&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let arr = ['a','b','c','d','e'];

arr[0];    // 1st way
arr.at(0); // 2nd way

// Get the last element of the array
arr[arr.length - 1];  // 1st way
arr.slice(-1)[0];     // 2nd way
arr.at(-1);           // 3rd way

arr.at(0); // 'a'
arr.at(-1); // 'e'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;forEach:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Looping over array using forEach method.
let account = [2000,-300,+400, -200, -500, +1000, -300];

// Loop over an array using for-of
for(let money of account){
  if(money &amp;gt; 0){
    console.log(`Deposited ${money}`);
  } else {
    console.log(`Withdrawn ${Math.abs(money)}`);
  }
}

// .entries(): returns an array of arrays.
// return the output as index-value pair.
// first element must be index, second element must be element-value
for(let [i,money] of account.entries()){
  if(money &amp;gt; 0){
    console.log(`Transaction ${i+1}, Deposited ${money}`);
  } else {
    console.log(`Transaction ${i+1}, Withdrawn ${Math.abs(money)}`);
  }
}

// Loop over an array using forEach which requires a callback fn.
// forEach will call the callback fn, and not we.
// forEach will pass each element as argument in every iteration.
account.forEach(function(money){
  if(money &amp;gt; 0){
    console.log(`Deposited ${money}`);
  } else {
    console.log(`Withdrawn ${Math.abs(money)}`);
  }
});
// Iteration 1: pass arg1 to CB-fn(arg1)
// Iteration 2: pass arg2 to CB-fn(arg2)
// Iteration 3: pass arg3 to CB-fn(arg3)
// .....
// .....


// forEach will pass each element, index, array as argument in every iteration. Order of arguments matter, not the no of these arguments i.e first element should be the current-Element, second element should be index, third element should be entire array which is being looped-over.
// first element must be element-value, second element should be index, third element must be entire array. This is how its different from array.entries()
account.forEach(function(money, i, arr){
  if(money &amp;gt; 0){
    console.log(`Transaction ${i+1}, Deposited ${money} into ${arr}`);
  } else {
    console.log(`Transaction ${i+1}, Withdrawn ${Math.abs(money)} from ${arr}`);
  }
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  When to use for-of &amp;amp; forEach:
&lt;/h2&gt;

&lt;p&gt;forEach: Cannot break-out of it. continue-break don't work inside it. Will always loop over the entire array, and nothing can be done to stop it.&lt;br&gt;
for-of: Used when we need to loop out of the array.&lt;/p&gt;

&lt;p&gt;"As you practice more &amp;amp; more, you'll get better in your skills."&lt;/p&gt;
&lt;h2&gt;
  
  
  forEach
&lt;/h2&gt;

&lt;p&gt;works on arrays as well as maps &amp;amp; sets also.&lt;br&gt;
creates side-effect as compared to map().&lt;br&gt;
elements are logged one by one.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Map
const currencies = new Map([
  // key, value pairs inside map are listed below
  ['USD', 'United States Dollar'],
  ['EUR', 'Euro'],
  ['GBP', 'British Pound']
]);

// called with currentValue in the iteration i.e val, with its key &amp;amp; the entire map
currencies.forEach(function(val, key, map){
  console.log(`${key}: ${val}`);
})


// Set: Need to pass an iterable as arg to 'new Set()'
const currenciesUnique = new Set(['USD','GBP','USD','GBP','EUR', 'INR', 'CAD']);
console.log(currenciesUnique);

// A set neither has keys nor indexes. Hence, to make forEach common for all, the callback fn signature was left like that.
// _ in arg denotes a complete unnecessary variable as we cannot have redundant args name. 
currenciesUnique.forEach(function(val, _ , map){
  console.log(`${val}: ${val}`);
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  map()
&lt;/h2&gt;

&lt;p&gt;maps values from an existing array to a new array based on C/b.&lt;br&gt;
similar to forEach, but it creates a brand new array.&lt;br&gt;
takes an array, loops over it, apply Callback fn on each element.&lt;br&gt;
map() will call the callback fn on each of the elements, not us.&lt;br&gt;
Each time map() calls a callback, it passes element, index, whole array.&lt;br&gt;
Side-effect is not created in each iteration of map() i.e elements are not logged one after another. All operations are completed, then the final result is logged.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const movements = [400, -200, 300, 500, -700, 100, -900];

// A new array is returned by map() without mutating the original array.
const eurToUsd = 1.1;
const movementsUSD = movements.map(mov =&amp;gt; (mov*eurToUsd).toFixed(2));

movements;
movementsUSD;

// Manually creating a new array.
const movementsUSDfor = [];
for(const mov of movements){
  movementsUSDfor.push((mov * eurToUsd).toFixed(2));
}
movementsUSDfor;

const movementsDescriptions = movements.map((mov, i, arr) =&amp;gt; {
  console.log(`Transaction ${i+1}: ${(mov&amp;gt;0)? 'Deposited' : 'Withdrawn'} ${Math.abs(mov)}`);  
});
movementsDescriptions;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  filter()
&lt;/h2&gt;

&lt;p&gt;filter out the elements in a new array which satisfy the C/b condn.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const movements = [400, -200, 300, 500, -700, 100, -900];
// Fnal approach. Fns can be chained here.
const deposits = movements.filter(mov =&amp;gt; {
  return mov&amp;gt;0;
});
deposits;

// Same result in both cases.
const depositFor = []
for(let mov of movements){
  if(mov&amp;gt;0){
    depositFor.push(mov);
  }
}
depositFor;

const withdrawls = movements.filter(mov =&amp;gt; {
  return mov&amp;lt;0;
});
withdrawls;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  reduce()
&lt;/h2&gt;

&lt;p&gt;reduces all elements down to a single value. &lt;br&gt;
Ex. adding all elements together. Define an accumulator, keep adding the current element to the accumulator to get the resultant sum in the end.&lt;br&gt;
this value is return from the method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const movements = [400, -200, 300, -500, -700, 100, 900];

// Fnal approrach using .reduce()
// loops over array, calls the callback on each iteration.
// acc is current sum of all the prev values.
const balance = movements.reduce(function(acc, cur, i, arr){
  console.log(`Iteration ${i+1}: ${acc}`)
  return acc + cur;
}, 1000); // 1000 is the initial value of acc in the first iteration
balance;

// for-of approach
let balance2 = 1000;
for(let mov of movements){
  balance2 += mov;
}
balance2;


// Maximum Value
const balance = movements.reduce(function(acc, mov){
  if(acc &amp;gt; mov){
    return mov;
  } else{
    return mov;
  }
}, movements[0]); // 1000 is the initial value of acc in the first iteration
balance;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>es6</category>
      <category>datastructures</category>
    </item>
    <item>
      <title>Functions</title>
      <dc:creator>Mohammed Ali</dc:creator>
      <pubDate>Thu, 05 Sep 2024 10:30:38 +0000</pubDate>
      <link>https://forem.com/mahf001/functions-1gke</link>
      <guid>https://forem.com/mahf001/functions-1gke</guid>
      <description>&lt;h2&gt;
  
  
  Intro to Fns:
&lt;/h2&gt;

&lt;p&gt;Fundamental building blocks of the language.&lt;br&gt;
Most essential concepts.&lt;br&gt;
Fn - piece of code which can be used again and again.&lt;br&gt;
{Invoking, Running, Calling} a Fn all mean the same.&lt;br&gt;
Fn - can take data as arguments, return data as result after computation.&lt;br&gt;
Fn call is replaced by the result returned from it after execution.&lt;br&gt;
Fns are perfect for implementing DRY principle&lt;br&gt;
Arguments are passed, parameters are placeholder which receives values passed to fn.&lt;/p&gt;
&lt;h2&gt;
  
  
  Fn declaration vs expression:
&lt;/h2&gt;

&lt;p&gt;Fn declaration begins with fn keyword.&lt;br&gt;
Fn expression are anonymous fn, stored inside a variable. Then that variable which stores the fn act as a fn.&lt;br&gt;
The anonymous fn defn is an expression, and the expression produces a value. Fn are just values.&lt;br&gt;
Fn are not a String, Number type. Its a value, hence can be stored in a variable.&lt;br&gt;
Fn declaration can be called even before they are defined in the code i.e they are hoised. This doesn't work with Fn expression.&lt;br&gt;
Fn expression forces the user to define fns first, then use them later. Everything is stored inside variables.&lt;br&gt;
Both have their place in JS, hence needs to be mastered properly.&lt;br&gt;
Fn expression = essentially a fn value stored in a variable&lt;/p&gt;
&lt;h2&gt;
  
  
  Arrow Fn came with ES6
&lt;/h2&gt;

&lt;p&gt;Implicit return for one-liner, for multiple lines explicit return is needed.&lt;br&gt;
Arrow fns don't get 'this' keyword of their own&lt;br&gt;
Learning is not an a linear process, knowledge builds up in an incremental way gradually. You cannot learn everything about a thing in one go.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;## Default parameters
const bookings = [];

const createBooking = function(flightNum, numPassengers=1, price= 100 * numPassengers){
  // It will work for parameters defined before in the list like numPassengers is defined before its used in expression of next argument else it won't work.
  // Arguments cannot be skipped also with this method. If you want to skip an argument, then manually pass undefined value for it which is equivalent to skipping an argument
  /* Setting default values pre-ES6 days.
  numPassengers = numPassengers || 1;
  price = price || 199;*/

// Using enhanced object literal, where if same property name &amp;amp; value is there, just write them once as shown below.
  const booking = {
    flightNum,
    numPassengers,
    price,
  };

  console.log(booking);
  bookings.push(booking);
}

createBooking('AI123');
/*
{
  flightNum: 'AI123',
  numPassengers: 1,
  price: 100
}
*/ 

createBooking('IN523',7);
/*
{
  flightNum: 'IN523',
  numPassengers: 7,
  price: 700
}
*/ 

createBooking('SJ523',5);
/*
{
  flightNum: 'SJ523',
  numPassengers: 5,
  price: 500
} 
*/ 

createBooking('AA523',undefined, 100000);
/*
{
  flightNum: 'AA523',
  numPassengers: 1,
  price: 100000
}
*/ 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Calling one fn from inside another fn:
&lt;/h2&gt;

&lt;p&gt;Very common technique to suport DRY principle.&lt;br&gt;
Supports maintainability&lt;br&gt;
return immediately exits the fn&lt;br&gt;
return = to output a value from the fn, terminate the execution&lt;br&gt;
Three ways of writing fn, but all work in a similar way i.e Input, Computation, Output&lt;br&gt;
Parameters = placeholders to receive i/p values, Like local variables of a fn.&lt;/p&gt;
&lt;h2&gt;
  
  
  How passing arguments works i.e Value vs Reference Types
&lt;/h2&gt;

&lt;p&gt;Primitives are passed by value to fn. Original value remains intact.&lt;br&gt;
Objects are passed by reference to fn. Original value is changed.&lt;br&gt;
JS doesn not have pass value by reference. &lt;/p&gt;

&lt;p&gt;Interaction of different fns with same object can create trouble sometimes&lt;/p&gt;
&lt;h2&gt;
  
  
  Fns are first-class in JS, hence we can write HO fns.
&lt;/h2&gt;

&lt;p&gt;Fns are treated as values, just another 'type' of object.&lt;br&gt;
Since objects are values, fns are values too. Hence, can also be stored in variables, attached as object properties etc.&lt;br&gt;
Also, fns can be passed to other fns also. Ex. event listeners-handlers.&lt;br&gt;
Return from fns.&lt;br&gt;
Fns are objects, and objects have their own methods-properties in JS. Hence, fn can have methods as well as properties which can be called on them. Ex call, apply, bind etc.&lt;/p&gt;

&lt;p&gt;Higher Order Fn : Fn that receives another fn as an argument, that returns a new fn or both. Only possible because fns are first class in JS&lt;br&gt;
Fn that is passed in callback fn, which will be called by HOF.&lt;/p&gt;

&lt;p&gt;Fns that return another fn, i.e in Closures.&lt;/p&gt;

&lt;p&gt;First class fns and HOF are different concepts.&lt;/p&gt;

&lt;p&gt;Callback Fns Adv:&lt;br&gt;
Allow us to create abstractions. Makes easier to look at larger problem.&lt;br&gt;
Modularize the code into more smaller chunks to be resused.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Example for CB &amp;amp; HOF:
// CB1
const oneWord = function(str){
  return str.replace(/ /g,'').toLowerCase();
};

// CB2
const upperFirstWord = function(str){
    const [first, ...others] = str.split(' ');
    return [first.toUpperCase(), ...others].join(' ');
};

// HOF
const transformer = function(str, fn){
  console.log(`Original string: ${str}`);
  console.log(`Transformed string: ${fn(str)}`);
  console.log(`Transformed by: ${fn.name}`);
};
transformer('JS is best', upperFirstWord);
transformer('JS is best', oneWord);

// JS uses callbacks all the time.
const hi5 = function(){
  console.log("Hi");
};
document.body.addEventListener('click', hi5);

// forEach will be exectued for each value in the array.
['Alpha','Beta','Gamma','Delta','Eeta'].forEach(hi5);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Fns returning another fn.
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// A fn returning another fn.
const greet = function(greeting){
  return function(name){
    console.log(`${greeting} ${name}`);
  }
}

const userGreet = greet('Hey');
userGreet("Alice");
userGreet("Lola");

// Another way to call
greet('Hello')("Lynda");

// Closures are widely used in Fnal programming paradigm.

// Same work using Arrow Fns. Below is one arrow fn returning another arrow fn.
const greetArr = greeting =&amp;gt; name =&amp;gt; console.log(`${greeting} ${name}`);

greetArr('Hola')('Roger');
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;"You will only progress once you understand a certain topic thoroughly"&lt;/p&gt;

&lt;h2&gt;
  
  
  call(), apply(), bind():
&lt;/h2&gt;

&lt;p&gt;Used to set 'this' keyword by explicitly setting its value.&lt;br&gt;
call - takes a list of arguments after the value of 'this' keyword.&lt;br&gt;
apply - takes an array of arguments after the value of 'this' keyword. It will take elements from that array, and pass it into functions.&lt;/p&gt;

&lt;p&gt;bind(): This method creates a new function with the this keyword bound to the specified object. The new function retains the this context set by .bind() no matter how the function is invoked.&lt;/p&gt;

&lt;p&gt;call() and apply(): These methods call a function with a specified this value and arguments. The difference between them is that .call() takes arguments as a list, while .apply() takes arguments as an array.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const lufthansa = {
  airline: 'Lufthansa',
  iataCode: 'LH',
  bookings: [],
  book(flightNum, name){
    console.log(`${name} booked a seat on ${this.airline} flight ${this.iataCode} ${flightNum}`);
    this.bookings.push({flight: `${this.iataCode} ${flightNum}`, name});
  },
};

lufthansa.book(4324,'James Bond');
lufthansa.book(5342,'Julie Bond');
lufthansa;


const eurowings = {
  airline: 'Eurowings',
  iataCode: 'EW',
  bookings: [],
};

// Now for the second flight eurowings, we want to use book method, but we shouldn't repeat the code written inside lufthansa object.

// "this" depends on how fn is actually called.
// In a regular fn call, this keyword points to undefined.
// book stores the copy of book method defuned inside the lufthansa object.
const book = lufthansa.book;

// Doesn't work
// book(23, 'Sara Williams');

// first argument is whatever we want 'this' object to point to.
// We invoked the .call() which inturn invoked the book method with 'this' set to eurowings 
// after the first argument, all following arguments are for fn.
book.call(eurowings, 23, 'Sara Williams');
eurowings;

book.call(lufthansa, 735, 'Peter Parker');
lufthansa;

const swiss = {
  airline: 'Swiss Airlines',
  iataCode: 'LX',
  bookings: []
}

// call()
book.call(swiss, 252, 'Joney James');

// apply()
const flightData = [652, 'Mona Lisa'];
book.apply(swiss, flightData);

// Below call() syntax is equivalent to above .apply() syntax. It spreads out the arguments from the array.
book.call(swiss, ...flightData);


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>es6</category>
    </item>
    <item>
      <title>Modules 2/2</title>
      <dc:creator>Mohammed Ali</dc:creator>
      <pubDate>Wed, 04 Sep 2024 11:58:18 +0000</pubDate>
      <link>https://forem.com/mahf001/iife-module-pattern-commonjs-5gkd</link>
      <guid>https://forem.com/mahf001/iife-module-pattern-commonjs-5gkd</guid>
      <description>&lt;ul&gt;
&lt;li&gt;Module Pattern was used before ES6 Modules.&lt;/li&gt;
&lt;li&gt;Goal: Encapsulate functionality, suport private data, expose public API and all this is achieved by using IIFEs.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  IIFE: Ex. (function(){})();
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// IIFE Goal: Create a new scope, return the data just once. All of data inside IIFE will be private as it would inside the fn scope. 
// Using this way, we don't need to call it separately. And it ensures its called only once.
// IIFE is created only once, goal is 'NOT TO REUSE' by executing it multiple times.

// Result of running an IIFE is stored, or else it will disappear simply.
const ShoppingCart2 = (function(){
  const cart = [];
  const shippingCost = 10;
  const totalPrice = 237;
  const totalQuantity = 10;

  const addToCart = function(product, quantity){
    cart.push({product, quantity});
    console.log(`${quantity} ${product} added to cart. Shipping cost is ${shippingCost}`);
  };

  const orderStock = function(product, quantity){
    console.log(`${quantity} ${product} ordered from supplier`);
  };
  // Need to return something, in order to return a public API. For that, an object is returned containing stuff which needs to be made public.
  return {
    addToCart,
    cart, 
    totalPrice,
    totalQuantity
  };
})();
// Everything inside the above module is private to the module.
// The above fn returns the object mentioned inside return statement and assign it to the ShoppingCart2 variable mentioned at the start of fn. This IIFE is returned then long ago.
// All this is possible because of closures. Hence, addToCart can acccess the cart variable.

ShoppingCart2.addToCart('apple', 4);
ShoppingCart2.addToCart('pizza', 5);
ShoppingCart2;
ShoppingCart2.shippingCost; // inaccessible.

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  The Module pattern has been working even before ES6 modules.
&lt;/h2&gt;

&lt;p&gt;Disadv:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Now if we want one module per file, like we have with ES6 modules then multiple scripts need to be created and linked inside the HTML file.&lt;/li&gt;
&lt;li&gt;The order of the script loading will also matter.&lt;/li&gt;
&lt;li&gt;All those variables will be living in global scope.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Beside native ES6 modules &amp;amp; module pattern, JS also supported other module systems which were not native to JS. Ex. AMD, CommmonJS&lt;br&gt;
Ex. CommonJS modules are used in Node.js for all of its existance. Recently ES6 modules have been implemented in Node.js&lt;br&gt;
All modules on npm repository still use the commonJS module system as npm was originally intended for node. Only later, npm became the repository for the whole JS world. Hence, we are basically stuck with CommonJS. So, CommonJS still needs to be paid attention to as its impt in Node.js&lt;br&gt;
Just like ES6 module, 1 file is 1 module in CommonJS.&lt;br&gt;
The commonJS code won't work in browser, but it will work in node.js&lt;br&gt;
ES Modules will replace all module system eventually but as of now we need to use commonjs also.&lt;/p&gt;

&lt;p&gt;export keyword is an object, which is not defined in our code as well as in browser.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// EXPORT
export.addToCart = function(product, quantity){
    cart.push({product, quantity});
    console.log(`${quantity} ${product} added to cart. Shipping cost is ${shippingCost}`);
};

// IMPORT: is similar to ES Modules but would use a require fn.
// require is not defined in browser env but its defined in node env as its a part of commonjs
const addToCart = require('./shoppingCart.js')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>modulepattern</category>
      <category>es6</category>
    </item>
    <item>
      <title>OOP in JS - 2/2</title>
      <dc:creator>Mohammed Ali</dc:creator>
      <pubDate>Tue, 03 Sep 2024 12:25:40 +0000</pubDate>
      <link>https://forem.com/mahf001/oops-in-js-22-5a2n</link>
      <guid>https://forem.com/mahf001/oops-in-js-22-5a2n</guid>
      <description>&lt;ul&gt;
&lt;li&gt;JS classes are like syntactic sugar, not the same as classes of other strongly typed languages.&lt;/li&gt;
&lt;li&gt;Only adds syntax-wrapping to make it familiar for devs coming from other languages.&lt;/li&gt;
&lt;li&gt;classes are a special type of functions behind the scenes, hence can be written as class expression as well as class declaration.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;## class expression:
const Person = class {
}

## class declaration:
class Person {
  constructor(fName, bYear){
   this.fName = fName;
   this.bYear = bYear;
  }
  calcAge(){
   console.log(2024 - this.bYear);
  }
}

- constructor is a method of this class. Pass values for properties to have in objects created using this fn.
- then set the properties of the object using this.xxx = xxx;
- On using 'new' operator, this constructor will be called automatically and return a new object which will be stored in LHS variable as shown below.
Ex. const ronald = new Person('ronald',1975); // Person { fName: 'ronald', bYear: 1975 }
- Methods are written outside the constructor fn and will be added to the prototype property of the object which can be verified using devConsole.
Ex. ronald.calcAge(); // 49

ronald.__proto__ === Person.prototype; // true

- No commas need to be added while adding multiple methods below the constructor fn inside the class.

## Hence, the above syntax works same as constructor fn syntax but with a familiar syntax of strongly typed class based languages.

## Adding a fn explicitly to the prototype:
Person.prototype.greet = function(){
console.log(`Hey ${this.fName}`);
}
ronald.greet(); // 'Hey ronald'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Impt Points:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Fn declarations are hoisted while Class declarations are NOT hoisted.&lt;/li&gt;
&lt;li&gt;Also first class citizen just like Fns i.e can be passed-to &amp;amp; returned-from fns.&lt;/li&gt;
&lt;li&gt;Body of class is always executed in strict mode whether we activate the strict mode or not.&lt;/li&gt;
&lt;li&gt;Classes make the code look cleaner, with reduced character noise provided you know how its implemented under the hood.
** To become an expert in JS, you need to understand the intricate language implementation details like with classes.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Accessor Properties: Getters &amp;amp; Setters i.e fns that get &amp;amp; set the value. But on the outside, they still look like regular properties.&lt;/p&gt;

&lt;p&gt;Normal Properties are called Data Properties.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Getters &amp;amp; Settters are common to all objects in JS i.e every object can have getter and setter property. These getter-setter are called as accessor properties, while normal properties are called as data properties.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  - Getter &amp;amp; setter are fns that get and set a value, from outside look like normal properties.
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const account = {
  owner: 'jonas',
  movements: [200,300,100,500],
  get latest(){
    // will return an array with last value. Hence, use pop to get the value.
    return this.movements.slice(-1).pop();
  },
  set latest(mov){
    this.movements.push(mov);
  }
}

account.latest; // 500
account.latest = 50; 
account.latest; // 50

Just like above, classes also support the getter-setter methods but acccessed like using a property syntax.

These are very useful for data validation.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Static Methods
&lt;/h2&gt;

&lt;p&gt;Ex. Array.from() = Converts array-like structure to array.&lt;br&gt;
Array.from(document.querySelector('h1'));&lt;br&gt;
Array.from(document.querySelectorAll('h1'));&lt;/p&gt;

&lt;p&gt;Ex. .from is attached to the Array construcutor, not to the prototype property of the constructor. Hence all arrays don't inherit this fn.&lt;br&gt;
[1,2,3].from(); // .from is not a function&lt;/p&gt;

&lt;p&gt;Ex. Number.parseFloat(12) is a static method on Number constructor, not available on number variables.&lt;/p&gt;
&lt;h2&gt;
  
  
  Creating a static method.
&lt;/h2&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Static methods are not inherited. They are not added to prototype.
className.fnName = function(){
  console.log(this); // Entire constructor() which is calling the method
  console.log("JS is awesome")
};
className.fnName();

// Rule =  whatever object is calling the method, 'this' points to that object inside the fn. Hence its simply the entire constructor() above.

//Inside class, we need to use static keyword for adding a static method.
static fnName = function(){
  console.log(this); // can point to the entire class defn
  console.log("JS is awesome")
};

// Static methods and instance methods will be different from each other.
// instance methods will be prototype, hence all instances can have access to them
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h2&gt;
  
  
  Object.create():
&lt;/h2&gt;

&lt;p&gt;Manually used to set prototype of our object to any object that we want.&lt;br&gt;
Will be used to implement inheritance b/w classes.&lt;br&gt;
Prototypal Inheritance Implemented using this fn.&lt;br&gt;
Object.create returns an empty object.&lt;br&gt;
Works in a different way in which constructor fns and classes work.&lt;br&gt;
Still there is idea of prototypal inheritance, even without involvement of 'prototype', 'constructor()', 'new' operator.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const PersonProto = {
  // This method will be looked up using __proto__ link
  calcAge(){
    console.log(2024 - this.bYear);
  }
};

// baba will be created, with its prototype set to PersonProto object.
const baba = Object.create(PersonProto);
baba;

baba.name = 'Roger';
baba.bYear = '2000';
baba.calcAge();

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Constructor Fn   --(.prototype)--&amp;gt;   Person.prototype&lt;br&gt;
Object Instance  --(&lt;strong&gt;proto&lt;/strong&gt;)--&amp;gt;    Person.prototype&lt;/p&gt;

&lt;p&gt;Works just like it worked for fn constructors or in classes&lt;br&gt;
No need of constructor() or .prototype property to achieve this goal.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const PersonProto = {
  // This method will be looked up using __proto__ link
  calcAge(){
    console.log(2024 - this.bYear);
  },
  // Noting special with init name, its a normal fn here.
  // This has nothing to with ES6 constructor()
  // Manual way of initialzing an object.
  init(fName, bYear){
    this.fName = fName;
    this.bYear = bYear;
  }
};

// baba will be created, with its prototype set to PersonProto object.
const baba = Object.create(PersonProto);
baba;

baba.name = 'Roger';
baba.bYear = '2000';
baba.calcAge();

baba.__proto__;    // { calcAge: [Function: calcAge] }
baba.__proto__ === PersonProto; //true


const alice = Object.create(PersonProto);
alice.init("alice", 2000);
alice;   // { fName: 'alice', bYear: 2000 }  
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Ways to create Prototypal Inhertitance:&lt;br&gt;
Constructor Fn&lt;br&gt;
ES6 Classes&lt;br&gt;
Object.create&lt;/p&gt;
&lt;h2&gt;
  
  
  Inheritance between Classes using constructor():
&lt;/h2&gt;

&lt;p&gt;All of these techniques allow object to lookup for methods on its prototype.&lt;br&gt;
Real classes do not exist in JS.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Person = function(firstName, bYear){
  this.firstName = firstName;
  this.bYear = bYear;
};

Person.prototype.calcAge = function(){
  console.log(2024 - this.bYear);
};

const Student = function(firstName, bYear, course){
  // This is the duplicate code, any change in Person won't be reflected here.
  this.firstName = firstName;
  this.bYear = bYear;
  this.course = course;
};

Student.prototype.introduce = function(){
  console.log(`My name is ${this.firstName} and I study ${this.course}`);
}

const matt = new Student("Matt", 2000, "CSE");
matt.introduce(); //  'My name is Matt and I study CSE'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Removing redundant code from above example:
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Person = function(firstName, bYear){
  this.firstName = firstName;
  this.bYear = bYear;
};

Person.prototype.calcAge = function(){
  console.log(2024 - this.bYear);
};

const Student = function(firstName, bYear, course){
  // Person(firstName, bYear); -&amp;gt; This doesn't work because we are calling it as a regular fn call. 'new' has to be used to call this fn constructor. This fn call is simply a regular fn call, in which 'this' is set 'undefined'. Hence, an error as it cannot set firstName on undefined.
  // We want to set the 'this' inside this fn to be same as inside Person above.
  Person.call(this, firstName, bYear);
  this.course = course;
};

Student.prototype.introduce = function(){
  console.log(`My name is ${this.firstName} and I study ${this.course}`);
}

const matt = new Student("Matt", 2000, "CSE");
matt.introduce(); //  'My name is Matt and I study CSE'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;'new' makes a link automatically between object instance and its prototype via &lt;strong&gt;proto&lt;/strong&gt;&lt;br&gt;
Whole idea of inheritance is that child class can share behavior from parent classes up the prototype chain.&lt;br&gt;
Prototype[Object.prototype] = null; // Sits on top of prototype chain.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Person = function(firstName, bYear){
  this.firstName = firstName;
  this.bYear = bYear;
};

Person.prototype.calcAge = function(){
  console.log(2024 - this.bYear);
};

const Student = function(firstName, bYear, course){
  Person.call(this, firstName, bYear);
  this.course = course;
};

// Student.prototype = Person.prototype; =&amp;gt; This doesn't work because we won't get the prototype chain, rather we will get 
// Constructor fn[i.e Person()]    --------------&amp;gt; Person.prototype
// Constructor fn[i.e Student()]   --------------&amp;gt; Person.prototype
// Object [Matt] __proto__: Student.prototype ---&amp;gt; Person.prototype

// Student.prototype manually linked for lookup to Person.prototype.
// This has to be done here and not after else Object.create will overwrite any of the existing methods like introduce() on it.
Student.prototype = Object.create(Person.prototype);

Student.prototype.introduce = function(){
  console.log(`My name is ${this.firstName} and I study ${this.course}`);
}

const matt = new Student("Matt", 2000, "CSE");
matt.introduce(); //  'My name is Matt and I study CSE'
matt.calcAge();    // 24

matt.__proto__;                   // Person { introduce: [Function (anonymous)] }
matt.__proto__.__proto__;        // { calcAge: [Function (anonymous)] }
matt.__proto__.__proto__.__proto__;   // [Object: null prototype] {}

Student.prototype.constructor = Student;   // [Function: Student]

matt instanceof Student; // true
matt instanceof Person; // true
matt instanceof Object; // true
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;class syntax hides a lot of behind the scene details.&lt;br&gt;
Its just a layer of abstraction over constructor fns.&lt;br&gt;
Mainly extend, super are needed to implement the same functionality of inheritance using classes which was established above using constructor fns.&lt;/p&gt;

&lt;p&gt;extends - inheritance between classes, automatically sets prototype chain for us.&lt;/p&gt;

&lt;p&gt;public field - similar to property defined in the constructor, available on created object&lt;/p&gt;

&lt;p&gt;private field - not accessible outside of class, perfect for implementation of data privacy &amp;amp; encapsulation&lt;/p&gt;

&lt;p&gt;static public field - available only on class&lt;/p&gt;

&lt;p&gt;constructor() - automatically called by new operator whenever a new object from the class is created. Mandatory in parent class, can be omitted in child class if we want to have exact same name &amp;amp; same no of arguments in child class.&lt;/p&gt;

&lt;p&gt;super(): &lt;br&gt;
its the constructor fn of the parent class, just pass-in the required arguments.&lt;br&gt;
Always need to happen first, as this call is responsible for creating 'this' keyword in child-class.&lt;br&gt;
Without doing this, we won't be able to access the 'this.course = course'&lt;br&gt;
call to parent(super) class (necessary with extend). Needs to happen before accessing 'this' keyword in the constructor.&lt;/p&gt;

&lt;p&gt;instance property - available on each created object, set based on input data of the constructor. fields are common for all the object, while these properties are unique for each object.&lt;/p&gt;

&lt;p&gt;getter method - get a value out of an object by simply writing a property instead of a method.&lt;/p&gt;

&lt;p&gt;setter method - use '_' to set a property with name as method, and also add getter.&lt;/p&gt;

&lt;p&gt;static method - available only on class, cannot access instance properties nor methods, only static ones. Ex. only static public fields will be accessible inside static methods.&lt;/p&gt;

&lt;p&gt;NOTE: Classes are:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;syyntactic sugar over constructor fns.&lt;/li&gt;
&lt;li&gt;not hoisted&lt;/li&gt;
&lt;li&gt;first class citizens just like fns.&lt;/li&gt;
&lt;li&gt;class body is always executed in strict mode&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>es6</category>
      <category>javascript</category>
      <category>webdev</category>
      <category>classes</category>
    </item>
    <item>
      <title>Modules 1/2</title>
      <dc:creator>Mohammed Ali</dc:creator>
      <pubDate>Mon, 02 Sep 2024 11:53:10 +0000</pubDate>
      <link>https://forem.com/mahf001/javascript-modules-101-2o4m</link>
      <guid>https://forem.com/mahf001/javascript-modules-101-2o4m</guid>
      <description>&lt;ul&gt;
&lt;li&gt;Now we don't write all JS in a single file and send to the client.&lt;/li&gt;
&lt;li&gt;Today, we write code into modules which share data between them and are more maintainable.&lt;/li&gt;
&lt;li&gt;Convention is to use camelCase names for Modules.&lt;/li&gt;
&lt;li&gt;We can even include 3rd party modules into our own code via npm repos like jquery, react, webpack, babel etc.&lt;/li&gt;
&lt;li&gt;A final bundle is built from small module files which is deployed to prod server, eventually being sent to clients.&lt;/li&gt;
&lt;li&gt;Modules are not supported by older browsers&lt;/li&gt;
&lt;li&gt;For perf reasons, its better to send small js files to browser.&lt;/li&gt;
&lt;li&gt;Modules ar super-important part of JS, already used in other languages for decades by devs.&lt;/li&gt;
&lt;li&gt;Modules: reusable piece of code, which encapsulates implementation details of a certain part of our project.&lt;/li&gt;
&lt;li&gt;Its a standalone file, but it doesn't have to be.&lt;/li&gt;
&lt;li&gt;Modules can also have imports &amp;amp; exports
Native ES6 Modules: There were no modules before ES6. Had to be implemented ourselves or use external libararies. Modules are stored in files, exactly one module per file.&lt;/li&gt;
&lt;li&gt;We can export values, functions out of modules etc. Whatever we export is called a public API which is exposed for other code to consume.&lt;/li&gt;
&lt;li&gt;This public API is consumed by importing public code into module and are called dependencies.&lt;/li&gt;
&lt;li&gt;Simple applns can be written without modules also, but for enterprise scale projects we need modules.&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Adv: &lt;br&gt;
-&amp;gt; Makes really easy to compose software as modules are small building blocks that we put together to build complex applications.&lt;br&gt;
-&amp;gt; Isolating Components: Each feature can be developed in complete isolation and without worrying about the work of other devs or how the entire system works.&lt;br&gt;
-&amp;gt; Code abstraction: Implement low level code in modules, import these abstractions into other modules, naturally leading to a more organized codebase.&lt;br&gt;
-&amp;gt; Code reusability: Allow us to reuse code even across multiple projects.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Modern JS uses bundling &amp;amp; transpiling.&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;## Bundling = is a complex process which involves:
a. Eliminate unused Code
b. Combine all modules into single file.
c. Compress the code.
Ex. webpack build tool - requires manual config, hence complex.
Ex. parcel - zero build tool as we don't need to write any setup code.

## Transpiling/Polyfiling:
Convert modern JS to ES5 or older syntax such that older browser supports the application. 
Ex. done using tool called Babel

Entire process results in the final bundle file for production ready to be deployed on server. 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;### Scripts are also files but they are different from ES6 modules in the following ways:
Script[used earlier]:
- All top level variables are always global. This leads to global namespace pollution and name-coliision.
- Default mode: Sloppy mode
- Top level 'this' points to window object.
- Import/Export of values is not allowed.
- Linked to html using plain script tag.
- Downloaded by default in sync way, unless async or defer attribute is used.

### ES6 Modules:
- All top-level variables are scoped to module i.e they are private by default. Such a value can be access by outside varible only when its exported by the module else it will be inaccessible for outside world.
- Default mode: Strict mode. Hence with modules no more need to declare strict mode.
- Top level 'this' is 'undefined'
- Allows import/export of values using ES6 syntax of import/export.
- Link to html file using &amp;lt;script type="module"&amp;gt; tag.
- File download always happens in an async way, i.e for module loaded from html or an import one module to another.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;## Understanding module import process:
Parsing -&amp;gt; [Asyn module download, Linking import-export, Execute individual module itself] -&amp;gt; Execution overall index.js
- import/export only need to happen at the top level of if-block or any function. Imports are hoisted. Importing values is always the first thing which happens in a module.
- Top-level static imports make imports known before execution. 
- Modules are loaded in async way from the server, importing happens in sync manner. 
- Parsing refers to reading the code without executing it in which imports are hoisted. Modules are imported even before execution. Hence, it enables bundling &amp;amp; code elimation even before fn exection. [V Impt as large projects have 100s of modules, and 3rd party modules also from which we want the small piece and not the entire module]
- Bundlers can then join multiple modules, and then eliminate code. hence, we can easily import/export from code.
- After a module arrives, its parsed and then the module exports are linked to imports in index.js i.e live connection is established between import inside index.js and export statement of the module file. They are not copied. Import is just a reference to the exported value. Hence, when the value changes in the exporting module, it also changes in the importing module too. This concept is unique to ES6 modules, other module system don't work like this.
- Code in the imported modules is executed.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzktgq9emtdu6n6ri35s4.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzktgq9emtdu6n6ri35s4.jpg" alt="Import-Export-JS1" width="800" height="395"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpjyz4e8dzh21ad9mi0zx.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpjyz4e8dzh21ad9mi0zx.jpg" alt="Import-Export-JS2" width="800" height="491"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>modules</category>
      <category>es6</category>
      <category>webdev</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Demystifying Closures in JS</title>
      <dc:creator>Mohammed Ali</dc:creator>
      <pubDate>Sun, 01 Sep 2024 00:30:00 +0000</pubDate>
      <link>https://forem.com/mahf001/demystifying-closures-in-js-43df</link>
      <guid>https://forem.com/mahf001/demystifying-closures-in-js-43df</guid>
      <description>&lt;ul&gt;
&lt;li&gt;Needs to be mastered to understand the intricate details of the language.&lt;/li&gt;
&lt;li&gt;Not created like we create an array or function.&lt;/li&gt;
&lt;li&gt;A fn returning another fn which is stored inside the LHS variable.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const secureBooking = function(){
  let passengerCount = 0;
  return function(){
    passengerCount++;
    console.log(`${passengerCount} passengers`);
  }
}

const booker = secureBooking();

booker();
booker();
booker();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;secureBooking fn is executed in global scope.&lt;/li&gt;
&lt;li&gt;A new execution context will be created on the global execution context. &lt;/li&gt;
&lt;li&gt;Every execution context(EC) has its own variable environment with all of its variables. 'let passengerCount = 0' is defined inside this EC.
It can access all varibles of its parent scope.&lt;/li&gt;
&lt;li&gt;A new fn is returned, and will be stored in booker.&lt;/li&gt;
&lt;li&gt;The Global EC will also contain the booker variable.&lt;/li&gt;
&lt;li&gt;Now secureBooking() will be removed from EC and is gone. The secureBooking EC environment is no longer active. But still the passengerCount variable is being accessed which was defined at the time of fn creation.&lt;/li&gt;
&lt;li&gt;Still, inner fn will be able to access the passengerCount varible defined inside outer fn. This happens due to closure. &lt;/li&gt;
&lt;li&gt;Closure makes the fn remember the varibles defined surrounding the birthplace of the fn or its EC.&lt;/li&gt;
&lt;li&gt;booker is not a fn, located in global scope.&lt;/li&gt;
&lt;li&gt;Now executing booker(); for the first time will create an EC on the call stack, with its own variables.&lt;/li&gt;
&lt;li&gt;A fn has access to the variable environment of the execution context in which the fn was created i. secureBooking. Hence, booker will have access to variables defined in variable environment of secureBooking fn. This connection of fn's birthplace i.e of definition to its surrounding variable environment is called Closure even after the EC of secureBooking fn containing the fn has popped out of Call Stack.&lt;/li&gt;
&lt;li&gt;Closure: Variable Environment attached to the fn, exactly as it was at the time and place the fn was created.&lt;/li&gt;
&lt;li&gt;Scope chain is preserved through the closure, even though EC is gone the variable enviroment keeps living somehow in the Engine. Hence, we say booker fn is closed over parent fn including parent fn arguments which we don't have here.&lt;/li&gt;
&lt;li&gt;Using closure, a fn does not lose connection to the variables defined surrounding its birthplace.&lt;/li&gt;
&lt;li&gt;If variable is not in current scope, JS looks into closure even before looking up the scope chain. Suppose if there is a global variable, even then the variable defined in its closure is looked up first.&lt;/li&gt;
&lt;li&gt;Closure has priority over scope chain.&lt;/li&gt;
&lt;li&gt;After running the booker() for the first time, value of passengerCount is incremented, logged in console and then booker is popped off call stack.&lt;/li&gt;
&lt;li&gt;Execution moves to next line, a new EC is created but the closure variable is still there. The existing value is incremented and the EC is popped out.&lt;/li&gt;
&lt;li&gt;Again the third time this process repeats.&lt;/li&gt;
&lt;/ul&gt;

&lt;h1&gt;
  
  
  SUMMARY
&lt;/h1&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Defn: A closure is closed-over variable environment of the EC in which a fn was created, even after that EC has gone.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Also, a closure gives a fn access to all the variables of its parent fn, even after that parent fn has returned. The fn keeps a reference to its outer scope, which preserves the scope chain throughout time. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;A closure ensures that the fn doesn't lose connection to variables that existed at the time of fn's birth. Its like a backpack that a fn carries around wherever it goes. This backpack has all the variables that were present in the environment where the fn was created.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;We don't have to create closures manually. Also, we can't even access closed-over variables explicitly. A closure is not a tangible JS object i.e we cannot reach to a closure and take variables from it. Its an internal property of a fn. To take a look at backpack, "console.dir(booker);"&lt;br&gt;
[[Scope]] will show you about the VE of this fn call.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;[[]] means its an internal property, which we cannot access from our code.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;We always don't need to return a fn from another fn to create a closure. In below example, variable 'f' wasn't even defined inside the fn also, as its in global scope. Its able to access the 'a' variable also even after g() has finished its EC. 'a' is inside the backpack of 'f' now.&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let f;

const g = function(){
  const a = 23;
  f = function() {
    console.log(a*2); // 46
  };
};


const h = function(){
  const b = 777;
  f = function(){
    console.log(b*2); // 1554
  };
};

g();
f();
console.dir(f);

// f fn is reassigned using h fn. Hence, old closure value i.e 'a' will be replaced with new value 'b' which can be verified using console.dir().
h();
f();
console.dir(f);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;setTimeout(callbackFnToBeCalled, Delay);&lt;/li&gt;
&lt;li&gt;Closure variables have higher priority over scope chain.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Boarding Passengers using Closures
const boardPassengers = function(n, wait){
  const perGroup = n / 3;

  setTimeout(function(){
    console.log(`We are now boarding all ${n} passengers`);
    console.log(`There are 3 groups, each with ${perGroup} passengers`)
  }, wait*1000);

  console.log(`Will start boarding in ${wait} seconds`);
}

boardPassengers(180, 3);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>es6</category>
      <category>javascript</category>
      <category>webdev</category>
      <category>functional</category>
    </item>
    <item>
      <title>JavaScript Engine</title>
      <dc:creator>Mohammed Ali</dc:creator>
      <pubDate>Sat, 31 Aug 2024 11:18:57 +0000</pubDate>
      <link>https://forem.com/mahf001/javascript-engine-12ld</link>
      <guid>https://forem.com/mahf001/javascript-engine-12ld</guid>
      <description>&lt;h1&gt;
  
  
  JS Engine:
&lt;/h1&gt;

&lt;ul&gt;
&lt;li&gt;Program that executes JS code. Ex. Google's V8.&lt;/li&gt;
&lt;li&gt;V8 powers Chrome, Node.js&lt;/li&gt;
&lt;li&gt;Other browsers have their own JS Engine.&lt;/li&gt;
&lt;/ul&gt;

&lt;h1&gt;
  
  
  JS Engine has 2 parts:
&lt;/h1&gt;

&lt;ol&gt;
&lt;li&gt;Call Stack: Where our code is executed using execution context.&lt;/li&gt;
&lt;li&gt;Heap: Unstructured memory pool, used for storing objects.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Every c/r program needs to be converted to machine code. Done via two processes:&lt;/p&gt;

&lt;h2&gt;
  
  
  1. Compilation: Entire code is converted into machine code at once, written to a binary file that can be execued by a computer.
&lt;/h2&gt;

&lt;p&gt;Source Code -(compiled)-&amp;gt; Binary Code[Portable File] -(executed)-&amp;gt; Pgm Run&lt;br&gt;
Execution can happen way after compilation.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. Interpretation: Interpreter runs through the source code, executes it line by line.
&lt;/h2&gt;

&lt;p&gt;Source code -(execution line by line)-&amp;gt; Pgm Run&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Here code still needs to be converted to machine code. &lt;/li&gt;
&lt;li&gt;They are much slower as compared to compiled l/gs.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  3. JIT i.e Just in Time Compilation:
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Modern JS Engine is a mix of compilation &amp;amp; interpretation to make it fast.&lt;/li&gt;
&lt;li&gt;Entire code is converted into machine code at once, then executed immediately.
Source Code -(compiled)-&amp;gt; Machine code -(executed)-&amp;gt; Pgm Run&lt;/li&gt;
&lt;li&gt;There is no intermediate portable file to execute.&lt;/li&gt;
&lt;li&gt;Execution happens immediately after compilation.&lt;/li&gt;
&lt;li&gt;Hence, JS now is much faster than interpreted l/gs due to this technique.&lt;/li&gt;
&lt;/ul&gt;

&lt;h1&gt;
  
  
  Compilation Process in JS:
&lt;/h1&gt;

&lt;h2&gt;
  
  
  Step 1. Parsing:
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Our code is Parsed i.e read by JS engine into AST or Abstract Syntax Tree. &lt;/li&gt;
&lt;li&gt;Works by splitting code into a tree based on keywords like const, let, function etc which are meaningful to the l/g.&lt;/li&gt;
&lt;li&gt;Then saves the code into a tree in a structured way.&lt;/li&gt;
&lt;li&gt;Also check for any syntax errors.&lt;/li&gt;
&lt;li&gt;AST has nothing to do with the DOM tree. AST is just representation of our code inside the JS Engine.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Step 2, 3[combined]: Compilation + Execution
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;AST is compiled and immediately executed after it, using JIT.&lt;/li&gt;
&lt;li&gt;Execution happens in Call stack.&lt;/li&gt;
&lt;li&gt;Modern JS has clever optimisation strategies, i.e they quickly create an unoptimized version of machine code in begining so as to start execution asap.&lt;/li&gt;
&lt;li&gt;In the background, this code is again recompiled during an already running pgm execution.&lt;/li&gt;
&lt;li&gt;Done in mutiple iterations, and after each optimisation the unoptimized code is swapped with newly optimized code without ever stopping the code execution. This makes V8 so fast.&lt;/li&gt;
&lt;li&gt;All this parsing, compilation, execution happens in some special thread inside JS Engine which we can't access using our code completely separate from the main thread which is running our code using call stack.&lt;/li&gt;
&lt;li&gt;JS is no more just interpreted l/g. It has JIT compilation which makes it way faster than interpreted l/gs.&lt;/li&gt;
&lt;/ul&gt;

&lt;h1&gt;
  
  
  JS Runtime = JS Engine + Web APIs + C/B Queue
&lt;/h1&gt;

&lt;ul&gt;
&lt;li&gt;JS Runtime: Container including all the things that we need to use JS.&lt;/li&gt;
&lt;li&gt;Heart of any JS runtime is JS Engine.&lt;/li&gt;
&lt;li&gt;Without JS Engine, there is no runtime hence no JS at all.&lt;/li&gt;
&lt;li&gt;JS Engine alone is not enough, we need access to Web APIs like DOM, Fetch, Timers etc.&lt;/li&gt;
&lt;li&gt;Web APIs: Functionality provided to engine by runtime, but not part of JS engine. Ex. window object in browser, global object in node.&lt;/li&gt;
&lt;li&gt;Callback Queue is a data structure containing all the functions ready to be executed. Ex. click, timer, data etc&lt;/li&gt;
&lt;li&gt;DOM Event handler fns are also called as callback fns.&lt;/li&gt;
&lt;li&gt;When Call stack is empty, callback fn is shifted from C/B queue to Call stack for execution.&lt;/li&gt;
&lt;li&gt;The continuous checking &amp;amp; shifting is performed by Event Loop.&lt;/li&gt;
&lt;li&gt;Event loop is something which enables JS to have a non-blocking concurrency model.&lt;/li&gt;
&lt;li&gt;For node, we don't have Web APIs provided by browser. We have something called as C++ bindings &amp;amp; thread pool.&lt;/li&gt;
&lt;/ul&gt;

&lt;h1&gt;
  
  
  How JS Code executes on the Call Stack
&lt;/h1&gt;

&lt;ul&gt;
&lt;li&gt;JS has single thread of execution, hence can do only thing at a time. Hence, no multiasking in JS.&lt;/li&gt;
&lt;li&gt;APIs are provided by environment, but not the part of language. Ex. Web APIs like Timers, Fetch, DOM, Geolocation etc.&lt;/li&gt;
&lt;li&gt;Callback Queue: Ready to be executed callback fns that are attached to some event which has occurred.&lt;/li&gt;
&lt;li&gt;Whenever call stack is empty, event loop transfers callback from calback to queue to call stack for execution.&lt;/li&gt;
&lt;li&gt;Event loop is hence an essential piece which makes Async behavior in JS possible.&lt;/li&gt;
&lt;li&gt;Concurrency Model: How a l/g handles multiple things happening at the same time.&lt;/li&gt;
&lt;li&gt;Essential parts of JS Runtime:&lt;/li&gt;
&lt;li&gt;Call Stack&lt;/li&gt;
&lt;li&gt;Web APIs&lt;/li&gt;
&lt;li&gt;Callback Queue&lt;/li&gt;
&lt;li&gt;Event loop&lt;/li&gt;
&lt;li&gt;Everything related to DOM is part of Web APIs, not JS.&lt;/li&gt;
&lt;li&gt;Image loading happens in async way, had it been in sync way then it would have been blocking i.e not on main thread rather Web APIs environment.&lt;/li&gt;
&lt;li&gt;All the event listeners, .then() etc work happens in WEb APIs environment and not on call stack.&lt;/li&gt;
&lt;li&gt;Callback fns are placed in callback queue waiting for them to be executed onn call stack.&lt;/li&gt;
&lt;li&gt;Callback queue is like a todo list which a call-stack has to complete.&lt;/li&gt;
&lt;li&gt;Duration mentioned is the minimum delay before for execution, and not the time for execution.&lt;/li&gt;
&lt;li&gt;Callback queue also contains callbacks coming from DOM events, clicks, keypress etc. DOM events are not async behavior, but they use callback queue for their execution.&lt;/li&gt;
&lt;li&gt;Event loop keeps checking the callback queue until its empty. Each callback placed on call stack is called as event loop tick.&lt;/li&gt;
&lt;li&gt;Event loop orchestrates the entire JS runtime.&lt;/li&gt;
&lt;li&gt;JS has itself no sense of time as Async code doesn't execute in engine. Its the runtime which manages async behavior and the event loop who decides which callback to be executed.&lt;/li&gt;
&lt;li&gt;Engine or Call stack simply executes the code given to it.&lt;/li&gt;
&lt;li&gt;When an image is to be loaded, the event listener keeps on waiting in the Web APIs environment until load event is fired off. When its fired, then only it goes to callback queue as a callback fn waiting for its turn to be executed on call stack.&lt;/li&gt;
&lt;/ul&gt;

&lt;h1&gt;
  
  
  Microtask Queue:
&lt;/h1&gt;

&lt;ul&gt;
&lt;li&gt;Callbacks from Promises don't go to callback queue, they go to microtask queue.&lt;/li&gt;
&lt;li&gt;This queue has higher priority over callback queue.&lt;/li&gt;
&lt;li&gt;Event loop checks this queue first, executes all of its task first, then goes to callback queue for execution.&lt;/li&gt;
&lt;li&gt;Callbacks on promises are called microtasks, hence its called microtask queue. There are other microtasks also, but not relevant here as of now.  Event loop decides when each callback is executed. It gives microtask higher priority as compared to callback queue&lt;/li&gt;
&lt;li&gt;Microtasks can cut inline before all other regular callback queues.&lt;/li&gt;
&lt;li&gt;Promise.resolve() : creates a promise which is resolved immediately, and its success value is passed inside it as argument. then() callback is called with resolved value as argument.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.log("Direct simple console BEGIN");
setTimeout(() =&amp;gt; console.log("Text from Timer"),0);
Promise.resolve("Text from Promise").then(res =&amp;gt; console.log(res));
console.log("Direct simple console END");

Order of Output:
Direct simple console BEGIN
Direct simple console END
Text from Promise
undefined
Text from Timer
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;A microtask queue can even starve the callback queue also if there are lot of microtasks in it or time-consuming microtasks.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.log("Direct simple console BEGIN");
setTimeout(() =&amp;gt; console.log("Text from Timer"),0);
Promise.resolve("Text from Promise1").then(res =&amp;gt; console.log(res));
Promise.resolve("Text from Promise2").then(res =&amp;gt; {
  for(let i=0; i&amp;lt;5000; i++)
  console.log(res);
});
console.log("Direct simple console END");
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>programming</category>
      <category>advanced</category>
    </item>
  </channel>
</rss>
