0% found this document useful (0 votes)
0 views6 pages

java script interview questions ❓

Uploaded by

xyank2734
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)
0 views6 pages

java script interview questions ❓

Uploaded by

xyank2734
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/ 6

Here are the answers to the JavaScript interview questions:

1. What is JavaScript?

 JavaScript is a high-level, interpreted programming language primarily used for making web
pages interactive. It is an essential part of web technologies alongside HTML and CSS.
JavaScript is versatile and supports functional, object-oriented, and event-driven
programming styles.

2. What are the data types supported by JavaScript?

 JavaScript supports the following data types:

1. Primitive types: string, number, boolean, undefined, null, symbol, and bigint.
2. Non-primitive types: object, including arrays, functions, and dates.

3. What is the difference between let, const, and var?

 var: Function-scoped or globally scoped, allows redeclaration, and can be hoisted.


 let: Block-scoped, does not allow redeclaration, but can be reassigned.
 const: Block-scoped, cannot be redeclared or reassigned, but if it’s an object or array, the
contents can be mutated.

4. Explain how == and === differ.

 ==: Loose equality operator; checks for equality after performing type conversion.
 ===: Strict equality operator; checks for equality without type conversion, meaning both the
value and type must be the same.

5. What is a closure?

 A closure is a function that remembers and accesses variables from its lexical scope, even
when it’s executed outside that scope.

js
function outer() {
let count = 0;
return function inner() {
count++;
return count;
};
}const increment = outer();console.log(increment()); // 1console.log(increment()); //
2

6. What is hoisting?

 Hoisting is JavaScript's default behavior of moving declarations (variables and functions) to


the top of their scope before execution. This means variables declared with var can be used
before they are defined, though their value will be undefined.
7. Explain the concept of "this" in JavaScript.

 this refers to the object that is currently executing the function. The value of this depends on
how the function is called:

o In a method, this refers to the object.


o In a regular function, this refers to the global object (window in browsers).
o In strict mode, this is undefined in regular functions.
o In arrow functions, this is lexically scoped and refers to the surrounding context.

8. What are JavaScript prototypes?

 Prototypes are objects from which other objects inherit properties. Every JavaScript object
has a prototype, and objects inherit methods and properties from their prototype.

9. What is the difference between null and undefined?

 undefined means a variable has been declared but has not been assigned a value.
 null is an assignment value that represents the intentional absence of any object value.

10. How does JavaScript handle asynchronous operations?

 JavaScript handles asynchronous operations using:

o Callbacks
o Promises
o async/await These mechanisms allow JavaScript to perform non-blocking
operations, such as fetching data from an API without freezing the UI.

11. What is a promise?

 A promise represents the eventual completion (or failure) of an asynchronous operation and
its resulting value. It can be in one of three states: pending, fulfilled, or rejected.

12. What are async/await functions?

 async/await is syntactic sugar over promises, providing a cleaner way to write asynchronous
code. async functions return a promise, and await is used to pause the execution until the
promise resolves.

13. Explain event delegation in JavaScript.

 Event delegation allows you to handle events at a higher level in the DOM rather than
adding event listeners to individual elements. This takes advantage of event bubbling, where
an event triggered on a child element bubbles up to its parent elements.

Js
document.querySelector('#parent').addEventListener('click', function(event) {
if (event.target.matches('.child')) {
// Handle click on child element
}
});

14. What are JavaScript modules?

 Modules are reusable blocks of code that can be imported/exported between files. They
help in organizing code better by separating functionality.

js
// export.jsexport const myFunction = () => {};// import.jsimport { myFunction } from
'./export.js';

15. How can you prevent a function from being called multiple times?

 You can prevent multiple calls using debouncing or throttling techniques. Debouncing delays
function execution until after a certain amount of time has passed. Throttling ensures a
function is called at most once every specified period.

js
function debounce(func, delay) {
let timer;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => func.apply(this, args), delay);
};
}

16. What is the event loop?

 The event loop is the mechanism that allows JavaScript to handle asynchronous code. It
continuously checks the call stack and task queues (microtasks, macrotasks) to execute the
pending tasks after the main thread is free.

17. What is the difference between apply() and call() methods?

 Both apply() and call() invoke functions with a given this value, but:

o call() accepts arguments one by one.


o apply() accepts arguments as an array.

18. What is bind() method used for?

 The bind() method creates a new function that, when called, has its this value set to the
