🦸🏻‍♂️ Javascript Questions

🔸 Are semicolons required in JavaScript?

Answer

🔸 What happens when you call a constructor function with the new keyword

Answer

🔸 null vs undefined

Answer

🔸 What is a closure, and how/why would you use this?

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function.

In JavaScript, closures are created every time a function is created, at function creation time.

Whenever a function is declared in JavaScript a closure is created. inside the IIFE

Closure Scope Chain: Every closure has three scopes

  1. Local Scope (Own scope)
  2. Outer Functions Scope
  3. Global Scope
// global scope
var e = 10;
function sum(a) {
return function (b) {
return function (c) {
// outer functions scope
return function (d) {
// local scope
return a + b + c + d + e;
};
};
};
}
console.log(sum(1)(2)(3)(4)); // log 20

I came across great post on closure please refer this to understand more link

🔸 Can you give a useful example of closure?

  • closure can be used for function currying
  • Situations where you might want to do this are particularly common on the web. Much of the code written in front-end JavaScript is event-based. You define some behavior, and then attach it to an event that is triggered by the user (such as a click or a keypress). The code is attached as a callback (a single function that is executed in response to the event).
  • You can emulate private methods with closures. Languages such as Java allow you to declare methods as private but JavaScript does not provide a native way of doing this, but it is possible to emulate private methods using closures, this resulting the modularization
var counter = (function () {
var privateCounter = 0;
function changeBy(val) {
privateCounter += val;
}
return {
increment: function () {
changeBy(1);
},
decrement: function () {
changeBy(-1);
},
value: function () {
return privateCounter;
},
};
})();
console.log(counter.value()); // 0.
counter.increment();
counter.increment();
console.log(counter.value()); // 2.
counter.decrement();
console.log(counter.value()); // 1.

🔸 What are the consideration that we need to avoid while working with closure

Answer

🔸 Explain how this works

Answer

🔸 Explain how prototypal inheritance works.

Answer

🔸 How does prototypal inheritance differ from classical inheritance?

Answer

🔸 What's a typical use case for anonymous functions?

Answer

🔸 What's the difference between host objects and native objects?

Answer

🔸 Can you give an example of a curry function and why this syntax offers an advantage?

Answer

🔸 Explain how Event Loop works and explain the individual component that take a part in it

Answer

🔸 Explain Promise, Promise Chain and its methods

Answer

🔸 Promise.race vs Promise.all

Answer

🔸 How Callback function different then Promise and what problem promise can solve

Answer

🔸 How async and await works and how it solved the problem of promise

Answer

🔸 What is Computed properties what us the typical use cases of this

Answer

🔸 What is generators and how is it different from function

Answer

🔸 What are the real use-case of the generators

  1. Generators can be implement in replacement for an iterators

Let me show you with a simple example.

Here i am just trying to generate natural no from 1, 10 using an Symbol.Iterator

let range = {
from: 1,
to: 10,
[Symbol.iterator]() {
return {
current: this.from,
last: this.to,
next() {
if (this.current < this.last) {
return {done: false, value: this.current++};
} else {
return {done: true};
}
},
};
},
};
console.log([...range]); // [1,2,3,4,5,6,7,8,9]

Now the above can be simplified using generator

let range = {
from: 1,
to: 10,
*[Symbol.iterator]() {
for (let i = this.from; i < this.to; i++) {
yield i;
}
},
};
console.log([...range]);
  1. Better Async functionality

Code using promises and callbacks such as

function fetchJson(url) {
return fetch(url)
.then((request) => request.text())
.then((text) => {
return JSON.parse(text);
})
.catch((error) => {
console.log(`ERROR: ${error.stack}`);
});
}

can be written as (with the help of libraries such as co.js) which uses the generator

const fetchJson = co.wrap(function* (url) {
try {
let request = yield fetch(url);
let text = yield request.text();
return JSON.parse(text);
} catch (error) {
console.log(`ERROR: ${error.stack}`);
}
});

There are more applications of generators like

  1. Lazy Evaluation
  2. Memory efficiency
  3. Data streaming

🔸 How symbol works explain its use-case

Answer

🔸 Explain Function Decomposition

Answer

🔸 What is the difference between a parameter and an argument?

Answer

🔸 Does JavaScript pass by value or by reference?

Answer

🔸 What is IIFE and what are the use case of this?

Answer

🔸 What is the reason for wrapping the entire contents of a JavaScript source file in a function that is immediately invoked?

Answer

🔸 Can you offer a use case for the new arrow => function syntax? How does this new syntax differ from other functions?

Answer

🔸 What is Decorators in javascript and When its suitable to use decorators

Answer

🔸 Write a polyfill for bind()

A bind() using ES6 looks something like this

let userInfo = {
name: 'Abhin',
nationality: 'India 🇮🇳',
};
function displayDetails() {
console.log(`${arguments[0]} ${this.name} from ${this.nationality}`);
}
let display = displayDetails.bind(userInfo, 'Hello');
display(); // Hello Abhin from India 🇮🇳

Now the Polyfill for the bind will look something like this

