100 most asked JavaScript Interview Questions and Answers — Part 1

JavaScript (JS) is a lightweight, interpreted, or just-in-time compiled programming language with first-class functions. While it is most well-known as the scripting language for Web pages, many non-browser environments also use it, such as Node.js, Apache CouchDB, and Adobe Acrobat. JavaScript is a prototype-based, multi-paradigm, single-threaded, dynamic language, supporting object-oriented, imperative, and declarative (e.g. functional programming) styles.

We are going to learn JavaScript, by answering the most frequently asked javascript interview questions.

JavaScript Interview Questions and Answers Series

Welcome to the Tech Talks tutorial

If you guys want to practice for JavaScript Interview on mock video interview, please drop me an email at admin@ankitkumar.dev

Questions

Question 1. What is JavaScript?
Question 2. What are the
primitive types in JavaScript?
or
Explain the various JavaScript
data types?
Question 3. What's the difference between
undefined and null in JavaScript?
Question 4. What are the escape characters in JavaScript?
Question 5. What does the
Logical AND (&&) operator do?
Question 6. What does the
Logical OR (||) operator do?
Question 7. What is the fastest way to convert a string to a number?
Question 8. What are the different types of Error Name values in JavaScript?
Question 9. Please explain
Self Invoking Function
Question 10. Explain the difference between function declaration and function expression.
Question 11. What is the DOM?
Question 12. Please explain the difference between
attributes and property?
Question 13. What are
cookies? How will you create, read, and delete a cookie using JavaScript?
Question 14. What is
Event Propagation?
Question 15. What is Event Bubbling?
Question 16. What is Event Capturing?
Question 17. Explain difference between
event.preventDefault() and event.stopPropagation() methods?
Question 18. How to know if the
event.preventDefault() method was used in an element?
Question 19. What is Closure?
Question 20. How many ways can you create an array in JavaScript?
Question 21. How will you empty an array in JavaScript?

Answers

If you feel lazy to read more text, you can watch a video covering all questions here

1. What is JavaScript?

The high-level definition of JavaScript is:

  • JavaScript is a scripting language that enables you to create dynamically updating content, control multimedia, animate images, and pretty much everything else.

2. What are the primitive types in JavaScript?

The data types supported by JavaScript are:

  • String

3. What’s the difference between undefined and null in JavaScript?

undefined is the default value of

  • a variable that has not been assigned a specific value.
console.log(12);
  • a property that does not exist in an object. The JavaScript engine does this for us the assigning undefined values.
let _undefinedVar;
const doNothing = () => {};
const someObj = {
ab : “Tech Talks”,
bc : “With AK”,
cd : “Subscribe, Link in Bio”,
};
console.log(_undefinedVar); // undefined
console.log(doNothing()); // undefined
console.log(someObj[“d”]); // undefined

null is

  • a value that represents no value.
fs.readFile('path/to/file', (err,data) => {
console.log(e); //prints null when no error occurred
if(e){
console.log(e);
}
console.log(data);
}
);

comparing null and undefined

  • When comparing null and undefined we get true when using == and false when using ===.
console.log(null == undefined); // logs true
console.log(null === undefined); // logs false

JavaScript?

  • We use escape characters backslash (\) while working with special characters, such as ampersands (&), apostrophes (‘), double quotes (“ ”), and single quotes (‘ ’).

\b — Backspace

\f — Form feed

\n — Newline

\r — Carriage return

\t — Horizontal tabulator

\v — Vertical tabulator

  • These aren’t in anyway executed in the HTML or JS code.

5. What does the Logical AND operator do?

  • The && or Logical AND operator finds the first false expression in its operands and returns it.
   console.log(false && 10 && []); // false
console.log(" " && true && 10); // 10

6. What does the Logical OR operator do?

  • The || or Logical OR operator finds the first truthy expression in its operands and returns it.
console.log(null || 10 || undefined); //prints 10

function printChannelName(name) {
var n = name || "Tech Talks With AK";
console.log(n);
}

printChannelName(); //prints "Tech Talks With AK"

7. What is the fastest way to convert a string to a number?

According to MDN Documentation the Unary Plus (+) is the fastest way of converting a string to a number because it does not perform any operations on the value if it is already a number.

8. What are the different types of Error Name values in JavaScript?

There are 6 Error Name values in JavaScript.

  • Eval Error — Thrown when coming across an error in eval() (Newer JS releases don’t have it)