provided context. It allows us to explicitly bind a specific context to a function, useful in
callbacks.

js
const obj = { x: 10 };function getX() { return this.x; }const boundGetX =
getX.bind(obj);console.log(boundGetX()); // 10
19. What is a JavaScript event loop?

 The event loop is responsible for managing asynchronous callbacks in JavaScript. It processes
the call stack and the callback queue, ensuring that asynchronous tasks (like timers and I/O
operations) are executed after the current call stack is clear.

20. Explain the concept of "event bubbling" and "event capturing".

 Event bubbling: When an event is triggered, it propagates from the innermost element
(where the event occurred) up to the outer elements.
 Event capturing: The reverse of bubbling, where the event is first captured by the outermost
element and propagates down to the target element.

21. What is the difference between deep copy and shallow copy?

 Shallow copy: Copies the reference of nested objects, so changes in the copy reflect in the
original.
 Deep copy: Duplicates every level of an object, so the original and the copy are independent.

js
const shallowCopy = Object.assign({}, obj); // Shallow copyconst deepCopy =
JSON.parse(JSON.stringify(obj)); // Deep copy

22. What are generator functions?

 Generator functions are functions that can be paused and resumed. They return a generator
object that can be iterated over using the next() method.

js
function* generator() {
yield 1;
yield 2;
return 3;
}const gen = generator();console.log(gen.next()); // { value: 1, done: false }

23. What is the new keyword used for?

 The new keyword is used to create an instance of an object with a constructor function. It
sets up the inheritance chain and allows new properties to be added to the instance.

24. How do JavaScript’s setTimeout and setInterval work?

 setTimeout: Executes a function once after a specified delay.


 setInterval: Repeatedly executes a function at fixed time intervals.

js
setTimeout(() => console.log('Executed after delay'), 1000);setInterval(() =>
console.log('Repeated every second'), 1000);
25. What is a WeakMap and how is it different from a Map?

 A WeakMap holds key-value pairs where keys are objects and are weakly referenced,
meaning if there are no other references to the object, the garbage collector can reclaim it.
 In contrast, Map keeps strong references to objects, preventing garbage collection.

26. What is a Set in JavaScript?

 A Set is a collection of unique values in JavaScript. It automatically removes duplicate values


and maintains the order of insertion.
 Key properties:
o Values are unique.
o You can iterate over the elements.
o Common methods include add(), has(), delete(), and clear().

js
const mySet = new Set([1, 2, 3, 3, 4]);console.log(mySet); // Set { 1, 2, 3, 4 }

27. What is Object.create() used for?

 Object.create() creates a new object using an existing object as the prototype of the newly
created object. It allows for setting up inheritance in a clean way.

js
const parent = { name: 'Parent' };const child =
Object.create(parent);console.log(child.name); // 'Parent'

28. How does JavaScript’s garbage collection work?

 JavaScript’s garbage collection is an automatic memory management process. The engine


periodically checks for objects that are no longer referenced by any part of the program and
frees the memory associated with those objects. The primary technique used is mark-and-
sweep, where unreachable objects are marked for removal.

29. What are "decorators" in JavaScript?

 Decorators are a feature proposal in JavaScript (not yet a standard) that allows you to
modify classes, methods, or properties in a declarative way. They are functions that can be
applied to classes or methods to enhance or modify their behavior.

js
function log(target, key, descriptor) {
const originalMethod = descriptor.value;
descriptor.value = function (...args) {
console.log(`Method ${key} called with args:`, args);
return originalMethod.apply(this, args);
};
return descriptor;
}
class Example {
@log
method(val) {
return val;
}
}

30. Explain the difference between prototype and __proto__.

 prototype: It is a property of constructor functions (functions used to create objects) and is


an object that is shared by all instances of that constructor. It allows for inheritance and
sharing methods and properties across all instances.
 __proto__: It is an internal property of all objects, pointing to the prototype of the object’s
constructor function. It is the mechanism by which objects inherit properties and methods
from their prototype chain.

In simpler terms:

 prototype is for functions/constructors, allowing them to define properties and methods that
their instances can inherit.
 __proto__ is for instances, referring to the prototype object from which the instance was
derived.

js
function Person(name) {
this.name = name;
}Person.prototype.greet = function() {
console.log('Hello, ' + this.name);
};
const john = new Person('John');
john.greet(); // 'Hello, John'console.log(john.__proto__ === Person.prototype); //
true

You might also like