Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
0 views

Javascript Interview Questions and Answers

The document provides a comprehensive overview of JavaScript, covering its definition, data types, variable declarations, and key concepts such as functions, callbacks, promises, and the DOM. It also explains advanced topics like closures, event handling, and the differences between various JavaScript features. The content is structured as a Q&A format, making it suitable for interview preparation.

Uploaded by

vishalaher287
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Javascript Interview Questions and Answers

The document provides a comprehensive overview of JavaScript, covering its definition, data types, variable declarations, and key concepts such as functions, callbacks, promises, and the DOM. It also explains advanced topics like closures, event handling, and the differences between various JavaScript features. The content is structured as a Q&A format, making it suitable for interview preparation.

Uploaded by

vishalaher287
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

1. What is JavaScript?

Answer:
JavaScript is a high-level, interpreted programming language that allows
you to create dynamic and interactive web pages. It's the core
technology behind web development, alongside HTML and CSS.
JavaScript is used for client-side scripting (in the browser) and can also
be used on the server-side with environments like Node.js. JavaScript
enables the creation of things like interactive forms, animations, and
games within websites.
2. What are the data types in JavaScript?
Answer:
JavaScript has several data types, categorized into two types:
o Primitive types: These are the most basic types of data. They
include:
▪ String: Represents text (e.g., "Hello").
▪ Number: Represents numbers (e.g., 100, 3.14).
▪ Boolean: Represents true or false.
▪ Undefined: A variable that has been declared but not
assigned a value.
▪ Null: Represents an intentional absence of value.
▪ Symbol: A unique identifier used mainly for object
properties in ES6.
o Non-primitive types:
▪ Object: Represents collections of key-value pairs, like arrays,
functions, and custom objects.
3. What is the difference between var, let, and const?
Answer:
o var is the traditional way of declaring variables in JavaScript. It is
function-scoped, meaning it's accessible anywhere within the
function it is declared. However, it can be redeclared, which can
sometimes lead to unexpected behavior.
o let is block-scoped, meaning the variable is only available within
the block ({}) where it's defined. It cannot be redeclared within the
same scope, which makes it safer to use.
o const is also block-scoped like let, but once a variable is assigned a
value using const, it cannot be reassigned. This is typically used for
values that should not change after they are assigned.
4. What is undefined vs null?
Answer:
o undefined is the default value of uninitialized variables. If a
variable is declared but not assigned any value, JavaScript
automatically assigns it undefined.
o null is an assigned value that represents the intentional absence of
any object value. It's typically used when you want to explicitly
indicate that a variable should have no value.
5. What are JavaScript’s falsy values?
Answer:
Falsy values in JavaScript are values that are considered false when
encountered in boolean contexts (like in if conditions). The falsy values in
JavaScript are:
o false
o 0
o "" (empty string)
o null
o undefined
o NaN (Not-a-Number)
6. What is a function in JavaScript?
Answer:
A function in JavaScript is a block of code designed to perform a
particular task. Functions can take inputs (called parameters) and can
return an output (called a return value). Functions allow you to reuse
code multiple times. Here's an example:
javascript
Copy code
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("John"); // Output: Hello, John!
7. What is the difference between == and ===?
Answer:
o == is the loose equality operator. It checks for equality of values
but does not consider data types. It performs type coercion,
meaning it converts the values to the same type before
comparison.
javascript
Copy code
console.log(5 == '5'); // true because it converts the string '5' to the number 5
o === is the strict equality operator. It checks both the value and the
data type, ensuring that they are both the same.
javascript
Copy code
console.log(5 === '5'); // false because 5 is a number and '5' is a string
8. What is a callback function?
Answer:
A callback function is a function that is passed as an argument to another
function. The passed function is then invoked (called back) inside the
outer function. This is commonly used for handling asynchronous tasks
(e.g., reading files, making API calls). Here's an example:
javascript
Copy code
function fetchData(callback) {
// Simulate data fetching
let data = "Some fetched data";
callback(data);
}

function processData(data) {
console.log("Processing " + data);
}

fetchData(processData); // Output: Processing Some fetched data


