JavaScript Quick Revision – 3

Topics Covered

  • JS Engine
  • V8 Browser Architecture
  • Concurrency Model in JS
  • Higher Order Functions
  • Map, Filter and Reduce

JS Engine

Javascript Runtime Environment is a container which has everything required to run a JS code. Every Browser has a JS Runtime Environment. Node.js has its own runtime environment. Javascript Runtime Environment commonly has the following components:

  • Javascript Engine
  • APIs that are specific to the runtime environment. Browser has APIs like setTimeOut, console, fetch etc.
  • Event Loop
  • Callback Queue
  • Microtask Queue.

Common Javascript Engines:

  • V8 – is the JS engine for Google’s Chrome
  • Chakra – for Microsoft Edge
  • SpiderMonkey – for Mozilla Firefox

JS Engine in a browser executes in the following stages:

Code -> Parsing -> Compilation -> Execution

  • Parsing: The parser breaks down the code into Tokens. Then the syntax parser creates an AST – Abstract Syntax Tree. The AST is sent to the compilation phase.
  • Compilation: Most Browsers perform JIT – Just In Time compilation. They have an interpreter and a compiler that converts to byte code and optimizes code before execution.
    • Optimization techniques commonly used: In-lining, copy elision, Inline caching etc.
    • There is also a garbage collector to free-up space. It uses the Mark & Sweep Algorithm
  • Execution: Byte code is sent to the execution phase. Execution of the byte code happens with the help of two major components of the JS Engine: Memory Heap and the Call Stack.

V8 Browser Architecture

Name of the Interpreter in V8 is Ignition and that of the compiler is TurboFan

Concurrency Model in JS

Let us first understand what concurrency is all about. Parallelism is another concept closely associated with Concurrency.

Concurrency vs Parallelism

Parallelism: Is when two or more tasks or two threads are running parallelly or at the same time on different CPU cores.

Concurrency: Is when there is only one core/resource and multiple threads or tasks run on the same core by sharing time.

Concurrency Model in JS is based on the event loop. JS has a single call Stack. The Event loop waits until the Global Execution Context is popped out. That means, it waits until the main thread completes execution. After that it picks up tasks from the callback queue or microtask queue and adds it onto the stack for execution.

Higher Order Functions

They are functions that take another function as an argument or return a function.

Writing a custom MAP function:

const arr = [6, 1, 3, 5];

Array.prototype.area = function (shape) {
  output = [];
  for (let i = 0; i < this.length; i++) {
    output.push(shape(this[i]));
  }
  return output;
};

function square(side) {
  return side * side;
}

function circle(radius) {
  return Math.PI * radius * radius;
}

console.log(arr.area(square));
console.log(arr.area(circle));

Map, Filter and Reduce

  • Map: Iterates through a list and performs the function passed as argument, on each element.
  • Filter: (Filters the list) Iterates through a list and returns only those elements which have the truth value as “true” when returned from the function (that is passed as argument).
  • Reduce: reduces the list to a required value (sum, max etc). Takes two arguments: arr.reduce((acc,curr),init). The first argument is the Accumulator and the Current element of the list. Second argument is the initial value to be assigned to the Accumulator.

Let us see some examples:

const arr = [6, 1, 3, 5, 14];

const users = [
  { firstname: "Mickey", lastname: "Mouse", age: 12 },
  { firstname: "Donald", lastname: "Duck", age: 10 },
  { firstname: "Goofy", lastname: "Puppy", age: 5 },
  { firstname: "Miney", lastname: "Mouse", age: 12 },
];

//MAP
const square = arr.map((a) => a * a);
const cube = arr.map((a) => a * a * a);
const binary = arr.map((a) => a.toString(2));

const fullname = users.map((each) => each.firstname + " " + each.lastname);

//FILTER
const odd = arr.filter((x) => x % 2);
const even = arr.filter((x) => x % 2 === 0);

//return first name of all those users who's age is 12
const age12 = users.filter((x) => x.age == 12).map((y) => y.firstname);

//REDUCE
const sum = arr.reduce((acc, curr) => acc + curr, 1);
const max = arr.reduce((acc, curr) => {
  if (curr > acc) {
    acc = curr;
  }
  return acc;
}, 0);

//return an age map which looks like {5: 1, 12: 2, 10: 1}
const ageMap = users.reduce((acc, curr) => {
  if (acc[curr.age]) {
    acc[curr.age] = ++acc[curr.age];
  } else {
    acc[curr.age] = 1;
  }
  return acc;
}, {});

//return first name of all those users who's age is 12
const age12reduce = users.reduce((acc, curr) => {
  if (curr.age == 12) {
    acc.push(curr.firstname);
  }
  return acc;
}, []);

Link to Previous Blogposts:

JavaScript Quick Revision – 1

JavaScript Quick Revision – 2

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s