20 JavaScript Interview Question






Hey amazing people, in this post i'll be covering many JavaScript question that Interviewer asks.

So let's start..

Q1. What does the && operator do?

The && or Logical AND operator finds the first falsy expression in its operands and returns it and if it does not find any falsy expression it returns the last expression. It employs short-circuiting to prevent unnecessary work. You can use this in the catch block when closing database connection.

console.log(false && 1 && []); //logs false
   console.log(" " && true && 5); //logs 5

Using if statements.

const router: Router = Router();

  router.get('/endpoint', (req: Request, res: Response) => {
     let conMobile: PoolConnection;
     try {
        //do some db operations
     } catch (e) {
     if (conMobile) {
      conMobile.release();
     }
  }
});

Using && operator.

const router: Router = Router();

router.get('/endpoint', (req: Request, res: Response) => {
  let conMobile: PoolConnection;
  try {
     //do some db operations
  } catch (e) {
    conMobile && conMobile.release()
  }
});

Q2. What's Event Bubbling?

When an event occurs on a DOM element, that event does not entirely occur on that just one element. In the Bubbling Phase, the event bubbles up or it goes to its parent, to its grandparents, to its grandparent's parent until it reaches all the way to the window.

If we have an example markup like this.

 <div class="grandparent">
    <div class="parent">
      <div class="child">1</div>
    </div>
  </div>

And our JavaScript code.

function addEvent(el, event, callback, isCapture = false) {
  if (!el || !event || !callback || typeof callback !== 'function') return;
  if (typeof el === 'string') {
    el = document.querySelector(el);
  };
  el.addEventListener(event, callback, isCapture);
}

addEvent(document, 'DOMContentLoaded', () => {
  const child = document.querySelector('.child');
  const parent = document.querySelector('.parent');
  const grandparent = document.querySelector('.grandparent');

  addEvent(child, 'click', function (e) {
    console.log('child');
  });

  addEvent(parent, 'click', function (e) {
    console.log('parent');
  });

  addEvent(grandparent, 'click', function (e) {
    console.log('grandparent');
  });

  addEvent(document, 'click', function (e) {
    console.log('document');
  });

  addEvent('html', 'click', function (e) {
    console.log('html');
  })

  addEvent(window, 'click', function (e) {
    console.log('window');
  })

});

The addEventListener method has a third optional parameter useCapture with a default value of false the event will occur in the Bubbling phase if true the event will occur in the Capturing Phase. If we click on the child element it logs child,parent,grandparenthtmldocument and window respectively on the console. This is Event Bubbling.

Q3. What's Event Capturing?

When an event occurs on a DOM element, that event does not entirely occur on that just one element. In Capturing Phase, the event starts from the window all the way down to the element that triggered the event.

If we have an example markup like this.

 <div class="grandparent">
    <div class="parent">
      <div class="child">1</div>
    </div>
  </div>

And our JavaScript code.

function addEvent(el, event, callback, isCapture = false) {
  if (!el || !event || !callback || typeof callback !== 'function') return;
  if (typeof el === 'string') {
    el = document.querySelector(el);
  };
  el.addEventListener(event, callback, isCapture);
}

addEvent(document, 'DOMContentLoaded', () => {
  const child = document.querySelector('.child');
  const parent = document.querySelector('.parent');
  const grandparent = document.querySelector('.grandparent');

  addEvent(child, 'click', function (e) {
    console.log('child');
  }, true);

  addEvent(parent, 'click', function (e) {
    console.log('parent');
  }, true);

  addEvent(grandparent, 'click', function (e) {
    console.log('grandparent');
  }, true);

  addEvent(document, 'click', function (e) {
    console.log('document');
  }, true);

  addEvent('html', 'click', function (e) {
    console.log('html');
  }, true)

  addEvent(window, 'click', function (e) {
    console.log('window');
  }, true)

});

The addEventListener method has a third optional parameter useCapture with a default value of false the event will occur in the Bubbling phase if true the event will occur in the Capturing Phase. If we click on the child element it logs window,document,htmlgrandparent and parent and child respectively on the console. This is Event Capturing.

Difference b/w bubbling and caputiring, With bubbling, the event is first captured and handled by the innermost element and then propagated to outer elements. With capturing, the event is first captured by the outermost element and propagated to the inner elements. ... listener: a function that will trigger when the event occur.

Q4. What's the difference between event.preventDefault() and event.stopPropagation() methods?

The event.preventDefault() method prevents the default behavior of an element. If used in a form element it prevents it from submitting. If used in an anchor element it prevents it from navigating. If used in a contextmenu it prevents it from showing or displaying. While the event.stopPropagation() method stops the propogation of an event or it stops the event from occurring in the bubbling or capturing phase.

Q5. How to know if the event.preventDefault() method was used in an element?

We can use the event.defaultPrevented property in the event object. It returns a boolean indicating if the event.preventDefault() was called in a particular element.