9. What is an arrow function?
Answer:
Arrow functions provide a shorter syntax for writing functions. They are
introduced in ES6 and are more concise than traditional functions. They
also behave differently with respect to the this keyword, making them
useful for certain cases. Example:
javascript
Copy code
const add = (a, b) => a + b;
console.log(add(5, 3)); // Output: 8
Arrow functions are also often used for anonymous functions and callbacks.
10.What is the DOM?
Answer:
The DOM (Document Object Model) is an interface that allows programs
(like JavaScript) to interact with HTML or XML documents. It represents
the document as a tree of nodes, with each node representing a part of
the page (e.g., elements, attributes, text). JavaScript can manipulate the
DOM to change content, structure, and styles of web pages dynamically.
Example:
javascript
Copy code
document.getElementById("myButton").onclick = function() {
alert("Button clicked!");
}
11.What is event bubbling and event capturing?
Answer:
o Event Bubbling: In this phase, the event starts from the innermost
target element and bubbles up to the outer elements. This is the
default behavior.
o Event Capturing: In this phase, the event starts from the
outermost element and is captured by inner elements. You can
enable capturing by passing an additional argument when adding
the event listener:
javascript
Copy code
element.addEventListener("click", callback, true); // true enables capturing
12.What is the difference between null and NaN?
Answer:
o null represents the intentional absence of a value. It's often used
to indicate that a variable should not hold any value.
o NaN stands for "Not-a-Number." It is returned when an operation
or function cannot produce a valid number, such as dividing a
string by a number or performing an invalid mathematical
operation.
13.What are JavaScript closures?
Answer:
A closure is a function that has access to its own scope, the scope in
which it was defined, and the global scope. Closures are created when a
function is defined inside another function and the inner function refers
to variables from the outer function. Example:
javascript
Copy code
function outer() {
let count = 0;
return function inner() {
count++;
console.log(count);
};
}
const counter = outer();
counter(); // Output: 1
counter(); // Output: 2
14.What is the difference between let and var?
Answer:
o let is block-scoped, meaning it's only accessible within the block {}
where it is defined. It cannot be redeclared in the same scope.
o var is function-scoped, meaning it is accessible anywhere within
the function it is declared, even if it is declared in a block.
15.What is the purpose of this in JavaScript?
Answer:
The value of this depends on how a function is called. It refers to the
object that is currently executing the function. In the global context, this
refers to the global object (window in the browser). In a method, this
refers to the object that owns the method. Example:
javascript
Copy code
const person = {
name: "John",
greet: function() {
console.log(this.name);
}
};
person.greet(); // Output: John

I’ll continue with more questions in the next response. Let me know if you'd
like me to go ahead!
4o mini
You said:
try to give at least 40 questions which asked mosted in the interview
ChatGPT said:
ChatGPT
Certainly! Here's a continuation with 40 more JavaScript interview questions
and detailed answers, covering a range of important topics. These are
commonly asked in interviews for freshers.

Intermediate JavaScript Questions (21-40)


