JavaScript Interview Questions and Answers
Last updated: Thursday, December 19, 2024
1. What Is JavaScript?
JavaScript is a high-level, interpreted programming language that makes it possible to create interactive web pages and online apps with dynamic functionality. Commonly referred to as the universal language, JavaScript is primarily used by developers for front-end and back-end work.
2. What Are the Different Data Types in JavaScript?
JavaScript has six primitive data types:
- Number
- String
- Boolean
- Null
- Undefined
- Symbol
It also has two compound data types:
- Object
- Array
3. What Is Hoisting in JavaScript?
Hoisting is a JavaScript concept that refers to the process of moving declarations to the top of their scope. This means that variables and functions can be used before they are declared, as long as they are declared before they are used in a function.
For example, the following code will print "Hello, world!"
even though the greeting variable is not declared until after the console.log()
statement.
Hoisting Example:
greeting = "Hello, world!";
function sayHello() {
console.log(greeting);
}
sayHello(); // Logs: "Hello, world!"
4. What Is the Difference Between null and undefined?
null
is an assignment value that represents no value or an empty value, while undefined
is a variable that has been declared but not assigned a value.
Example:
let x;
console.log(x); // Logs: undefined
let y = null;
console.log(y); // Logs: null
5. What Is the Purpose of the “this” Keyword in JavaScript?
The this
keyword refers to the object that is executing the current function or method. It allows access to object properties and methods within the context of that object.
Example:
const person = {
name: "John",
age: 30,
greet() {
console.log(`Hello, my name is ${this.name}`);
},
};
person.greet(); // Logs: "Hello, my name is John"
6. What Is the Difference Between “var” and “let” Keywords in JavaScript?
The var
and let
keywords are both used to declare variables in JavaScript. However, there are some key differences between the two keywords.
The var
keyword declares a global variable, which means that the variable can be accessed from anywhere in the code. The let
keyword declares a local variable, which means that the variable can only be accessed within the block of code where it is declared.
7. What Are Closures in JavaScript?
Closures (closureFn
) are functions that have access to variables from an outer function even after the outer function has finished executing. They “remember” the environment in which they were created.
Closure Example:
function outerFunction() {
const treasure = 'hidden treasure';
function innerFunction() {
console.log(treasure);
}
return innerFunction;
}
const closureFn = outerFunction();
closureFn(); // Output: hidden treasure
In this example:
- The
outerFunction
creates a variabletreasure
and a functioninnerFunction
. - The
innerFunction
has access to thetreasure
variable even afterouterFunction
has finished executing. - The
closureFn
function is returned fromouterFunction
and can still access thetreasure
variable.
8. What Is Implicit Type Coercion in JavaScript?
Implicit type coercion is a JavaScript concept that refers to the automatic conversion of a value from one type to another. In JavaScript, this conversion follows a priority order that typically begins with strings, then numbers, and finally booleans. If you try to add a string to a number, JavaScript will implicitly coerce the number to a string before performing the addition operation because strings have the highest priority in type coercion.
For example, when you combine the number 5
with the string '10'
using the addition operator, the result is the string '510'
. This occurs because JavaScript will implicitly convert the number 5
to a string following the priority of coercion, and then concatenate it to the string '10'
.
Implicit Type Coercion Example:
console.log(5 + '10'); // Output: '510'
9. Explain the Concept of Prototypes in JavaScript.
Prototypes are a mechanism used by JavaScript objects for inheritance. Every JavaScript object has a prototype, which provides properties and methods that can be accessed by that object.
Example:
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
console.log(`Hello, my name is ${this.name}`);
}
const person = new Person("John");
person.greet(); // Logs: "Hello, my name is John"
In this example:
- The
Person
function is a constructor function that creates objects with aname
property. - The
greet
method is added to thePerson.prototype
object, which is shared by all instances of thePerson
constructor. - The
person
object is created using thePerson
constructor and has aname
property.
10. What are Event Bubbling and Capturing in JavaScript?
Event Bubbling and Event Capturing are concepts used to understand how events propagate through DOM elements. Event Bubbling propagates events from the target element upwards to its parent elements, while Event Capturing propagates events from parent elements down to the target element.
Example:
<div id="parent">
<div id="child">Child</div>
</div>
const parent = document.getElementById('parent');
const child = document.getElementById('child');
parent.addEventListener('click', () => {
console.log('Parent element triggered');
}, true);
child.addEventListener('click', () => {
console.log('Child element triggered');
}, true);
In this example:
parent
andchild
represent DOM elements.- The
parent
element has aclick
event listener withtrue
, indicating Event Capturing. - The
child
element also has aclick
event listener withtrue
, indicating Event Capturing. - When a user clicks on the
child
element, the console logs:Child element triggered Parent element triggered
This demonstrates the Event Capturing process.
11. What is "use strict" in JavaScript?
use strict
is a feature in JavaScript that enforces strict mode, making it easier to catch errors and write secure, reliable code. It prevents the use of certain error-prone practices and helps developers identify common mistakes.
Example:
'use strict';
x = 3.14; // Error: x is not declared
In this example, use strict
is enabled, and since the variable x
is not declared, an error is thrown. Without use strict
, no error would occur, and x
would become a global variable implicitly.
12. What Is the Difference Between "async" and "defer" Scripts in JavaScript?
async
and defer
scripts are used to specify how JavaScript files should be added to an HTML page. They determine how the script is loaded and the order in which it is executed. The difference lies in their execution order and their placement during the page loading process. async
scripts are loaded during the page loading process, while defer
scripts are not loaded during the page loading process.
Key Differences:
async
scripts are loaded during page loading, whiledefer
scripts are not loaded during the page loading process.async
scripts are executed during page loading, whiledefer
scripts are executed after page loading.async
scripts don't wait for loading order during page load, whiledefer
scripts maintain the loading order during the page loading process.
13. What are JavaScript cookies?
JavaScript cookies are small data files stored by a browser. Websites set them to store information about you. An example would be the cookie set when you choose “Remember Me” when logging into a website. The site will store a cookie in your browser as a token to identify you without requiring you to log in again.
14. What is Local Storage in JavaScript?
Local Storage is a web storage object that allows you to store key/value pairs in a web browser. It is similar to cookies but has a larger storage capacity and is more secure. Local Storage data is stored without an expiration date and will persist even after the browser is closed. It is accessible across different browser sessions and tabs.
15. What is the Event Loop in JavaScript?
The Event Loop is a mechanism in JavaScript that allows the runtime environment to handle asynchronous operations. It continuously checks the call stack and the callback queue to determine if there are any tasks that need to be executed. The Event Loop ensures that JavaScript remains single-threaded and non-blocking, allowing it to handle multiple tasks concurrently. This is essential for handling asynchronous operations like network requests, timers, and user interactions.