Javascript Interview Questions and Answers

Please follow & like us :)

three sum algorithm

Read More Here Front-end Interview Prep Guide.

What is Closure in Javascript?

Closure is a feature in javascript where inner function has access to outer function’s variables.

A closure is an inner function that has access to the variables in the outer (enclosing) function’s scope chain. The closure has access to variables declared within function, within outer enclosing function and globally declared variables.

Here is an example:

const outerFn = () => {
  let a = 2;
  const innerFn = () => {
    let b = 4;
    let sum = a + b;
  }
  return innerFn;
}
let globalVar = "xyz";

(function outerFunc(outerArg) {
    let outerVar = 'a';
    
    (function innerFunc(innerArg) {
    let innerVar = 'b';
    
    console.log(
      "innerVar = " + innerVar + "\n" +
      "outerVar = " + outerVar + "\n" +
      "globalVar = " + globalVar);   
    });
});

Closure provides Data Encapsulation, most important feature of object oriented language.

What is Event Bubbling in Javascript?

Event Bubbling is a phase during javascript events.

When an event is fired on an element that has parent elements, the browser check if element selected has an onclick event handler registered on it and run that handler.

Then it moves on to the next immediate ancestor element and does the same thing, then the next one, and so on until it reaches the root <html> element.

Let’s take an example:

<style>
.hidden {
  display: none;
}
.showing {
  display: block;
}
</style>


<button>Play Video</button>
<div class="hidden">
  <video width="320" height="240">
    <source src="http://dglobaltech.com/wp-content/uploads/2021/01/Coding-Interview-Question_-Two-Sum-Target.mp4" type="video/mp4">
    <source src="http://dglobaltech.com/wp-content/uploads/2021/01/Coding-Interview-Question_-Two-Sum-Target.ogg" type="video/ogg">
Your browser does not support the video tag.
  </video>
</div>

<script>
  const playbtn = document.querySelector('button');
  const divBox = document.querySelector('div');
  const video = document.querySelector('video');
  
  playbtn.onclick = function() {
    divBox.setAttribute('class','showing');
  }

  divBox.onclick = function() {
    divBox.setAttribute('class','hidden');
  };

  video.onclick = function() {
    video.play();
  };
</script>

In this example, when you click on video, it fires the event handler attached to that vide component. After that, it will check if there is any event handler attached to the parent component and it will invoke that handler as well. To see it in action checkout this code playground here:

What is Event Capturing in Javascript?

Event Bubbling is a phase during javascript events.

When an event is fired on an element. The browser checks to see if the element’s outer-most ancestor has an onclick event handler on it and runs it if so.

Then it moves on to the next element inside <html> and fire event handler and so on until it reaches the element that was actually selected.

Let’s take an example:


<style>
body * {
    margin: 10px;
    border: 1px solid blue;
  }
</style>
<section class="main">This is Main Section
  <article class="contnt">
    This is Article 
    <div id="outer">This is outer div</div>
  </article>
</section>
<script>
let tagsArr = document.querySelectorAll('*');
for (let i = 0; i < tagsArr.length; i++) {
  tagsArr[i].addEventListener("click", e => alert(`Capturing: ${tagsArr[i].tagName}`), true);
}
</script>

By default, Event Handler is registered for Bubbling Phase. To register event for capturing phase, you need to pass “true” inside the addEventListener call.

To see it in action checkout this code playground here:

What is Event Delegation?

Event Delegation is a concept and advantage of Event bubbling. That means if you want to run same code on number of child elements, instead of attaching Event Listener to each child you can attach listener to parent and bubble it to child element.

<ul id="parent-list">
  <li id="id1">Item 1</li>
  <li id="id2">Item 2</li>
  <li id="id3">Item 3</li>
  <li id="id4">Item 4</li>
  <li id="id5">Item 5</li>
  <li id="id6">Item 6</li>
</ul>
const uiTag = document.getElementById("parent-list");
uiTag.addEventListener("click", (e) => { alert(e.target.id); });

What is Event.preventDefault()?

preventDefault() method tells the user agent to cancel that event. For example, if there is click event on button and then you call method preventDefault() as call back, that click event will get canceled.

