0% found this document useful (0 votes)
11 views15 pages

2.1 answers- js interview questions

The document provides an overview of JavaScript concepts including data types, variable declarations, function definitions, and object manipulation. It explains key features such as strict mode, hoisting, closures, and the differences between various function types and variable scopes. Additionally, it covers array methods, prototypal inheritance, and the usage of ES6 classes, along with examples for better understanding.

Uploaded by

bedorat563
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views15 pages

2.1 answers- js interview questions

The document provides an overview of JavaScript concepts including data types, variable declarations, function definitions, and object manipulation. It explains key features such as strict mode, hoisting, closures, and the differences between various function types and variable scopes. Additionally, it covers array methods, prototypal inheritance, and the usage of ES6 classes, along with examples for better understanding.

Uploaded by

bedorat563
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Strict mode catches common coding mistakes and throws

Basics exceptions. It is enabled by placing 'use strict'; at the


beginning of a script or a function.
1. What are the data types in JavaScript? javascript
Copy code
○ JavaScript has primitive data types such as number,
'use strict';
string, boolean, null, undefined, and symbol
(added in ES6). Objects (object) and functions

(function) are also types in JavaScript.
8. What are global variables and how are they declared?
2. Explain the difference between undefined and null.
Global variables are accessible from any part of the program.
undefined means a variable has been declared but has not They are declared without the var, let, or const
yet been assigned a value. null is an assignment value keywords.
that represents a deliberate non-value. `javascript
javascript Copy code
Copy code globalVariable = 10;
let a; // undefined
let b = null; // null ○
9. Explain the difference between var, let, and const.

3. How does JavaScript handle types? var declares variables scoped to the nearest function block,
○ JavaScript is dynamically typed, meaning variables can
let declares variables scoped to the nearest enclosing
hold values of any type without any type enforcement. Type
block, and const declares constants scoped to the nearest
coercion may occur during operations.
4. What are truthy and falsy values in JavaScript? enclosing block.
javascript
Copy code
Truthy values are values that coerce to true in boolean
var a = 1;
contexts. Falsy values are values that coerce to false.
let b = 2;
javascript
const c = 3;
Copy code
// Falsy values

let falseValue = false;
10. How do you define constants in JavaScript?
let zero = 0;
let emptyString = '';
Constants are declared using the const keyword and must be
let notANumber = NaN;
initialized with a value that cannot be changed.
let nullValue = null; javascript
let undefinedValue = undefined; Copy code
const PI = 3.14;
// Truthy values
let trueValue = true; ○
let anyNonEmptyString = 'Hello';
let anyNonZeroNumber = 42; Functions
let anyObject = {};
11. What are the different ways to create functions in
○ JavaScript?
5. What is the difference between == and ===?
Functions can be created using function declarations, function
expressions, arrow functions, and methods (functions
== checks for equality after doing type conversion. === checks
defined on objects).
for equality without type conversion (strict equality).
javascript
javascript
Copy code
Copy code
// Function declaration
1 == '1'; // true (type coercion)
function greet() {
1 === '1'; // false (no type coercion)
return 'Hello!';
}

6. Explain hoisting in JavaScript.
// Function expression
Hoisting is JavaScript's default behavior of moving declarations let greet = function() {
to the top of the current scope before code execution. return 'Hello!';
javascript };
Copy code
console.log(a); // undefined
// Arrow function
var a = 5;
let greet = () => 'Hello!';



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!'); };
} }

sayHi(); // Error: sayHi is not a function let increment = outer();


increment(); // Returns 1
let sayHi = function() { increment(); // Returns 2
console.log('Hi!');
}; ○
17. What is a callback function? Provide an example of its
○ usage.
13. What are arrow functions? How do they differ from
regular functions? A callback function is a function passed into another function as
an argument to be executed later. It allows asynchronous
Arrow functions are a concise way to write function expressions actions and is common in event handling and AJAX
in JavaScript, using =>. They do not have their own this requests.
and arguments bindings. javascript
javascript Copy code
Copy code function fetchData(callback) {
let multiply = (x, y) => x * y; setTimeout(() => {
let data = 'Data fetched!';
○ callback(data);
14. What is function hoisting? Does it work with arrow }, 2000);
functions? }

Function hoisting moves function declarations to the top of the


function displayData(data) {
current scope. Arrow functions are not hoisted because
console.log(data);
they are part of expressions.
javascript }
Copy code
sayHello(); // Works fetchData(displayData); // Logs 'Data fetched!'
after 2 seconds
function sayHello() {
console.log('Hello!'); ○
}
Explain the concept of higher-order functions and provide
sayHi(); // Error: sayHi is not a function an example.
Higher-order functions are functions that take other functions as
let sayHi = () => { arguments or return functions as results. They enable
console.log('Hi!'); functional programming paradigms.
javascript
};
Copy code
function operateOnArray(arr, operation) {

let result = [];
15. How do you pass arguments to a function in
JavaScript? for (let element of arr) {
result.push(operation(element));
Arguments are passed to functions as comma-separated values }
inside parentheses during function invocation. return result;
javascript }
Copy code
function add(a, b) { let numbers = [1, 2, 3, 4, 5];
return a + b;
} // Example of higher-order function using map
let squaredNumbers = operateOnArray(numbers, x
add(3, 5); // Returns 8 => x * x);

○ ○
16. Explain function closures and how they are used.
18. How does this keyword work in JavaScript?

A closure is the combination of a function and the lexical


this refers to the object to which a method belongs or the
environment within which that function was declared. It
context in which a function is called. Its value is determined
allows a function to access variables from its outer scope
by how a function is invoked.
javascript // Using constructor function
Copy code function Person(name, age) {
let person = {
this.name = name;
name: 'John',
this.age = age;
greet: function() {
this.greet = function() {
console.log(`Hello, ${this.name}!`);
console.log(`Hello, my name is
}
${this.name}.`);
};
};
}
person.greet(); // Logs 'Hello, John!'

let person1 = new Person('Alice', 25);



19. What is the difference between call, apply, and bind
methods? // Using Object.create()
let obj = Object.create(null);
call and apply are used to invoke functions with a specific obj.name = 'Bob';
context (this value) and arguments. bind creates a new obj.age = 20;
function with a fixed context (this value) and optional
arguments. ○
javascript 22. Explain the concept of prototypal inheritance in
Copy code JavaScript.
let person1 = { name: 'Alice' };
let person2 = { name: 'Bob' }; In JavaScript, objects can inherit properties and methods from
other objects. Every JavaScript object has a prototype
object, which acts as a template object that it inherits
function greet() { methods and properties from.
console.log(`Hello, ${this.name}!`); javascript
} Copy code
// Example of prototypal inheritance
greet.call(person1); // Logs 'Hello, Alice!' let animal = {
greet.apply(person2); // Logs 'Hello, Bob!' makeSound: function() {
console.log('Some sound');
let greetBob = greet.bind(person2); }
greetBob(); // Logs 'Hello, Bob!' };

○ let cat = Object.create(animal);


cat.makeSound(); // Logs 'Some sound'
This covers the Basics and Functions categories. Let me know if
you'd like to continue with Objects and Prototypes, Arrays, ○
or any other topic! 23. What is a prototype chain?

3.5 The prototype chain is a series of objects linked together by their


prototypes. It is used to implement inheritance and shared
continue properties among objects.
javascript
ChatGPT Copy code
let animal = {
Certainly! Let's continue with Objects and Prototypes, and then makeSound: function() {
we'll move on to Arrays: console.log('Some sound');
}
Objects and Prototypes };

21. How do you create objects in JavaScript?


let cat = Object.create(animal);
let kitten = Object.create(cat);
Objects in JavaScript can be created using object literals, the
new keyword with a constructor function, or with
kitten.makeSound(); // Logs 'Some sound'
Object.create() method.
javascript

Copy code
24. How do you add properties to an object in JavaScript?
// Using object literals
let person = {
Properties can be added to an object using dot notation or
name: 'John',
bracket notation.
age: 30, javascript
greet: function() { Copy code
console.log(`Hello, my name is let person = {};
${this.name}.`); person.name = 'Alice';
} person['age'] = 30;
};
○ this.age = age;
25. What are object methods? Provide an example. }
}
Object methods are functions defined on objects. They can
access and manipulate object properties.

javascript
29. How do you inherit from a class in JavaScript?
Copy code
let person = {
Inheritance in JavaScript can be achieved using the extends
name: 'John',
keyword to create a subclass (child class) from a
greet: function() { superclass (parent class).
console.log(`Hello, my name is javascript
${this.name}.`); Copy code
} // Superclass
}; class Animal {
constructor(name) {
person.greet(); // Logs 'Hello, my name is this.name = name;
John.' }

○ 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 };

hasOwnProperty is a method that checks if an object has a


// Using Object.assign()
property defined on itself, not inherited from its prototype
let clonedObj = Object.assign({}, obj); chain. The in operator checks if a property exists
anywhere in the prototype chain of the object.
○ javascript
28. What are ES6 classes? How do they differ from Copy code
constructor functions? let obj = { a: 1 };

ES6 classes are a syntactical sugar over JavaScript's existing


obj.hasOwnProperty('a'); // true
prototype-based inheritance. They provide a more familiar
'a' in obj; // true
and cleaner syntax for defining classes and their
relationships.
javascript ○
Copy code
// Using constructor function Arrays
function Person(name, age) {
this.name = name; 31. How do you create an array in JavaScript?
this.age = age;
} Arrays can be created using array literals or the Array
constructor.
javascript
// Using ES6 class
Copy code
class Person {
// Using array literal
constructor(name, age) {
let fruits = ['apple', 'banana', 'cherry'];
this.name = name;
// Using slice()
// Using Array constructor let slicedFruits = fruits.slice(1, 3); //
let numbers = new Array(1, 2, 3, 4, 5); ['banana', 'cherry']

○ // Using splice()
32. Explain the various methods to add and remove fruits.splice(2, 1, 'grape'); // ['apple',
elements from an array.
'banana', 'grape', 'date']

Elements can be added to arrays using push(), unshift(), ○


or splice(), and removed using pop(), shift(), or 35. How do you iterate over an array in JavaScript?
splice().
javascript Arrays can be iterated using various methods such as for
Copy code loops, forEach(), map(), filter(), reduce(), etc.
let fruits = ['apple', 'banana']; javascript
Copy code
// Adding elements let numbers = [1, 2, 3, 4, 5];
fruits.push('cherry'); // ['apple', 'banana',
'cherry'] // Using for loop
fruits.unshift('orange'); // ['orange', for (let i = 0; i < numbers.length; i++) {
'apple', 'banana', 'cherry'] console.log(numbers[i]);
fruits.splice(2, 0, 'grape'); // ['orange', }
'apple', 'grape', 'banana', 'cherry']
// Using forEach()
// Removing elements numbers.forEach(num => console.log(num));
fruits.pop(); // ['orange', 'apple', 'grape',
'banana'] // Using map()
fruits.shift(); // ['apple', 'grape', 'banana'] let doubledNumbers = numbers.map(x => x * 2);
fruits.splice(1, 1); // ['apple', 'banana']
// Using for...of loop
○ for (let num of numbers) {
33. What are array methods like map, filter, and console.log(num);
reduce? Provide examples of their usage. }

map() creates a new array with the results of calling a provided ○


function on every element. filter() creates a new array
with elements that pass a test. reduce() applies a These explanations and examples should cover the Objects and
function to each element of the array to reduce it to a single Prototypes and Arrays sections. If you have any more
value. questions or need further clarification, feel free to ask!
javascript
Copy code Arrays
let numbers = [1, 2, 3, 4, 5];
36. What are array-like objects? Provide examples.
// Using map()
let doubledNumbers = numbers.map(x => x * 2); Array-like objects are objects that have indexed properties and a
// [2, 4, 6, 8, 10] length property, but do not inherit from
Array.prototype. Examples include DOM NodeList
// Using filter() objects and the arguments object.
let evenNumbers = numbers.filter(x => x % 2 === javascript
0); // [2, 4] Copy code
// NodeList example (from DOM)
// Using reduce() let nodeList = document.querySelectorAll('p');
let sum = numbers.reduce((acc, curr) => acc +
curr, 0); // 15 // Arguments object example (from function
parameters)
○ function sum() {
34. Explain the difference between slice and splice console.log(arguments.length); // Logs
methods. number of arguments passed
}
slice() returns a shallow copy of a portion of an array into a
new array object. splice() changes the contents of an ●
array by removing or replacing existing elements and/or 37. Explain the forEach method and how it differs from a
adding new elements in place. regular for loop.
javascript
Copy code
forEach is a method on arrays that iterates over each element
let fruits = ['apple', 'banana', 'cherry', and executes a callback function. It provides a more
'date']; concise way to iterate compared to a traditional for loop.
javascript
Copy code javascript
let numbers = [1, 2, 3, 4, 5]; Copy code
console.log('Start');
// Using forEach setTimeout(function() {
numbers.forEach(function(number) { console.log('Timeout');
console.log(number); }, 0);
}); console.log('End');

// Equivalent to traditional for loop ●


42. What are promises in JavaScript? How do they work?
for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
Promises are objects that represent the eventual completion or
}
failure of an asynchronous operation and its resulting
value.
● javascript
38. How do you check if a variable is an array in Copy code
JavaScript? // Example of a promise
let promise = new Promise(function(resolve,
You can check if a variable is an array using
reject) {
Array.isArray() method or by checking its constructor.
setTimeout(function() {
javascript
Copy code resolve('Success!');
let arr = [1, 2, 3]; }, 1000);
Array.isArray(arr); // true });

// 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. });

The event loop is a mechanism that handles asynchronous


// Promise example
operations in JavaScript. It continuously checks the call
stack and task queue, moving tasks from the queue to the let promise = new Promise(function(resolve,
stack when the stack is empty. reject) {
setTimeout(function() { console.log(iterator.next()); // { value: 3,
resolve('Data fetched'); done: false }
}, 1000); console.log(iterator.next()); // { value:
}); undefined, done: true }

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:

// Event capturing example DOM Manipulation and Events (continued)


document.addEventListener('click', function() {
console.log('Document clicked'); 55. How do you create and trigger custom events in
}, true); JavaScript?

● Custom events can be created using CustomEvent constructor


52. How do you add and remove event listeners in and triggered using dispatchEvent() method on DOM
JavaScript? elements.
javascript
Event listeners are added using addEventListener() and Copy code
// Creating a custom event
removed using removeEventListener().
javascript let customEvent = new
Copy code CustomEvent('myCustomEvent', {
function handleClick() { detail: { key: 'value' }
console.log('Button clicked'); });
}
// Triggering the custom event on an element
document.getElementById('myButton').addEventLis document.getElementById('myElement').dispatchEv
tener('click', handleClick); ent(customEvent);

// Remove event listener // Listening for the custom event


document.getElementById('myButton').removeEvent document.getElementById('myElement').addEventLi
Listener('click', handleClick); stener('myCustomEvent', function(event) {
console.log('Custom event triggered with
● detail:', event.detail);
53. How do you prevent default behavior in an event? });

Default behavior of an event can be prevented using ●


event.preventDefault() inside the event handler 56. Explain the difference between
function. document.getElementById and
javascript document.querySelector.
Copy code
document.getElementById('myLink').addEventL
document.getElementById is used to select an element by
istener('click', function(event) {
its id attribute, returning a single element, while
event.preventDefault();
document.querySelector allows you to select
console.log('Link clicked, but default
elements using CSS selectors, returning the first matching
behavior prevented.'); element.
}); javascript
Copy code
● // Example of getElementById
54. Explain event delegation and its benefits. let elementById =
document.getElementById('myId');
Event delegation is a technique where a single event listener is
attached to a parent element to manage events for its child
// Example of querySelector
elements. It helps to handle dynamically added elements
let elementByQuery =
efficiently.
javascript document.querySelector('.myClass');
Copy code
document.getElementById('myList').addEventL ●
istener('click', function(event) {
if (event.target.tagName === 'LI') { ES6+ Features
console.log('List item clicked:',
event.target.textContent); 57. What are the new features introduced in ES6
(ECMAScript 2015)?
}
});
ES6 introduced significant enhancements such as arrow
functions, let and const for variable declarations,

classes, template literals, destructuring, promises, and
55. How do you create and trigger custom events in
more.
JavaScript?
javascript
● Custom events can be created using `Custom
Copy code
// Example of ES6 features
3.5
const name = 'Alice';
let age = 30;
continue

