2.1 answers- js interview questions
2.1 answers- js interview questions
○
○
7. What is strict mode in JavaScript and how is it
12. Explain the difference between function declaration
enabled?
and function expression.
Function declarations are hoisted and can be used before they even after the outer function has finished executing.
are declared. Function expressions are not hoisted and javascript
cannot be used before they are defined. Copy code
javascript function outer() {
Copy code let count = 0;
sayHello(); // Works return function inner() {
count++;
function sayHello() { return count;
console.log('Hello!'); };
} }
○ ○
16. Explain function closures and how they are used.
18. How does this keyword work in JavaScript?
○ speak() {
26. Explain object destructuring in JavaScript. console.log(`${this.name} makes a
sound.`);
Object destructuring allows you to extract properties from
}
objects and bind them to variables.
}
javascript
Copy code
let person = { // Subclass
name: 'Alice', class Dog extends Animal {
age: 25 constructor(name, breed) {
}; super(name);
this.breed = breed;
let { name, age } = person; }
console.log(name); // Logs 'Alice'
console.log(age); // Logs 25 speak() {
console.log(`${this.name} barks.`);
○ }
27. How do you clone an object in JavaScript? }
Object cloning can be done using various methods like spread let myDog = new Dog('Buddy', 'Golden
syntax (...), Object.assign(), or using libraries like Retriever');
Lodash. myDog.speak(); // Logs 'Buddy barks.'
javascript
Copy code
○
// Using spread syntax
30. Explain the difference between hasOwnProperty and
let obj = { a: 1, b: 2 };
in operator.
let clone = { ...obj };
○ // Using splice()
32. Explain the various methods to add and remove fruits.splice(2, 1, 'grape'); // ['apple',
elements from an array.
'banana', 'grape', 'date']
// or promise.then(function(value) {
arr.constructor === Array; // true console.log(value); // Logs 'Success!'
after 1 second
● });
39. What are typed arrays in JavaScript?
●
Typed arrays are array-like objects that provide a mechanism for 43. Explain async and await keywords in JavaScript.
reading and writing raw binary data in memory. They offer
better performance for handling numerical data compared async keyword is used to define asynchronous functions.
to regular arrays. await keyword is used to pause execution within async
javascript
functions until a promise settles and returns its result.
Copy code
javascript
// Example of a typed array Copy code
let buffer = new ArrayBuffer(16); // 16 bytes async function getData() {
let view = new Int32Array(buffer); // 4 let response = await
elements, each 4 bytes (32-bit) fetch('https://api.example.com/data');
view[0] = 1; let data = await response.json();
view[1] = 2; return data;
}
●
●
Asynchronous JavaScript 44. What is the difference between callbacks and
promises?
40. What is asynchronous programming in JavaScript?
Callbacks are functions passed as arguments to another
Asynchronous programming in JavaScript allows operations to function to be executed later, while promises represent the
be executed asynchronously, meaning the code can eventual result of an asynchronous operation.
continue to run without waiting for an operation to finish. javascript
javascript Copy code
Copy code // Callback example
// Example of asynchronous operation function fetchData(callback) {
(setTimeout) setTimeout(function() {
console.log('Before timeout'); callback('Data fetched');
setTimeout(function() { }, 1000);
console.log('Inside timeout'); }
}, 1000);
console.log('After timeout'); fetchData(function(data) {
console.log(data); // Logs 'Data fetched'
● after 1 second
41. Explain the event loop in JavaScript. });
promise.then(function(data) { ●
console.log(data); // Logs 'Data fetched' 48. How do you handle multiple asynchronous operations
in JavaScript?
after 1 second
});
Multiple asynchronous operations can be handled using
Promise.all() to wait for all promises to settle, or using
●
45. How do you handle errors in asynchronous code? nested .then() calls for sequential operations.
javascript
Copy code
Errors in promises can be handled using .catch() method or
let promise1 =
try...catch blocks with async/await.
fetch('https://api.example.com/data1');
javascript
Copy code let promise2 =
async function fetchData() { fetch('https://api.example.com/data2');
try {
let response = await Promise.all([promise1, promise2])
fetch('https://api.example.com/data'); .then(responses =>
if (!response.ok) { Promise.all(responses.map(response =>
throw new Error('Failed to fetch response.json())))
data'); .then(data => console.log(data))
} .catch(error => console.error('Error:',
let data = await response.json(); error));
return data;
●
} catch (error) {
console.error('Error:', error.message);
} DOM Manipulation and Events
}
49. How do you access and manipulate the DOM in
JavaScript?
●
46. Explain the concept of chaining in promises.
DOM can be accessed using methods like
getElementById(), querySelector(), and
Chaining promises allows you to execute asynchronous
manipulated using properties and methods like
operations sequentially by returning a new promise from
innerHTML, setAttribute(), appendChild().
.then() or .catch() handlers.
javascript
javascript
Copy code
Copy code
// Accessing and manipulating DOM
fetch('https://api.example.com/data')
document.getElementById('myElement').innerHTML
.then(response => response.json())
= 'Hello, World!';
.then(data => console.log(data))
.catch(error => console.error('Error:',
●
error));
50. Explain event handling in JavaScript.
●
Event handling involves attaching event listeners to DOM
47. What are generator functions and iterators in
elements to respond to user interactions or other events.
JavaScript?
javascript
Copy code
Generator functions are special functions that can be paused document.getElementById('myButton').addEven
and resumed, producing a sequence of values using
tListener('click', function() {
yield keyword. Iterators are objects that implement the
console.log('Button clicked');
iterator protocol, used in for...of loops.
});
javascript
Copy code
function* generator() { ●
51. What are event bubbling and capturing?
yield 1;
yield 2;
Event bubbling is the propagation of events from the target
yield 3; element up through its ancestors to the root of the
} document. Event capturing is the opposite, where events
are captured from the root down to the target element.
let iterator = generator(); javascript
console.log(iterator.next()); // { value: 1, Copy code
done: false } // Event bubbling example
console.log(iterator.next()); // { value: 2, document.getElementById('myDiv').addEventListen
done: false } er('click', function() {
console.log('Div clicked');
}); Certainly! Let's continue with the remaining questions:
Cross-Origin Resource Sharing (CORS) issues can be handled test('adds 1 + 2 to equal 3', () => {
by configuring server-side headers to allow requests from expect(sum(1, 2)).toBe(3);
specific origins (Access-Control-Allow-Origin) and });
methods (Access-Control-Allow-Methods).
javascript ●
Copy code 77. What are some popular testing frameworks for
// Example of CORS-enabled fetch request JavaScript?
fetch('https://api.example.com/data', {
method: 'GET', Popular testing frameworks for JavaScript include Jest, Mocha,
headers: { Jasmine, and QUnit, each providing features for writing and
'Content-Type': 'application/json', executing tests.
javascript
'Access-Control-Allow-Origin': '*'
Copy code
}
// Example of using Mocha and Chai
})
const assert = require('chai').assert;
.then(response => response.json())
.then(data => console.log(data))
function multiply(a, b) {
.catch(error => console.error('Fetch error:',
return a * b;
error));
}
●
75. Explain the difference between synchronous and describe('Multiply function', function() {
asynchronous XMLHttpRequest. it('should multiply two numbers correctly',
function() {
XMLHttpRequest (XHR) is an older API for making HTTP assert.equal(multiply(2, 3), 6);
requests. Synchronous requests block the execution of });
code until the request completes, while asynchronous });
requests allow the code to continue executing while waiting
for the request to complete.
●
javascript
78. How do you optimize JavaScript code for better
Copy code
performance?
// Example of synchronous XHR
let xhr = new XMLHttpRequest(); JavaScript code can be optimized for performance by
xhr.open('GET', 'https://api.example.com/data', minimizing DOM manipulation, using efficient algorithms,
false); // false for synchronous caching variables, reducing function calls, and leveraging
xhr.send(null); browser developer tools for profiling and optimization.
console.log(xhr.responseText); javascript
Copy code
// Example of optimizing loop performance
// Example of asynchronous XHR
let sum = 0;
let xhrAsync = new XMLHttpRequest();
for (let i = 0; i < array.length; i++) {
xhrAsync.open('GET',
sum += array[i];
'https://api.example.com/data', true); //
}
true for asynchronous
xhrAsync.onload = function() {
// Optimized version using array.reduce()
if (xhrAsync.status === 200) {
let sum = array.reduce((acc, curr) => acc +
console.log(xhrAsync.responseText);
curr, 0);
} else {
● console.log('Timer executed after 1
79. What tools would you use to analyze and improve second.');
website performance? }, 1000);
● Tools like Google Lighthouse, Chrome DevTools
(Performance tab), WebPageTest, and GTmetrix are used
to analyze website performance by measuring metrics such // Example of setInterval
as load times, rendering speed, and resource utilization. let count = 0;
let interval = setInterval(function() {
Security and Best Practices console.log('Interval count:', ++count);
if (count === 5) {
80. What are some common security issues in JavaScript clearInterval(interval);
applications? }
● Common security issues include XSS (Cross-Site }, 1000);
Scripting), CSRF (Cross-Site Request Forgery), insecure
data storage, improper input validation, and insecure
●
third-party dependencies.
86. Explain the difference between synchronous and
81. How do you prevent XSS (Cross-Site Scripting) attacks
asynchronous code execution.
in JavaScript?
● Synchronous code executes line by line, blocking further
● XSS attacks can be prevented by sanitizing user input,
execution until the current operation is completed.
escaping characters in output to prevent script execution,
Asynchronous code allows multiple operations to be
and using frameworks/libraries that handle XSS
executed concurrently, without blocking the main thread.
vulnerabilities.
87. How do you implement a carousel/slider in JavaScript?
82. What is Content Security Policy (CSP) and how do you
implement it?
A carousel/slider can be implemented using HTML, CSS for
layout, and JavaScript for handling transitions and user
Content Security Policy (CSP) is a security feature that helps
interactions (e.g., clicking arrows or swiping).
prevent XSS attacks by defining approved sources for
html
content. It is implemented using HTTP headers or <meta> Copy code
tags. <!-- Example of HTML structure for carousel
html
-->
Copy code
<div class="carousel">
<!-- Example of CSP meta tag -->
<div class="carousel-inner">
<meta http-equiv="Content-Security-Policy"
<div class="carousel-item">Slide
content="default-src 'self'">
1</div>
● <div class="carousel-item">Slide
83. How do you sanitize user input in JavaScript? 2</div>
<div class="carousel-item">Slide
User input can be sanitized by removing or escaping potentially 3</div>
harmful characters (like <, >, ', "), validating input against </div>
expected formats, and using libraries/frameworks for input <button class="carousel-control
sanitization. prev">Prev</button>
javascript
<button class="carousel-control
Copy code
next">Next</button>
// Example of sanitizing user input
</div>
function sanitizeInput(input) {
return input.replace(/[<>'"]/g, ''); //
●
Remove HTML and SQL injection characters
88. Explain the concept of lazy loading images in
} JavaScript.
document.querySelector('.container').classL
Responsive design in JavaScript can be handled using CSS
media queries for basic layout changes and JavaScript for ist.add('enhanced');
more dynamic changes based on viewport size or device }
orientation.
javascript ○
Copy code
// Example of responsive design with Graceful Degradation Example:
JavaScript javascript
window.addEventListener('resize', function() { Copy code
if (window.innerWidth < 768) { // Example of gracefully degrading feature
console.log('Mobile view'); try {
} else { // Use modern API
console.log('Desktop view'); } catch (error) {
} // Fallback to alternative approach
}); }
● ○
98. How do you implement internationalization (i18n) in
JavaScript applications? 100. How do you integrate third-party libraries and plugins
in JavaScript applications? - Third-party libraries and
plugins can be integrated into JavaScript applications by
including their scripts or modules using <script> tags,
import statements (for ES modules), or using package
managers like npm or yarn.
javascript
Copy code
// Example of integrating a third-party
library
import { gsap } from 'gsap';