-
Notifications
You must be signed in to change notification settings - Fork 0
Interview Question JavaScript Part ‐ 1
JavaScript Interview Question
Answer: A closure is a function that retains access to its lexical scope, even when that function is executed outside of its original scope. Closures are created every time a function is created, at function creation time.
function outerFunction() {
let outerVariable = 'I am from outer function';
function innerFunction() {
console.log(outerVariable);
}
return innerFunction;
}
const myClosure = outerFunction();
myClosure(); // Output: "I am from outer function"Answer: == is the equality operator that performs type coercion, meaning it converts the operands to the same type before making the comparison. === is the strict equality operator that does not perform type coercion, so it only returns true if both the type and the value are the same.
5 == '5'; // true, because '5' is converted to 5
5 === '5'; // false, because the types are differentAnswer: var is function-scoped and can be redeclared and updated. let is block-scoped and can be updated but not redeclared within the same scope. const is also block-scoped but cannot be updated or redeclared; it must be initialized at the time of declaration.
function example() {
var x = 1;
if (true) {
var x = 2; // same variable
console.log(x); // 2
}
console.log(x); // 2
}
function exampleLet() {
let y = 1;
if (true) {
let y = 2; // different variable
console.log(y); // 2
}
console.log(y); // 1
}
const z = 3;
z = 4; // Error: Assignment to constant variableAnswer: The this keyword refers to the object that is currently executing the code. It allows methods to refer to their parent object and is determined at runtime based on the context in which a function is called.
const obj = {
name: 'John',
greet: function() {
console.log(this.name);
}
};
obj.greet(); // Output: 'John'
function globalGreet() {
console.log(this.name);
}
globalGreet.call(obj); // Output: 'John'Answer: Prototypal inheritance means that objects can inherit properties and methods from other objects. Each object has a private property (prototype) that links to another object. This allows one object to use the properties and methods of another.
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
console.log(`Hello, my name is ${this.name}`);
};
const john = new Person('John');
john.greet(); // Output: Hello, my name is JohnAnswer: Hoisting is JavaScript's behavior of moving declarations to the top of their containing scope during the compilation phase. This means that variable and function declarations are processed before any code is executed, but initializations are not hoisted.
console.log(x); // Output: undefined
var x = 5;
greet(); // Output: Hello
function greet() {
console.log('Hello');
}Answer: An IIFE is a function that is executed immediately after it is defined. It is used to create a local scope and avoid polluting the global namespace.
(function() {
var message = 'Hello, IIFE';
console.log(message);
})(); // Output: Hello, IIFE8. How do you handle asynchronous code in JavaScript? Explain the differences between callbacks, promises, and async/await.
Answer: Asynchronous code can be handled using callbacks, promises, and async/await.
- Callbacks: Functions passed as arguments to other functions and executed after some operation has been completed.
- Promises: Objects that represent the eventual completion (or failure) of an asynchronous operation and its resulting value.
- Async/Await: Syntactic sugar built on promises that allows for writing asynchronous code in a more synchronous fashion.
// Callbacks
function fetchData(callback) {
setTimeout(() => {
callback('Data received');
}, 1000);
}
fetchData((data) => {
console.log(data); // Output: Data received
});
// Promises
function fetchDataPromise() {
return new Promise((resolve) => {
setTimeout(() => {
resolve('Data received');
}, 1000);
});
}
fetchDataPromise().then((data) => {
console.log(data); // Output: Data received
});
// Async/Await
async function fetchDataAsync() {
const data = await fetchDataPromise();
console.log(data); // Output: Data received
}
fetchDataAsync();Answer: Event delegation is a technique where you use a single event listener to manage all events of a particular type for multiple elements. This is done by taking advantage of event bubbling.
document.getElementById('parent').addEventListener('click', (event) => {
if (event.target.matches('.child')) {
console.log('Child element clicked:', event.target);
}
});Answer: Objects in JavaScript can be created in several ways:
- Object literals
- The
Objectconstructor - The
newkeyword with a constructor function -
Object.createmethod - Classes (ES6 syntax)
// Object literal
const obj1 = { name: 'John' };
// Object constructor
const obj2 = new Object();
obj2.name = 'Jane';
// Constructor function
function Person(name) {
this.name = name;
}
const obj3 = new Person('Jim');
// Object.create
const proto = { greet: function() { console.log('Hello'); } };
const obj4 = Object.create(proto);
obj4.name = 'Jack';
// Classes
class Car {
constructor(model) {
this.model = model;
}
}
const obj5 = new Car('Toyota');Answer: null is an assignment value that means "no value" and must be assigned. undefined means a variable has been declared but has not yet been assigned a value.
let a;
console.log(a); // Output: undefined
let b = null;
console.log(b); // Output: nullAnswer: The event loop is a mechanism that allows JavaScript to perform non-blocking operations by offloading operations to the system kernel whenever possible. It continually checks the call stack and the message queue, processing messages (callbacks) from the queue only when the stack is empty.
Answer: You can prevent a default action in an event handler by calling the event.preventDefault() method.
document.querySelector('a').addEventListener('click', (event) => {
event.preventDefault();
console.log('Default action prevented');
});Answer: Arrow functions are a shorter syntax for writing functions in JavaScript. They do not have their own this, arguments, super, or new.target. Arrow functions are always anonymous and are best suited for non-method functions.
// Regular function
function add(a, b) {
return a + b;
}
// Arrow function
const addArrow = (a, b) => a + b;Answer: The module pattern is a design pattern used to encapsulate private and public methods and variables. It uses closures to create a private scope and exposes only the methods or variables that need to be public.
const Module = (function() {
let privateVar = 'I am private';
function privateMethod() {
console.log(privateVar);
}
return {
publicMethod: function() {
privateMethod();
}
};
})();
Module.publicMethod(); // Output: I am privateAnswer: The reduce method executes a reducer function on each element of the array, resulting in a single output value. The reducer function takes four arguments: accumulator, currentValue, currentIndex, and array.
const array = [1, 2, 3, 4];
const sum = array.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
}, 0);
console.log(sum); // Output: 10Answer: forEach executes a provided function once for each array element and does not return a new array. map executes a provided function once for each array element and returns a new array with the results.
const array = [1, 2, 3, 4];
// forEach
array.forEach((element) => {
console.log(element);
});
// map
const doubled = array.map((element) => {
return element * 2;
});
console.log(doubled); // Output: [2, 4, 6, 8]Answer: These methods are used to set the this context for a function.
-
bindcreates a new function with a specifiedthisvalue and arguments. -
callinvokes a function with a specifiedthisvalue and arguments. -
applyis similar tocall, but takes arguments as an array.
function greet(greeting, punctuation) {
console.log(`${greeting}, ${this.name}${punctuation}`);
}
const person = { name: 'John' };
const boundGreet = greet.bind(person);
boundGreet('Hello', '!'); // Output: Hello, John!
greet.call(person, 'Hi', '?'); // Output: Hi, John?
greet.apply(person, ['Hey', '.']); // Output: Hey, John.Answer: Exceptions in JavaScript are handled using try...catch blocks. The try block contains code that may throw an error, and the catch block contains code to handle the error.
try {
// Code that may throw an error
let result = riskyFunction();
} catch (error) {
console.log('An error occurred:', error.message);
}Answer: Higher-order functions are functions that can take other functions as arguments or return functions as their result. They are a key concept in functional programming.
function higherOrderFunction(callback) {
return function(value) {
return callback(value);
};
}
const double = higherOrderFunction((x) => x * 2);
console.log(double(5)); // Output: 10These detailed answers should give a comprehensive understanding of each concept.