ChatGPT class Person {


constructor(name, age) {
this.name = name; Copy code
this.age = age; // Example of arrow function
} const add = (a, b) => a + b;
console.log(add(3, 5)); // Outputs: 8
greet() {
return `Hello, my name is ${this.name} ●
62. What are default parameters in ES6?
and I am ${this.age} years old.`;
}
Default parameters allow you to initialize function parameters
}
with default values if no argument or undefined is
passed.
let alice = new Person(name, age); javascript
console.log(alice.greet()); Copy code
// Example of default parameters
● function greet(name = 'Guest') {
58. Explain destructuring assignment in ES6. console.log(`Hello, ${name}!`);
}
Destructuring assignment allows you to extract values from
arrays or objects into variables using syntax that mirrors
the structure of the array or object. greet(); // Outputs: Hello, Guest!
javascript greet('Alice'); // Outputs: Hello, Alice!
Copy code
// Example of array destructuring ●
let numbers = [1, 2, 3]; 63. How do you use classes in ES6?
let [a, b, c] = numbers;
Classes in ES6 provide a cleaner syntax for creating objects and
console.log(a, b, c); // Outputs: 1 2 3
implementing inheritance using extends keyword.
javascript
// Example of object destructuring
Copy code
let person = { name: 'Bob', age: 25 };
// Example of ES6 class
let { name, age } = person;
class Animal {
console.log(name, age); // Outputs: Bob 25
constructor(name) {
this.name = name;

}
59. What are template literals in ES6?

Template literals are string literals that allow embedded speak() {


expressions and multi-line strings. They are enclosed by console.log(`${this.name} makes a
backticks ( ) instead of single or double quotes. noise.`);
javascript }
Copy code }
// Example of template literals
let name = 'Charlie'; class Dog extends Animal {
let greeting = `Hello, ${name}!`; speak() {
console.log(greeting); // Outputs: Hello, console.log(`${this.name} barks.`);
Charlie! }
}