21.What are template literals in JavaScript?
Answer:
Template literals, introduced in ES6, allow you to embed expressions
inside string literals using ${} syntax. They are defined using backticks (`)
instead of single or double quotes. This makes string concatenation
easier and more readable.
Example:
javascript
Copy code
let name = "John";
let greeting = `Hello, ${name}!`; // Output: Hello, John!
22.What are JavaScript objects?
Answer:
JavaScript objects are collections of key-value pairs. The key is a string (or
symbol) and the value can be any valid JavaScript data type (string,
number, array, function, etc.). Objects are used to represent real-world
entities.
Example:
javascript
Copy code
const person = {
name: "Alice",
age: 25,
greet: function() { console.log("Hello!"); }
};
23.What is the difference between Object.freeze() and Object.seal()?
Answer:
• Object.freeze() makes an object immutable, meaning you cannot change
its properties or add new ones.
• Object.seal() prevents adding or removing properties but still allows
modification of existing properties.
24.What is the purpose of setTimeout() and setInterval()?
Answer:
• setTimeout() executes a function after a specified delay (in milliseconds).
• setInterval() executes a function repeatedly at a specified interval.
Example:
javascript
Copy code
setTimeout(() => console.log("Hello after 2 seconds"), 2000);
25.What is an event listener in JavaScript?
Answer:
An event listener is a function that waits for an event to occur, such as a
click, keypress, or mouse movement. It’s used to handle interactions on
web pages.
Example:
javascript
Copy code
document.getElementById("myButton").addEventListener("click", () => {
alert("Button clicked!");
});
26.What is the difference between localStorage and sessionStorage?
Answer:
• localStorage stores data with no expiration time. Data persists even
when the browser is closed and reopened.
• sessionStorage stores data for the duration of the page session, meaning
the data is lost when the browser is closed.
27.What is the purpose of window.onload?
Answer:
window.onload is an event that is triggered when the entire page,
including all resources (images, scripts, etc.), has fully loaded. It's often
used to run scripts after all page content has been rendered.
28.What is a promise in JavaScript?
Answer:
A Promise is an object that represents the eventual completion (or
failure) of an asynchronous operation and its resulting value. Promises
have three states:
• Pending: Initial state, neither fulfilled nor rejected.
• Resolved: The operation was successful.
• Rejected: The operation failed.
Example:
javascript
Copy code
let myPromise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Operation was successful!");
} else {
reject("Operation failed!");
}
});
29.What is async and await in JavaScript?
Answer:
• async is used to declare a function that returns a Promise.
• await is used inside an async function to pause execution until the
Promise is resolved.
Example:
javascript
Copy code
async function fetchData() {
let response = await fetch("https://api.example.com");
let data = await response.json();
console.log(data);
}
30.What is a JavaScript closure?
Answer:
A closure is a function that remembers its lexical scope even when the
function is executed outside of that scope. It gives functions access to
variables from their outer function after the outer function has finished
executing.
Example:
javascript
Copy code
function outer() {
let count = 0;
return function inner() {
count++;
console.log(count);
};
}
const counter = outer();
counter(); // Output: 1
counter(); // Output: 2
31.What is destructuring in JavaScript?
Answer:
Destructuring allows you to unpack values from arrays or properties
from objects into distinct variables. This makes the code cleaner and
more readable.
Example:
javascript
Copy code
const person = { name: "John", age: 25 };
const { name, age } = person;
console.log(name, age); // Output: John 25
32.What are higher-order functions in JavaScript?
Answer:
A higher-order function is a function that takes another function as an
argument or returns a function as its result. Common examples include
map(), filter(), and reduce().
33.What is the difference between forEach() and map()?
Answer:
• forEach() iterates over an array and executes a given function for each
element but returns undefined.
• map() creates a new array populated with the results of calling a
provided function on every element.
34.What is bind() in JavaScript?
Answer:
The bind() method creates a new function that, when called, has its this
value set to the provided value. It's often used to ensure that a function
uses the correct this.
Example:
javascript
Copy code
const person = {
name: "Alice",
greet: function() {
console.log(`Hello, ${this.name}`);
}
};
const greetAlice = person.greet.bind(person);
greetAlice(); // Output: Hello, Alice
35.What is the typeof operator?
Answer:
typeof is used to check the data type of a variable. It returns a string
indicating the type of the operand.
Example:
javascript
Copy code
console.log(typeof "Hello"); // Output: string
console.log(typeof 123); // Output: number
36.What is the spread operator?
Answer:
The spread operator (...) is used to unpack elements from an array or
object. It can be used to copy arrays/objects, merge them, or pass
arguments to a function.
Example:
javascript
Copy code
let arr = [1, 2, 3];
let newArr = [...arr, 4, 5];
console.log(newArr); // Output: [1, 2, 3, 4, 5]
37.What is the rest parameter?
Answer:
The rest parameter syntax allows a function to accept an indefinite
number of arguments as an array. It's represented by ... followed by a
name.
Example:
javascript
Copy code
function sum(...numbers) {
return numbers.reduce((acc, num) => acc + num, 0);
}
console.log(sum(1, 2, 3)); // Output: 6
38.What is the Array.prototype.slice() method?
Answer:
The slice() method is used to return a shallow copy of a portion of an
array into a new array object. It does not modify the original array.
Example:
javascript
Copy code
let arr = [1, 2, 3, 4, 5];
let newArr = arr.slice(1, 4);
console.log(newArr); // Output: [2, 3, 4]
39.What are set and map in JavaScript?
Answer:
• Set is a collection of unique values. It ensures that no duplicate values
are stored.
• Map is a collection of key-value pairs where the keys can be any data
type (including objects) and the keys are unique.
40.What are Promise.all() and Promise.race()?
Answer:
• Promise.all() waits for all the promises to resolve and returns an array of
results. If one promise rejects, it rejects the entire operation.
• Promise.race() returns as soon as one of the promises resolves or
rejects, whichever happens first.

This should give you a good foundation in JavaScript! If you want further details
on any question or need help with more concepts, feel free to ask!
4o mini
You said:
give 10 more questions
ChatGPT said:
ChatGPT
Sure! Here are 10 more JavaScript interview questions with detailed answers
that are frequently asked during interviews.

Advanced JavaScript Questions (41-50)


41.What is the difference between synchronous and asynchronous
programming in JavaScript?
Answer:
• Synchronous programming executes tasks one after the other. Each task
waits for the previous one to complete before it starts. This can block the
execution of the program if the task takes time (e.g., reading a large file
or making an API call).
• Asynchronous programming allows tasks to run in parallel. This means
the program doesn't have to wait for a task to finish before continuing
with other tasks. It is used in JavaScript for non-blocking I/O operations
(e.g., setTimeout(), Promises, async/await).
42.What are JavaScript Modules?
Answer:
JavaScript modules allow you to break your code into smaller, reusable
pieces. ES6 introduced the import and export syntax to manage
modules.
• export is used to make variables, functions, or objects accessible outside
the module.
• import is used to include those exports into another file.
Example:
javascript
Copy code
// In file1.js
export const name = "John";

// In file2.js
import { name } from './file1.js';
console.log(name); // Output: John
43.What is the event loop in JavaScript?
Answer:
The event loop is the mechanism that handles asynchronous callbacks in
JavaScript. It constantly checks the message queue for tasks that are
ready to be executed, and it runs them in the order they are added to
the queue. When the call stack is empty, the event loop takes the next
task from the message queue and pushes it onto the call stack. This
allows non-blocking behavior in JavaScript.
44.What are setImmediate() and process.nextTick() in Node.js?
Answer:
These are Node.js-specific functions that schedule callbacks:
• setImmediate() is used to schedule a callback to be executed in the next
iteration of the event loop, after the current event loop phase.
• process.nextTick() schedules a callback to be executed immediately after
the current operation completes, before any other I/O tasks.
Note: process.nextTick() has higher priority than setImmediate(), meaning it
runs before any other I/O tasks or timers.
45.What are JavaScript's apply(), call(), and bind() methods?
Answer:
These methods are used to explicitly set the this value in a function:
• call() immediately invokes the function with the given this value and
arguments passed individually.
• apply() works like call(), but arguments are passed as an array.
• bind() returns a new function that, when called, has the specified this
value and initial arguments.
Example:
javascript
Copy code
function greet(name) {
console.log(`${this.message} ${name}`);
}

const obj = { message: "Hello" };


greet.call(obj, "John"); // Output: Hello John
greet.apply(obj, ["John"]); // Output: Hello John
const boundGreet = greet.bind(obj);
boundGreet("John"); // Output: Hello John
46.What is the delete operator in JavaScript?
Answer:
The delete operator is used to remove a property from an object or an
element from an array. It does not affect the array length or reindex the
array. For objects, it removes the property completely, and for arrays, it
simply sets the element to undefined.
Example:
javascript
Copy code
let person = { name: "John", age: 30 };
delete person.age; // Removes the 'age' property from the object
console.log(person); // Output: { name: "John" }

let arr = [1, 2, 3];


delete arr[1]; // Removes the element at index 1, but does not reindex the
array
console.log(arr); // Output: [1, undefined, 3]
47.What is Hoisting in JavaScript?
Answer:
Hoisting refers to JavaScript’s behavior of moving variable and function
declarations to the top of their scope during compilation. However, only
the declarations are hoisted, not the initializations.
Example:
javascript
Copy code
console.log(myVar); // undefined
var myVar = 5;
console.log(myVar); // 5
In the example above, the declaration var myVar; is hoisted to the top, but the
initialization myVar = 5 stays in place.
48.What is the difference between setTimeout() and setInterval()?
Answer:
• setTimeout() is used to execute a function once after a specified delay
(in milliseconds).
• setInterval() is used to repeatedly execute a function with a fixed delay
between each call.
Example:
javascript
Copy code
setTimeout(() => console.log("Executed once after 2 seconds"), 2000); // 1 time
after 2 seconds
setInterval(() => console.log("Executed every 2 seconds"), 2000); // Repeated
every 2 seconds
49.What is the window object in JavaScript?
Answer:
The window object is a global object that represents the browser's
window. It provides methods to interact with the browser environment,
like manipulating the DOM, handling events, and managing timers. The
window object also serves as the global object for all JavaScript code
running in the browser.
Example:
javascript
Copy code
console.log(window.innerWidth); // Width of the window
50.What is Debouncing in JavaScript?
Answer:
Debouncing is a technique used to limit the rate at which a function is
executed. It ensures that a function is called only after a certain amount
of time has passed since the last invocation. It is commonly used for
handling events like resize or scroll to improve performance.
Example:
javascript
Copy code
function debounce(func, delay) {
let timeout;
return function() {
clearTimeout(timeout);
timeout = setTimeout(func, delay);
};
}

const debouncedFunction = debounce(() => console.log("Executed after


500ms"), 500);
window.addEventListener("resize", debouncedFunction);

You might also like