9. Please explain Self Invoking Function.

  • Functions that are automatically invoked are termed as Self Invoking Functions.
// A function is defined and then invoked
(function_name () {
return ()
}) ();
  • However, if there is a need to automatically execute a function at the place where it is given and not be called again, then anonymous functions can be used. Such functions have no name. So the name.

10. Explain the difference between function declaration and function expression.

function declaration and function expression can be differentiated on the basis of

  • Definition

Definition

  • A function declared as a separate statement in the main code flow is termed the function declaration.

Strict Mode

  • When a function declaration is within a code block in the Strict mode, it is visible everywhere inside that block but not outside of it.

Time of Use

  • A function expression is created when the execution reaches it. The function expression is usable from that moment onwards.

When to Use

  • Function declaration offers better readability and offers more freedom in organizing the code.

11. What is the DOM?

  • DOM stands for Document Object Model is an interface (API) for HTML and XML documents.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document Object Model</title>
</head>
<body>
<div>
<p>
<span></span>
</p>
<label></label>
<input> // other elements
</div>
</body>
</html>

The graphical representation of the DOM of the code above looks like

The document object in JavaScript represents the DOM.

It provides us many methods that we can use to selecting elements to update element contents and many more.

  • JavaScript can change all the HTML elements in the page

12. Please explain difference between attributes and property?

  • JS DOM objects have properties that are like instance variables for particular elements.

13. What are cookies? How will you create, read, and delete a cookie using JavaScript?

  • A cookie is simply data, usually small, sent from a website and stored on the user’s computer by the web browser used to access the website.

Creating a Cookie:

The most basic way of creating a cookie using JS is to assign a string value to the document.

document.cookie = “key1 = value1; key2 = value2; … ; keyN= valueN; expires = date”;

Reading a Cookie:

  • Reading a cookie using JS is as simple as creating.

Deleting a Cookie:

  • Simply setting the expiration date (expires) to a time that’s already passed.

14. What is Event Propagation?

  • When an event occurs on a DOM element, that event does not entirely occur on that just one element.

It has 3 phases.

  • Capturing Phase – The event starts from the window then goes down to every element until it reaches the target element.

15. What is 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 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.

16. What is 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 javascript code is

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.

17. Explain difference between event.preventDefault() and event.stopPropagation() methods?

  • The event.preventDefault() method prevents the default behavior of an element.

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

  • We can use the event.defaultPrevented property in the event object.

19. What is Closure?

  • Closures are created whenever a variable, defined outside the current scope, is accessed from within some inner scope.

Let’s look at an example

  • Without Closure
function greet(message) {
console.log(message);
}
function greeter(name, number) {
return name + " says Hey!! He has " + number + " subscribers";
}
var message = greeter("Tech Talks", 1026);
greet(message);
  • With Closure
function greeter(name, number) {
var message = name + " says Hey!! He has " + number + " subscribers";
return function greet() {
console.log(message);
};
}
// Generate the closure
var TechTalksGreeter = greeter("Tech Talks", 1026);
// Use the closure
TechTalksGreeter();

20. How many ways can you create an array in JavaScript?

There are three different ways of creating an array in JavaScript, namely:

  • By creating an instance of an array:
var someArray = new Array();
  • By array constructor:
var someArray = new Array(‘value1’, ‘value2’,…, ‘valueN’)
  • By using an array literal:
var someArray = [value1, value2,…., valueN];

21. How will you empty an array in JavaScript?

There are four ways to empty an array in JavaScript

  • By assigning an empty array:
var array1 = [1, 22, 24, 46];
array1 = [ ];
  • By assigning array length to 0:
var array1 = [1, 22, 24, 46];
array1.length=0;
  • By popping the elements of the array:
var array1 = [1, 22, 24, 46];
while(array1.length > 0) {
array1.pop();
}
  • By using the splice array function:
var array1 = [1, 22, 24, 46];
array1.splice(0, array1.length)

Originally posted on AnkitKumar.Dev

If you guys want to practice for JavaScript Interview on mock video interview, please drop me an email at admin@ankitkumar.dev

Further Reading

Also, to be notified about my new articles and stories:

Subscribe to my YouTube Channel

Follow me on Medium, Github, and Twitter.

You can find me on LinkedIn as well.

I am quite active in Dev Community as well and write small topics over there.

Cheers!!! Happy coding!!