<button> Click Me!</button>
const btn = document.getQuerySelector('button');
btn.addEventListener("click", (e) => { e.preventDefault();});

When there is form fields and you have validation rules you can use preventDefault to stop event if it won’t pass the validation.

Let’s take an example here:


  <form>
    <input type="text" id="my-textbox">
  </form>

let myTextbox = document.getElementById('my-textbox');
myTextbox.addEventListener('keypress', checkName, false);

const checkName(evt) => {
  let charCode = evt.charCode;
  if (charCode != 0) {
    if (charCode < 97 || charCode > 122) {
      evt.preventDefault();
      alert("Please use lowercase only.");
    }
  }
}

What is Event.stopPropagation()?

The stopPropagation() method prevents further propagation of the current event in the capturing and bubbling phases.

Here is the Example to test:

Can you explain variable scope in Javascript?

Scope in JavaScript is the area where we have valid access to variables or functions. JavaScript has mainly two scopes – global and local. Any variable declared outside of a function belongs to the global scope, and it can be accessible from anywhere in application. Each function has its own scope which is local scope. Any variable declared within that function is only accessible from that function and any nested functions.

Now ES6 introduces Block level scope. Before when we declare variable within function, it can be accessed anywhere within that function. Instead variable declare with let only accessible within the block they are defined.

For example:

function testvar() {

  for (let i = 0; i < 5; i++) {

    console.log(i);

}

  console.log(i)

}

So here “i” only available within for loop and not outside.

What is difference between Window and Document Object?

window is that global object and It is the root level element in any web page that holds global variables, global functions.

Document is the direct child of the window object. It is aka Document Object Model (DOM) of the html markup you have written.

What is difference between window.onload and document.onload?

window.onload is fired when DOM is ready and all the contents including images, css, scripts, sub-frames, etc. finished loaded. This means everything is loaded.

document.onload is fired when DOM (DOM tree built from markup code within the document)is ready which can be prior to images and other external content is loaded.

Consider the following code snippet. Can you explain what gets logged to the console when the user clicks on “Button 4” and why?

for (var i = 0; i < 5; i++) {
  var btn = document.createElement('button');
  btn.appendChild(document.createTextNode('Button ' + i));
  btn.addEventListener('click', function(){ console.log(i); });
  document.body.appendChild(btn);
}

No matter what button the user clicks the number 5 will always be logged to the console. This is because, at the point that the onclick method is invoked (for any of the buttons), the for loop has already completed and the variable i already has a value of 5.

What is callback?

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.

Here is a quick example:

function greeting(name) {
  alert('Hello ' + name);
}

function processUserInput(callback) {
  var name = prompt('Please enter your name.');
  callback(name);
}

processUserInput(greeting);

Can you explain “this” keyword in Javascript?

The JavaScript this keyword refers to the object it belongs to.

It has different values depending on where it is used:

  • In a method, this refers to the owner object.
  • Alone, this refers to the global object.
  • In a function, this refers to the global object.
  • In a function, in strict mode, this is undefined.
  • In an event, this refers to the element that received the event.
  • Methods like call(), and apply() can refer this to any object.

What is Hoisting in javascript?

Hoisting is JavaScript’s default behavior of moving all declarations to the top of the current scope (to the top of the current script or the current function).

In other words; a variable can be used before it has been declared.

Example:

x = 5; // Assign 5 to x
elem = document.getElementById("demo"); // Find an element
elem.innerHTML = x;                     // Display x in the element
var x; // Declare x

Variables and constants declared with let or const are not hoisted!

What is the difference between undefined and not defined in JavaScript?

In JavaScript, if you try to use a variable which has not been declared, then JavaScript will throw an error variable is not defined.

let p;
console.log(p); 

This will print -->> undefined

If a variable that is neither declared nor defined, when we try to reference such a variable we’d get the result not defined.

console.log(q);  

This will print -->> ReferenceError: q is not defined

Difference between “undefine” and “NULL” Keywords?

When you define a variable but not assign any value. typeof(undefine)=> undefined
Null- manually done. typeof(null)=> object