0% found this document useful (0 votes)
74 views

JS_solved

The document provides a comprehensive list of JavaScript interview questions and answers, categorized into basic, intermediate, and experienced levels. Key topics include JavaScript fundamentals, data types, functions, event handling, promises, and advanced concepts like closures and the event loop. It serves as a preparation guide for freshers and experienced candidates alike, covering essential concepts and practical examples.

Uploaded by

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

JS_solved

The document provides a comprehensive list of JavaScript interview questions and answers, categorized into basic, intermediate, and experienced levels. Key topics include JavaScript fundamentals, data types, functions, event handling, promises, and advanced concepts like closures and the event loop. It serves as a preparation guide for freshers and experienced candidates alike, covering essential concepts and practical examples.

Uploaded by

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

JavaScript Interview Questions for Freshers (Basic Level JS Interview Questions And

Answers): 00:01:52 - What is JavaScript and its common uses? 00:02:12 - What are
template literals in JavaScript? 00:02:59 - What is hoisting? Provide an example.
00:04:09 - Difference between let, var, and const. 00:05:40 - Data types in
JavaScript. 00:07:55 - What is an array, and how to access its elements? 00:08:34 -
Difference between == and ===. 00:09:12 - Purpose of the isNaN function.
00:10:04 - What is null vs undefined? 00:10:44 - Use of the typeof operator. 👨‍💻
Intermediate Level JavaScript Interview Questions (JavaScript Interview Preparation
Guide): 00:11:08 - Purpose of the map method in JavaScript. 00:13:51 - Explain
event bubbling and event capturing. 00:20:25 - What are higher-order functions?
Provide an example. 00:22:18 - What is an IIFE (Immediately Invoked Function
Expression)? 00:24:36 - Explain closures in JavaScript. 00:30:12 - How do
setTimeout and setInterval work? 00:35:25 - Describe promises in JavaScript.
00:39:05 - Use of async and await in JavaScript. 00:42:57 - Difference between call,
apply, and bind. 00:50:01 - What is event delegation? 👨‍💻 JavaScript Interview
Questions and Answers for Experienced (JavaScript Interview Coding Questions):
00:57:46 - Explain the event loop in JavaScript. 00:59:47 - Difference between
promises and async/await. 01:03:56 - Purpose of the reduce method in arrays.
01:08:31 - Explain currying in JavaScript. 01:12:42 - What is a generator function
and its usage? 01:15:57 - What are weak maps and weak sets in JavaScript?
01:19:39 - How does JavaScript handle memory management? 01:21:25 - Difference
between shallow and deep copying. 01:25:57 - What is strict mode in JavaScript and
how is it enabled? 01:32:47 - Observer pattern and its relation to JavaScript.

1. What is JavaScript and its common uses?


JavaScript is a high-level, interpreted programming language primarily used for web
development. It is a core technology of the World Wide Web (along with HTML and
CSS). JavaScript enables dynamic interaction and functionality on websites, such as
form validation, animation, and user interactivity.
Common uses:
 Client-side web development (interactivity, form validation, animations)
 Server-side web development (using Node.js)
 Game development
 Mobile app development (via frameworks like React Native)
 Creating web APIs