let userInfo = {
name: 'Abhin',
nationality: 'India 🇮🇳',
};
function displayDetails() {
console.log(`${arguments[0]} ${this.name} from ${this.nationality}`);
}
Function.prototype.myBind = function (context, ...arg) {
let fn = this;
return function () {
fn.apply(context, [...arg]);
};
};
let display = displayDetails.myBind(userInfo, 'Hello');
display(); // Hello Abhin from India 🇮🇳

Here the highlighted code is a polyfill for bind which does same things as native bind

🔸 What is polyfill why is that required

Answer

🔸 What is Transpiling in JS

Answer

🔸 Explain Debounce and its applications

The debounce function forces a function to wait a certain amount of time before running again. The function is built to limit the number of times a function is called.

function debounce(func, wait, immediate) {
var timeout; // To keep track of when the event occurred
return function executedFunction() {
var context = this; // window / global context
var args = arguments; // additional arguments it will in array
var later = function () {
timeout = null;
if (!immediate) func.apply(context, args); // looks for condition incase of immediate invocation
};
var callNow = immediate && !timeout;
clearTimeout(timeout); // clear the previous timeout if any
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args); // Incase of immediate function invocation
};
}
var returnedFunction = debounce(function () {
// The function's code
}, 250);
window.addEventListener('resize', returnedFunction);

simplified version of debounce

function debounce(func, wait) {
var timeout;
return function () {
var context = this; // window / global context
var args = arguments; // additional arguments it will in array
clearTimeout(timeout); // clear the previous timeout if any
timeout = setTimeout(later.apply(context, args), wait);
};
}
var returnedFunction = debounce(function () {
// The function's code
}, 250);
window.addEventListener('resize', returnedFunction);

Applications of Debouncing

  • Debouncing can be use to limit the no of API calls in a website
  • It also used to keep the track of user scroll event (Infinity Scroll)
  • Its helpful for to keep track of the window resize

🔸 Explain Throttling and its applications

Throttling enforces a maximum number of times a function can be called over time. For example, “execute this function at most once every 100 milliseconds.”

function debounce(func, wait) {
var timeout;
var flag = true;
return function () {
var context = this; // window / global context
var args = arguments; // additional arguments it will in array
if (flag) {
later.apply(context, args);
flag = false;
}
clearTimeout(timeout); // clear the previous timeout if any
timeout = setTimeout(() => (flag = true), wait);
};
}
var returnedFunction = debounce(function () {
// The function's code
}, 250);
window.addEventListener('resize', returnedFunction);

Applications of Throttling

  • Throttling can be used the action based polling system
  • It can also fit in when there is use cases to hit a button multiple time

🔸 Explain Scope Chain

Answer

🔸 Explain the working of JS Engine

Answer

Need to update an answer from here onwards

🔸 How does hoisting and scoping works

🔸 What is the difference between lexical scoping and dynamic scoping?

🔸 Pure function, Anonymous and Named function

🔸 Explain Function Borrowing and when it occur or can be implement

🔸 What is the definition of a higher-order function?

🔸 Explain the difference between: function Person(){}, var person = Person(), and var person = new Person()?

🔸 Can you explain what .call and .apply do? What's the notable difference between the two?

🔸 Explain Function.prototype.bind

🔸 Arrow function vs Regular function

🔸 Explain Map vs WeakMap

🔸 Explain Set vs WeakSet

🔸 Explain is Execution Context

🔸 What is the difference between Object.assign vs Object.clone

🔸 const vs Object.freeze()

🔸 Null propagation operator / Optional Chaining and Null Coalescing Operator

🔸 What is the term Coercion in javascript

🔸 typeOf vs instanceOf

🔸 What is Temporals Dead Zone (TDZ) when it can occur

🔸 What's the difference between an attribute and a property?

🔸 What are the pros and cons of extending built-in JavaScript objects?

🔸 What is the difference between == and ===?

🔸 Why is it called a Ternary operator, what does the word Ternary indicate?

🔸 What is strict mode? What are some of the advantages/disadvantages of using it?

🔸 What are the different truthy and falsy values in JS

🔸 Explain the difference between mutable and immutable objects

🔸 Can you give an example of generating a string with ES6 Template Literals?

🔸 Can you describe the main difference between the Array.forEach() loop and Array.map() methods and why you would pick one versus the other?

🔸 Explain Modules in Javascript

🔸 Why you might want to create static class members?

🔸 How do you create static class in JS

🔸 What are the differences between variables created using let, var or const?

🔸 Can you give an example for destructuring an object and an array?

🔸 What are the benefits of using spread syntax and how is it different from rest syntax?

🔸 Explain the difference between synchronous and asynchronous functions

🔸 What language constructions do you use for iterating over object properties and array items?

🔸 How can you achieve immutability in your own code?

🔸 What are the pros and cons of immutability?

🔸 How compiler and transpiler are different

🔸 Shallow Copy and Deep Copy

🔸 ES5 vs ES6

🔸 event.stopPropagation vs event.preventDefault

🔸 event.currentTarget.value vs event.target.value

🔸 Explain Event Delegation or DOM Event Delegation

🔸 Describe Event Bubbling and Event Capturing

🔸 What is Polyfill and Shim

🔸 What is short-circuit evaluation in JavaScript?

Last updated on by krishnaUIDev