Q6. What are the falsy values in JavaScript?

 const falsyValues = ['', 0, null, undefined, NaN, false];

falsy values are values that when converted to boolean becomes false.

Q7. How to check if a value is falsy?

Use the Boolean function or the Double NOT operator !!

Q8. What does "use strict" do?

"use strict" is a ES5 feature in JavaScript that makes our code in Strict Mode in functions or entire scripts. Strict Mode helps us avoid bugs early on in our code and adds restrictions to it.

Restrictions that Strict Mode gives us.

Assigning or Accessing a variable that is not declared.

function returnY(){
    "use strict";
    y = 123;
    return y;
 }

Assigning a value to a read-only or non-writable global variable;

"use strict";
   var NaN = NaN;
   var undefined = undefined;
   var Infinity = "and beyond";

Deleting an undeletable property.

"use strict";
   const obj = {};

   Object.defineProperty(obj, 'x', {
      value : '1'
   });  

   delete obj.x;
Duplicate parameter names.
   "use strict";

   function someFunc(a, b, b, c){

   }

Creating variables with the use of the eval function.

"use strict";

 eval("var x = 1;");

 console.log(x); //Throws a Reference Error x is not defined

The default value of this will be undefined.
  "use strict";

  function showMeThis(){
    return this;
  }

  showMeThis(); //returns undefined

There are more restriction in STRICT MODE than this.

Q9. What is ECMAScript?

ECMAScript is a standard for making scripting languages which means that JavaScript follows the specification changes in ECMAScript standard because it is the blueprint of JavaScript.

Q10. Why does b in this code become a global variable when you call this function?

function myFunc() {
  let a = b = 0;
}

myFunc();

The reason for this is that assignment operator or = has right-to-left associativity or evaluation. What this means is that when multiple assignment operators appear in a single expression they evaluated from right to left. So our code becomes likes this.

function myFunc() {
  let a = (b = 0);
}

myFunc();

First, the expression b = 0 evaluated and in this example b is not declared. So, The JS Engine makes a global variable b outside this function after that the return value of the expression b = 0 would be 0 and it's assigned to the new local variable a with a let keyword.

We can solve this problem by declaring the variables first before assigning them with value.

function myFunc() {
  let a,b;
  a = b = 0;
}
myFunc();

Q11. What is a Callback function?

A Callback function is a function that is gonna get called at a later point in time.

const btnAdd = document.getElementById('btnAdd');

btnAdd.addEventListener('click', function clickCallback(e) {
    // do something useless
});

In this example, we wait for the click event in the element with an id of btnAdd, if it is clicked, the clickCallback function is executed. A Callback function adds some functionality to some data or event. The reduce, filter and map methods in Array expects a callback as a parameter. A good analogy for a callback is when you call someone and if they don't answer you leave a message and you expect them to callback. The act of calling someone or leaving a message is the event or data and the callback is the action that you expect to occur later.

Q12. What are Wrapper Objects?

Primitive Values like string,number and boolean with the exception of null and undefined have properties and methods even though they are not objects.

let name = "DIVINE";

console.log(typeof name); // logs  "string"
console.log(name.toUpperCase()); // logs  "DIVINE"

name is a primitive string value that has no properties and methods but in this example we are calling a toUpperCase() method which does not throw an error but returns DIVINE.

The reason for this is that the primitive value is temporarily converted or coerce to an object so the name variable behaves like an object. Every primitive except null and undefined have Wrapper Objects. The Wrapper Objects are String,Number,Boolean,Symbol and BigInt. In this case, the name.toUpperCase() invocation, the back scenes will look like this.

console.log(new String(name).toUpperCase()); // logs  "DIVINE"

The newly created object is immediately discarded after we finished accessing a property or calling a method.

Q13. What is AJAX?

AJAX stands for Asynchronous JavaScript and XML. It is a group of related technologies used to display data asynchronously. What this means is that we can send data to the server and get data from the server without reloading the web page.

Technologies use for AJAX.

  • HTML - web page structure
  • CSS - the styling for the webpage
  • JavaScript - the behaviour of the webpage and updates to the DOM
  • XMLHttpRequest API - used to send and retrieve data from the server
  • PHP,Python,Nodejs - Some Server-Side language

Q14. What are the ways of making objects in JavaScript?

Using Object Literal.

const o = {
   name: "Rahul",
   greeting() {
      return `Hey, this is ${this.name}`;
   }
  };
  o.greeting(); //returns "Hey, this is Rahul"

Using Constructor Functions.

function Person(name) {
   this.name = name;
}

Person.prototype.greeting = function () {
   return `Hey, this is ${this.name}`;
}

const mark = new Person("Rahul");

mark.greeting(); //returns "Hey, this is Rahul"

Using Object.create method.