60. How do you use let and const in ES6? let dog = new Dog('Buddy');
dog.speak(); // Outputs: Buddy barks.
let and const are used for variable declarations. let allows
reassignment of variable values, while const declares ●
constants whose values cannot be changed once 64. Explain the spread (...) operator and its uses.
assigned.
javascript
The spread operator ... allows an iterable (like arrays or
Copy code
strings) to be expanded into individual elements. It is useful
let count = 10;
for array manipulation, function arguments, and object
count = 20; // Valid with let literals.
javascript
const PI = 3.14; Copy code
PI = 3.14159; // Error: Assignment to constant // Example of spread operator with arrays
variable let arr1 = [1, 2, 3];
let arr2 = [...arr1, 4, 5];
● console.log(arr2); // Outputs: [1, 2, 3, 4, 5]
61. Explain arrow functions and their advantages.
// Example of spread operator with function
Arrow functions are a concise syntax for writing function
arguments
expressions in JavaScript, with implicit return and lexical
function sum(a, b, c) {
this binding.
return a + b + c;
javascript
} throw new TypeError('Invalid type:
let numbers = [1, 2, 3]; Expected a number.');
console.log(sum(...numbers)); // Outputs: 6 }
return number;
● }
65. What are modules in ES6? How do you export and
import modules?
try {
validateNumber('abc');
Modules in ES6 provide a way to organize code into reusable
} catch (error) {
components. Modules are exported using export and
console.error(error.message);
imported using import.
}
javascript
Copy code
// Example of exporting and importing ●
69. What are some common debugging techniques in
modules
JavaScript?
// math.js (exporting module) ● Common debugging techniques include using
export function sum(a, b) { console.log(), console.error(), breakpoints in
return a + b; browser developer tools, debugger statement, and logging
} stack traces.
70. How do you use the JavaScript console for
// app.js (importing module) debugging?
import { sum } from './math.js';
console.log(sum(5, 3)); // Outputs: 8 The JavaScript console in browser developer tools (e.g.,
Chrome DevTools) is used for debugging by logging
messages, evaluating expressions, and inspecting