2. What are template literals in JavaScript?
Template literals are a feature in JavaScript that allows embedded expressions
inside string literals, and they are enclosed by backticks (`) instead of single or
double quotes. They can include placeholders for variables or expressions inside $
{}.
Example:
javascript
Copy
let name = 'Alice';
let age = 30;
let message = `Hello, my name is ${name} and I am ${age} years old.`;
console.log(message); // Output: "Hello, my name is Alice and I am 30 years old."
3. What is hoisting? Provide an example.
Hoisting is a JavaScript mechanism where variables and functions are moved to the
top of their scope before code execution. Variables declared with var and function
declarations are hoisted to the top.
Example:
javascript
Copy
console.log(x); // undefined
var x = 5;
console.log(x); // 5

// Function hoisting
greet(); // Output: "Hello!"

function greet() {
console.log("Hello!");
}
In the above example, the variable x is hoisted, but its assignment (x = 5) happens
later, so the first console.log(x) prints undefined. The function greet() is hoisted with
its definition, so it works even before its declaration.
4. Difference between let, var, and const:
 var: Variables declared with var have function or global scope and can be re-
assigned.
 let: Variables declared with let have block scope (limited to the block,
statement, or expression) and can be re-assigned.
 const: Variables declared with const have block scope and cannot be re-
assigned. However, objects or arrays declared with const can still have their
properties or elements modified.
Example:
javascript
Copy
var a = 1;
let b = 2;
const c = 3;

a = 10; // Re-assignable
b = 20; // Re-assignable
// c = 30; // Error: Assignment to constant variable.

console.log(a, b, c);
5. Data types in JavaScript:
JavaScript has both primitive and non-primitive data types:
 Primitive types: string, number, boolean, undefined, null, symbol, bigint
 Non-primitive types: object (including arrays, functions, and others)
Example:
javascript
Copy
let name = "John"; // string
let age = 25; // number
let isActive = true; // boolean
let address = null; // null
let person; // undefined
let uniqueId = Symbol('id'); // symbol
6. What is an array, and how to access its elements?
An array is a data structure that stores multiple values in a single variable. Arrays
are indexed, and you can access their elements using the index (starting from 0).
Example:
javascript
Copy
let fruits = ['apple', 'banana', 'cherry'];
console.log(fruits[0]); // 'apple'
console.log(fruits[1]); // 'banana'
console.log(fruits[2]); // 'cherry'
7. Difference between == and ===:
 == (loose equality): Compares values, performing type conversion if
necessary.
 === (strict equality): Compares both the value and the type, without type
conversion.
Example:
javascript
Copy
console.log(5 == '5'); // true (because type conversion happens)
console.log(5 === '5'); // false (because types are different)

console.log(0 == false); // true


console.log(0 === false); // false
8. Purpose of the isNaN function:
isNaN() checks whether a value is NaN (Not-a-Number). It returns true if the value is
NaN, and false otherwise.
Example:
javascript
Copy
console.log(isNaN(100)); // false (100 is a number)
console.log(isNaN('Hello')); // true (it's not a number)
console.log(isNaN('123')); // false (it's a valid number string)
9. What is null vs undefined?
 null: Represents the intentional absence of any object value. It's an object
type.
 undefined: Represents a variable that has been declared but not assigned a
value. It is its own type.
Example:
javascript
Copy
let a = null; // intentionally no value
let b; // undefined, variable declared but not initialized

console.log(a); // null
console.log(b); // undefined
10. Use of the typeof operator:
The typeof operator is used to determine the type of a variable or value.
Example:
javascript
Copy
console.log(typeof 'Hello'); // string
console.log(typeof 123); // number
console.log(typeof true); // boolean
console.log(typeof {}); // object
console.log(typeof undefined); // undefined
console.log(typeof Symbol()); // symbol
1. Purpose of the map method in JavaScript:
The map() method creates a new array populated with the results of calling a
provided function on every element in the array. It's commonly used to transform or
modify the elements of an array.
Example:
javascript
Copy
let numbers = [1, 2, 3, 4];
let doubled = numbers.map(num => num * 2);

console.log(doubled); // Output: [2, 4, 6, 8]


In this example, map() is used to double each number in the array.

2. Explain event bubbling and event capturing:


 Event Bubbling: The event starts from the target element and then bubbles
up to the root of the DOM, triggering any parent event listeners along the
way.
 Event Capturing: The event starts from the root and is captured by each
parent element before reaching the target element.
By default, most browsers use event bubbling.
Example (Event Bubbling):
html
Copy
<div id="parent" style="padding: 20px; border: 1px solid;">
<button id="child">Click me</button>
</div>

<script>
document.getElementById('parent').addEventListener('click', function() {
alert('Parent clicked');
});

document.getElementById('child').addEventListener('click', function() {
alert('Child clicked');
});
</script>
When you click the button, the "Child clicked" message shows first, and then the
"Parent clicked" message appears, demonstrating event bubbling.

3. What are higher-order functions? Provide an example.


A higher-order function is a function that either:
 Takes one or more functions as arguments, or
 Returns a function as its result.
Example:
javascript
Copy
// Higher-order function that accepts another function
function greet(name, callback) {
console.log(`Hello, ${name}!`);
callback();
}

greet('Alice', () => {
console.log('How are you today?');
});
Here, the greet() function is a higher-order function because it takes a function
(callback) as an argument.

4. What is an IIFE (Immediately Invoked Function Expression)?


An IIFE is a function that is defined and executed immediately after being declared.
It's commonly used to create a new scope and avoid polluting the global
namespace.
Example:
javascript
Copy
(function() {
let message = 'I am an IIFE!';
console.log(message);
})(); // Output: "I am an IIFE!"
The function is invoked immediately after being defined, without needing to call it
explicitly.

5. Explain closures in JavaScript:


A closure occurs when a function is able to remember and access its lexical scope,
even when the function is executed outside that scope.
Example:
javascript
Copy
function outer() {
let count = 0;
return function inner() {
count++;
console.log(count);
};
}

const counter = outer();


counter(); // Output: 1
counter(); // Output: 2
Here, the inner function forms a closure with the count variable from the outer
function. Even after outer() has finished executing, inner() still has access to count.

6. How do setTimeout and setInterval work?


 setTimeout(): Executes a function after a specified delay (in milliseconds).
 setInterval(): Executes a function repeatedly, with a specified interval (in
milliseconds).
Example:
javascript
Copy
// setTimeout
setTimeout(() => {
console.log('Executed after 2 seconds');
}, 2000);

// setInterval
let counter = 0;
const intervalId = setInterval(() => {
counter++;
console.log('Interval count:', counter);
if (counter === 5) {
clearInterval(intervalId); // Stop the interval after 5 iterations
}
}, 1000);

7. Describe promises in JavaScript:


A promise is an object representing the eventual completion or failure of an
asynchronous operation. It has three states:
 Pending: The operation is ongoing.
 Resolved (Fulfilled): The operation is successful.
 Rejected: The operation failed.
Example:
javascript
Copy
let myPromise = new Promise((resolve, reject) => {
let success = true;

if (success) {
resolve("Operation successful");
} else {
reject("Operation failed");
}
});

myPromise
.then(result => console.log(result)) // "Operation successful"
.catch(error => console.log(error)); // Will catch any rejection

8. Use of async and await in JavaScript:


 async: Declares a function as asynchronous, making it return a promise.
 await: Pauses the execution of the async function until a promise resolves.
Example:
javascript
Copy
async function fetchData() {
let response = await fetch('https://api.example.com/data');
let data = await response.json();
console.log(data);
}

fetchData();
In this example, await pauses execution until the fetch() request resolves and
returns data.

9. Difference between call, apply, and bind:


 call(): Immediately invokes a function with a given this value and arguments.
 apply(): Similar to call(), but arguments are passed as an array.
 bind(): Returns a new function with a specified this value, which can be
called later.
Example:
javascript
Copy
function greet(greeting, punctuation) {
console.log(`${greeting}, ${this.name}${punctuation}`);
}

let person = { name: 'Alice' };

// Using call
greet.call(person, 'Hello', '!'); // Output: "Hello, Alice!"

// Using apply
greet.apply(person, ['Hello', '!']); // Output: "Hello, Alice!"

// Using bind
let boundGreet = greet.bind(person, 'Hi', '!');
boundGreet(); // Output: "Hi, Alice!"

10. What is event delegation?


Event delegation is a technique where you attach a single event listener to a
parent element instead of attaching it to each child element. It relies on the concept
of event bubbling, where events are propagated from child elements to parent
elements.
Example:
html
Copy
<ul id="list">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>

<script>
document.getElementById('list').addEventListener('click', function(event) {
if (event.target.tagName === 'LI') {
alert(`You clicked on ${event.target.textContent}`);
}
});
</script>
In this example, the click event listener is attached to the ul element, and it checks
if the clicked element is an li. This way, we don't need to attach separate event
listeners to each li element.
HTML
➡️What is DOM?
➡️What are HTML Entities?
➡️What are Meta Tags?
➡️Explain Semantic Elements and how they differ from non-semantic elements.

🔹 CSS
➡️Explain the Box Model.
➡️What is Flexbox, and how does it work?
➡️Explain different CSS Positioning properties.
➡️What is Responsive Design, and how do you implement it?

🔹 JavaScript
➡️Difference between var, let, and const.
➡️Explain call, apply, and bind.
➡️Difference between splice and slice.
➡️Key ES6 Features.

🔹 JavaScript Output-Based Questions:

➡️for (var i = 0; i < 3; i++) {


setTimeout(() => console.log(i));
}

➡️a = [1, 2, 3];


a.length = 0;
console.log(a[0]);

➡️const arr = [1, 2, 3, 4, 5];


get the 2 elements from the array without modifying the original array

🔹 Javascript Problem-Solving Question:

➡️Given an array [1,2,3,2,3,3,4,4], return an object that counts the occurrences of


each element.

🔹 React
➡️What is the Virtual DOM?
➡️Difference between Redux and Context API.
➡️What are Higher-Order Components (HOCs)?
🔹 HTML Interview Questions & Answers
1. What are the differences between HTML4 and HTML5?

Feature HTML4 HTML5

<!DOCTYPE HTML PUBLIC


Doctype <!DOCTYPE html> (Simplified)
"-//W3C//DTD HTML 4.01//EN">

Audio & Needs third-party plugins like


Supports <audio> and <video>
Video Flash

Semantic New semantic tags like <article>,


No semantic tags
Tags <section>, <nav>

New elements like <input


Form
Limited form elements type="email">, <datalist>,
Elements
<output>

2. What is the difference between block-level and inline elements?


 Block-level elements: Take full width, start on a new line. (e.g., <div>,
<p>, <section>).
 Inline elements: Only take up as much width as needed. (e.g., <span>,
<a>, <strong>).

3. What is the purpose of the alt attribute in images?


The alt attribute provides alternative text for an image, useful for:
 Screen readers (Accessibility)
 SEO improvement
 When images fail to load
Example:
html
CopyEdit
<img src="logo.png" alt="Company Logo">

4. How does the <iframe> tag work in HTML?


An <iframe> is used to embed another webpage within a webpage.
Example:
html
CopyEdit
<iframe src="https://example.com" width="600" height="400"></iframe>

5. What is the difference between <section> and <div>?


 <section>: A semantic tag used to group related content with a heading.
 <div>: A generic container with no semantic meaning.
Example:
html
CopyEdit
<section>
<h2>About Us</h2>
<p>We provide the best services.</p>
</section>

<div class="container">Content inside div</div>

🔹 CSS Interview Questions & Answers


1. What is the difference between relative, absolute, and fixed
positioning?

Positio
Behavior
n

relative Moves relative to its normal position

absolut Positioned relative to the nearest positioned


e ancestor

fixed Stays fixed in the viewport (even on scroll)

Example:
css
CopyEdit
.relative { position: relative; left: 20px; }
.absolute { position: absolute; top: 50px; left: 100px; }
.fixed { position: fixed; top: 0; left: 0; width: 100%; }

2. What are pseudo-classes and pseudo-elements?


 Pseudo-classes: Apply styles based on element states.
css
CopyEdit
a:hover { color: red; } /* Changes color on hover */
 Pseudo-elements: Style a part of an element.
css
CopyEdit
p::first-letter { font-size: 30px; }

3. What is the difference between visibility: hidden; and display: none;?

Property Effect

visibility: Element is invisible but still takes up


hidden; space

display: none; Element is removed from the layout

4. What is the difference between Flexbox and Grid?

Feature Flexbox Grid

One-dimensional (row or
Layout Two-dimensional (rows & columns)
column)

Alignme Uses justify-content and align- Uses grid-template-rows and grid-template-


nt items columns

Example display: flex; display: grid;

🔹 JavaScript Interview Questions & Answers


1. What is event delegation in JavaScript?
Event delegation allows adding a single event listener to a parent element, which
handles events for its children.
Example:
js
CopyEdit
document.getElementById("parent").addEventListener("click", function(event) {
if (event.target.tagName === "BUTTON") {
alert("Button clicked: " + event.target.innerText);
}
});

2. What is the difference between shallow copy and deep copy in


JavaScript?
 Shallow Copy: Copies only references (nested objects still point to original).
 Deep Copy: Creates a completely new copy.
Example:
js
CopyEdit
let obj1 = { a: 1, b: { c: 2 } };
let shallowCopy = { ...obj1 }; // Shallow Copy
let deepCopy = JSON.parse(JSON.stringify(obj1)); // Deep Copy

3. What are closures in JavaScript?


A closure is when an inner function remembers the variables of its outer function
even after the outer function has executed.
Example:
js
CopyEdit
function outer() {
let count = 0;
return function inner() {
count++;
console.log(count);
};
}

const counter = outer();


counter(); // 1
counter(); // 2

4. What is the difference between == and ===?

Operat
Behavior
or

Checks value equality (converts types if


==
needed)

=== Strict equality (checks both value & type)

Example:
js
CopyEdit
console.log(5 == "5"); // true (type conversion)
console.log(5 === "5"); // false (different types)

5. Explain map(), forEach(), filter(), and reduce().

Metho
Purpose
d

map() Returns a new array with modified values

forEach
Iterates but does not return a new array
()

Returns a new array with elements that match a


filter()
condition

reduce( Reduces an array to a single value


Metho
Purpose
d

Example:
js
CopyEdit
let numbers = [1, 2, 3, 4];

// map()
let squared = numbers.map(num => num * num); // [1, 4, 9, 16]

// forEach()
numbers.forEach(num => console.log(num));

// filter()
let even = numbers.filter(num => num % 2 === 0); // [2, 4]

// reduce()
let sum = numbers.reduce((acc, num) => acc + num, 0); // 10

6. How does the event loop work in JavaScript?


The Event Loop handles asynchronous code execution by:
1. Running synchronous code first.
2. Executing setTimeout, Promises, and async operations in the callback
queue when the stack is empty.
Example:
js
CopyEdit
console.log("Start");
setTimeout(() => console.log("Timeout"), 0);
Promise.resolve().then(() => console.log("Promise"));
console.log("End");
Output:
sql
CopyEdit
Start
End
Promise
Timeout
(Promise resolves before setTimeout because of the microtask queue.)

You might also like