const n = {
   greeting() {
      return `Hey, this is ${this.name}`;
   }
};

const o = Object.create(n); // sets the prototype of "o" to be "n"

o.name = "Rahul";

console.log(o.greeting()); // logs "Hi, this is Rahul"

Q15. What's the difference between Object.seal and Object.freeze methods?

The difference between these two methods is that when we use the Object.freeze method to an object, that object's properties are immutable meaning we can't change or edit the values of those properties. While in the Object.seal method we can change those existing properties.

Q16. What is memoization and what's the use it?

Memoization is a process of building a function that is capable of remembering it's previously computed results or values. The use of making a memoization function is that we avoid the computation of that function if it was already performed in the last calculations with the same arguments. This saves time but has a downside that we will consume more memory for saving the previous results.

Q17. Implement a memoization helper function.

function memoize(fn) {
  const cache = {};
  return function (param) {
    if (cache[param]) {
      console.log('cached');
      return cache[param];
    } else {
      let result = fn(param);
      cache[param] = result;
      console.log(`not cached`);
      return result;
    }
  }
}

const toUpper = (str ="")=> str.toUpperCase();

const toUpperMemoized = memoize(toUpper);

toUpperMemoized("abcdef");
toUpperMemoized("abcdef");

This memoize helper function only works on a function that accepts one argument. We need to make a memoize helper function that accepts multiple arguments.

const slice = Array.prototype.slice;
function memoize(fn) {
  const cache = {};
  return (...args) => {
    const params = slice.call(args);
    console.log(params);
    if (cache[params]) {
      console.log('cached');
      return cache[params];
    } else {
      let result = fn(...args);
      cache[params] = result;
      console.log(`not cached`);
      return result;
    }
  }
}
const makeFullName = (fName, lName) => `${fName} ${lName}`;
const reduceAdd = (numbers, startingValue = 0) => numbers.reduce((total, cur) => total + cur, startingValue);

const memoizedMakeFullName = memoize(makeFullName);
const memoizedReduceAdd = memoize(reduceAdd);

memoizedMakeFullName("Marko", "Polo");
memoizedMakeFullName("Marko", "Polo");

memoizedReduceAdd([1, 2, 3, 4, 5], 5);
memoizedReduceAdd([1, 2, 3, 4, 5], 5);

Q18. What is the prototype of an object?

A prototype in simplest terms is a blueprint of an object. It is used as a fallback for properties and methods if it does exist in the current object. It's the way to share properties and functionality between objects. It's the core concept around JavaScript's Prototypal Inheritance.

  const o = {};
  console.log(o.toString()); // logs [object Object]

Even though the o.toString method does not exist in the o object it does not throw an error instead returns a string [object Object]. When a property does not exist in the object it looks into its prototype and if it still does not exist it looks into the prototype's prototype and so on until it finds a property with the same in the Prototype Chain. The end of the Prototype Chain is the Object.prototype.

   console.log(o.toString === Object.prototype.toString); // logs true
   // which means we we're looking up the Prototype Chain and it reached 
   // the Object.prototype and used the "toString" method.

Q19. What is the use Function.prototype.apply method?

The apply invokes a function specifying the this or the "owner" object of that function on that time of invocation.

const details = {
  message: 'Hello World!'
};

function getMessage(){
  return this.message;
}

getMessage.apply(details); // returns 'Hello World!'

This procedure works like Function.prototype.call the only difference is how we pass arguments. In apply we pass arguments as an array.

const person = {
  name: "Rahul"
};

function greeting(greetingMessage) {
  return `${greetingMessage} ${this.name}`;
}

greeting.apply(person, ['Hello']); // returns "Hello Rahul !"

Q20. What is the use Function.prototype.call method?

The call invokes a function specifying the this or the "owner" object of that function on that time of invocation.

const details = {
  message: 'Hello World!'
};

function getMessage(){
  return this.message;
}

getMessage.call(details); // returns 'Hello World!'

This procedure works like Function.prototype.apply the only difference is how we pass arguments. In call we pass directly the arguments separating them with a comma , for every argument.

const person = {
  name: "Rahul"
};

function greeting(greetingMessage) {
  return `${greetingMessage} ${this.name}`;
}

greeting.call(person, 'Hello'); // returns "Hello Rahul !"

Basically, they differ on how they handle function arguments.

The apply() method is identical to call(), except apply() requires an array as the second parameter. The array represents the arguments for the target method.

// assuming you have f
function f(message) { ... }
f.call(receiver, "test");
f.apply(receiver, ["test"]);

Source :-

  • StackOverFlow
  • Medium
  • Javapoint
  • Guru99

Thanks For Reading 😀 You can subscribe to my Newsletter too. (Head On To The TOP)

Comments

Popular posts from this blog

8 Best tools for remote workers

5 Common and Big mistakes freelancer make and can avoid it

This one line CSS can center object easily : Putting end to your Google search