variables.
javascript
Error Handling and Debugging Copy code
console.log('Debugging message');
66. How do you handle errors in JavaScript? console.error('Error message');

Errors in JavaScript can be handled using try...catch blocks ●


to catch and handle exceptions.
javascript
Web APIs and Browser Environment
Copy code
try {
71. How do you use localStorage and sessionStorage in
// Code that may throw an error
JavaScript?
throw new Error('Something went wrong!');
} catch (error) {
localStorage and sessionStorage provide mechanisms to
console.error(error);
store key-value pairs in the browser. localStorage
} persists data across browser sessions, while
sessionStorage persists data within the session.
● javascript
67. What are try, catch, and finally blocks? Copy code
// Example of using localStorage
try block contains code that may throw an error. catch block localStorage.setItem('key', 'value');
handles the error if one occurs. finally block contains let storedValue = localStorage.getItem('key');
code that executes regardless of whether an error occurred console.log(storedValue); // Outputs: 'value'
or not.
javascript
// Example of using sessionStorage
Copy code
sessionStorage.setItem('key', 'value');
try {
// Code that may throw an error

throw new Error('Something went wrong!');
72. What is the difference between localStorage and
} catch (error) { cookies?
console.error(error);
} finally { localStorage stores data locally in the browser, has larger
console.log('Execution complete.'); storage capacity (5MB+), and is not sent with every HTTP
} request. Cookies are sent with every request, have smaller
storage capacity (4KB), and can be set with expiration.
● javascript
68. How do you throw custom errors in JavaScript? Copy code
// Example of setting a cookie
Custom errors can be thrown using throw keyword with an document.cookie = 'name=Alice; expires=Sun, 20
instance of Error or its subclasses. Jun 2024 12:00:00 UTC; path=/';
javascript
Copy code
function validateNumber(number) { 73. How do you make HTTP requests in JavaScript?
if (typeof number !== 'number') { Explain fetch API.
fetch() API is used to make HTTP requests in JavaScript, console.error('Request failed.
supporting modern promises and providing a more flexible Status:', xhrAsync.status);
and powerful interface for fetching resources from the }
network. };
javascript
xhrAsync.send(null);
Copy code
// Example of using fetch API

fetch('https://api.example.com/data')
.then(response => {
Testing and Performance
if (!response.ok) {
throw new Error('Network response
76. How do you write unit tests for JavaScript code?
was not ok');
} Unit tests in JavaScript are typically written using testing
return response.json(); frameworks like Jest, Mocha, or Jasmine. Tests verify the
}) behavior of individual functions or modules.
.then(data => console.log(data)) javascript
.catch(error => console.error('Fetch Copy code
error:', error)); // Example of Jest test
function sum(a, b) {
● return a + b;
74. How do you handle CORS issues in JavaScript? }

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.

● Lazy loading delays loading of non-visible images until they are


84. What are some best practices for writing secure needed, typically as the user scrolls down the page,
JavaScript code? improving initial page load performance and reducing
● Best practices include validating input data, escaping bandwidth usage.
output to prevent XSS attacks, using HTTPS for secure javascript
communication, avoiding eval(), and keeping Copy code
libraries/frameworks updated to avoid known // Example of lazy loading images
vulnerabilities.
document.addEventListener('DOMContentLoaded',
function() {
Miscellaneous
let lazyImages =
document.querySelectorAll('img.lazy');
85. How do you create a timer in JavaScript?
lazyImages.forEach(function(lazyImage) {
lazyImage.src = lazyImage.dataset.src;
A timer in JavaScript can be created using setTimeout() or
});
setInterval() functions to execute code after a delay or
});
at regular intervals.
javascript
Copy code ●
// Example of setTimeout 89. How do you implement pagination using JavaScript?
setTimeout(function() {
Pagination can be implemented by fetching a subset of data 93. How do you handle routing in a single-page application
from a server/API and dynamically rendering page links or (SPA) using JavaScript?
buttons to navigate through pages.
javascript Routing in SPAs is typically handled using client-side routing
Copy code libraries like React Router, Vue Router, or by implementing
// Example of pagination custom routing logic using the History API.
const pageSize = 10; // Items per page javascript
let currentPage = 1; Copy code
// Example of routing with React Router
function fetchData(page) { import { BrowserRouter as Router, Switch, Route
// Fetch data for specified page from API } from 'react-router-dom';
}
function App() {
function renderPagination(totalPages) { return (
// Render pagination buttons or links <Router>
} <Switch>
<Route exact path="/"
// Example usage component={Home} />
fetchData(currentPage); <Route path="/about"
component={About} />
● <Route path="/products/:id"
90. How do you detect the browser and its version using component={ProductDetail} />
JavaScript? <Route component={NotFound} />
</Switch>
Browser detection can be done using navigator.userAgent </Router>
or feature detection (checking for specific browser APIs or );
behaviors).
}
javascript
Copy code

// Example of browser detection
94. How do you implement animations in JavaScript?
if (navigator.userAgent.includes('Chrome')) {
console.log('User is using Chrome Animations can be implemented in JavaScript using CSS
browser.'); animations/transitions or JavaScript libraries like GSAP
} (GreenSock Animation Platform) for more complex
animations.
● javascript
91. Explain the concept of functional programming in Copy code
JavaScript. // Example of animating with CSS
transitions
Functional programming in JavaScript emphasizes the use of const element =
pure functions, immutability, and higher-order functions to document.getElementById('animatedElement');
perform computations by composing functions together.
element.classList.add('animate');
javascript
Copy code
// Example of animating with GSAP library
// Example of functional programming
gsap.to('.animate', { duration: 1, x: 100,
const numbers = [1, 2, 3, 4, 5];
opacity: 0.5 });

// Using map and reduce for computation



const sum = numbers.map(num => num *
95. How do you implement drag-and-drop functionality in
2).reduce((acc, curr) => acc + curr, 0); JavaScript?
console.log(sum); // Outputs: 30
Drag-and-drop functionality can be implemented using native
HTML5 Drag and Drop API or JavaScript libraries like
interact.js for more advanced interactions.
92. What are the benefits of using immutable data javascript
structures in JavaScript? Copy code
● Immutable data structures, where data cannot be changed // Example of native HTML5 Drag and Drop
after creation, offer several benefits: API
○ Consistency: Immutable data ensures that once a value is const draggableElement =
set, it cannot be modified, avoiding unexpected changes. document.getElementById('draggable');
○ Concurrency: Immutable data is inherently thread-safe,
draggableElement.addEventListener('dragstart',
simplifying concurrent programming as data cannot be
mutated. function(event) {
○ Predictability: Immutability reduces bugs caused by event.dataTransfer.setData('text/plain',
unintended side effects, making code easier to reason 'Drag me!');
about and debug. });
○ Performance: Immutable data can optimize performance
by allowing data to be shared safely across components or const droppableElement =
threads without deep copying.
document.getElementById('droppable');
droppableElement.addEventListener('dragover', Internationalization (i18n) can be implemented using libraries
function(event) { like i18next, FormatJS, or frameworks like React Intl to
event.preventDefault(); handle translations and locale-specific formatting.
}); javascript
Copy code
// Example of using i18next for
droppableElement.addEventListener('drop',
internationalization
function(event) {
import i18n from 'i18next';
const data =
import { initReactI18next } from
event.dataTransfer.getData('text/plain');
'react-i18next';
event.target.textContent = data;
});
i18n
.use(initReactI18next)

96. Explain the concept of memoization and provide a .init({
practical example. resources: {
en: { translation: { welcome: 'Welcome!'
Memoization is a technique used to optimize functions by } },
caching the results of expensive function calls and fr: { translation: { welcome:
returning the cached result when the same inputs occur 'Bienvenue!' } }
again.
},
javascript
lng: 'en',
Copy code
fallbackLng: 'en',
// Example of memoization
interpolation: { escapeValue: false }
function memoize(func) {
});
const cache = {};
return function(...args) {
// Usage in components
const key = JSON.stringify(args);
function App() {
if (!cache[key]) {
const { t } = useTranslation();
cache[key] = func.apply(this,
return <h1>{t('welcome')}</h1>;
args);
}
}
return cache[key];

};
99. What are the differences between progressive
} enhancement and graceful degradation?
● Progressive enhancement involves starting with a
function fibonacci(n) { baseline of usable functionality and progressively
if (n <= 1) return n; enhancing it for browsers that support advanced features.
return fibonacci(n - 1) + fibonacci(n - 2); Graceful degradation starts with a full-featured
} experience and gracefully adapts to support less capable
browsers.

const memoizedFibonacci = memoize(fibonacci);


Progressive Enhancement Example:
console.log(memoizedFibonacci(10)); // Outputs: javascript
55 (result cached) Copy code
// Example of progressively enhanced
● feature
97. How do you handle responsive design with if (document.querySelector) {
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';

gsap.to('.element', { duration: 1, x: 100 });

You might also like