Basic JavaScript Questions
- Q: What is JavaScript?
A: JavaScript is a lightweight, interpreted programming language that is primarily used for creating interactive effects within web browsers.
- Q: What are the different data types in JavaScript?
A: The basic data types in JavaScript are undefined
, null
, boolean
, number
, string
, bigint
, and symbol
.
- Q: What is the difference between
let
, const
, and var
?
A: var
is function-scoped or globally scoped, let
is block-scoped and can be reassigned, while const
is also block-scoped but cannot be reassigned.
- Q: What is a closure in JavaScript?
A: A closure is a function that retains access to its lexical scope, even when the function is executed outside that scope.
- Q: What are arrow functions?
A: Arrow functions are a shorthand syntax for writing function expressions in JavaScript, and they do not have their own this
context.javascriptconst add = (a, b) => a + b;
- Q: How do you declare a function in JavaScript?
A: You can declare a function using the function keyword:javascriptfunction myFunction() { // Code here }
- Q: What is the purpose of the
this
keyword?
A: The this
keyword refers to the context in which a function is called, pointing to the object that the function is a property of.
- Q: Explain event bubbling and event capturing.
A: Event bubbling is when an event starts from the target element and bubbles up to the root, while event capturing is the opposite, where the event starts from the root and goes down to the target.
- Q: How do you create an object in JavaScript?
A: You can create an object using object literal notation, constructor functions, or the class
keyword.javascriptconst myObj = { key: "value" };
- Q: What is the difference between
==
and ===
?
A: ==
is an equality operator that performs type coercion, while ===
is a strict equality operator that does not perform type coercion.
Intermediate JavaScript Questions
- Q: What is hoisting in JavaScript?
A: Hoisting refers to the JavaScript mechanism where variables and function declarations are moved to the top of their containing scope during the compile phase.
- Q: What is the
bind
method?
A: The bind
method creates a new function that, when called, has its this
keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
- Q: Explain the concept of promises.
A: A promise is an object that 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.
- Q: What are async/await in JavaScript?
A: async/await
is a syntax that makes it easier to work with Promises by allowing asynchronous code to be written in a synchronous style.
- Q: What is the difference between
slice
and splice
?
A: slice
returns a shallow copy of a portion of an array, while splice
changes the contents of an array by removing or replacing existing elements and/or adding new elements.
- Q: What are higher-order functions?
A: Higher-order functions are functions that take other functions as arguments or return functions as their result.
- Q: How do you handle exceptions in JavaScript?
A: Exceptions can be handled using try
, catch
, and finally
statements.javascripttry { // Code that may throw an error } catch (error) { // Handle the error } finally { // Always executed }
- Q: What is the event loop in JavaScript?
A: The event loop is a mechanism that allows JavaScript to perform non-blocking operations by using a single thread to handle multiple tasks, including executing code, collecting and processing events, and executing queued sub-tasks.
- Q: What are template literals?
A: Template literals are string literals that allow embedded expressions, using backticks (`) instead of quotes:javascriptconst name = "John"; const greeting = `Hello, ${name}!`;
- Q: Explain the difference between an array and an object in JavaScript.
A: An array is an ordered collection of values, while an object is a collection of key-value pairs. Arrays are typically used for lists, and their elements can be accessed by index, whereas objects are accessed by keys.
Advanced JavaScript Questions
- Q: What is the purpose of the
console
object?
A: The console
object provides access to the browser’s debugging console, allowing developers to log information, errors, and debugging messages.
- Q: Explain the concept of
this
binding.
A: The context of this
is determined by how a function is called. It can be bound explicitly using call
, apply
, or bind
, or it is determined implicitly in the case of methods and constructors.
- Q: What is the difference between synchronous and asynchronous programming?
A: Synchronous programming executes tasks sequentially, while asynchronous programming allows tasks to run concurrently, enabling better performance for I/O operations.
- Q: How can you optimize JavaScript performance?
A: Performance can be optimized by minimizing DOM manipulations, using event delegation, caching values, using efficient algorithms, and minimizing network requests.
- Q: What is a JavaScript module?
A: A module is a self-contained unit of code that encapsulates functionality, typically exporting and importing features for use in other parts of an application.
- Q: What is the purpose of the
fetch
API?
A: The fetch
API is used to make network requests similar to XMLHttpRequest
but with a more powerful and flexible feature set, returning Promises.
- Q: How do you create a promise?
A: A promise can be created using the Promise
constructor, which takes a function with resolve
and reject
as parameters.javascriptconst myPromise = new Promise((resolve, reject) => { // Asynchronous operation });
- Q: What is the difference between
call
, apply
, and bind
?
A: call
and apply
are used to call functions with a specific this
context, with call
taking arguments individually and apply
taking an array of arguments. bind
creates a new function with a fixed this
context.
- Q: Explain how the prototype chain works in JavaScript.
A: In JavaScript, objects inherit properties and methods from other objects through the prototype chain, allowing for property lookup via the prototype of the object.
- Q: What is the purpose of the
localStorage
and sessionStorage
?
A: localStorage
and sessionStorage
are part of the Web Storage API, used for storing data in the clientтАЩs browser. localStorage
persists even after the browser is closed, while sessionStorage
is limited to the duration of a page session.
JavaScript Functional Programming
- Q: What is functional programming in JavaScript?
A: Functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions, avoiding state and mutable data. It emphasizes the use of functions as first-class citizens.
- Q: What are pure functions?
A: Pure functions are functions that always return the same output for the same inputs and do not have side effects.
- Q: What is currying?
A: Currying is the technique of transforming a function with multiple arguments into a series of functions that each take a single argument.
- Q: What are IIFEs (Immediately Invoked Function Expressions)?
A: IIFEs are functions that are defined and immediately executed. They allow for the creation of a scope to encapsulate variables.javascript(function() { // Code here })();
- Q: How is
Array.prototype.map()
different from Array.prototype.forEach()
?
A: map()
creates a new array populated with the results of calling a provided function on every element, while forEach()
executes the provided function once for each array element without returning a new array.
Object-Oriented JavaScript
- Q: How do you create a class in JavaScript?
A: A class is created using the class
keyword, followed by a class body:javascriptclass MyClass { constructor() { // Initialization } }
- Q: What is inheritance in JavaScript?
A: Inheritance is a mechanism that allows a class (child) to inherit properties and methods from another class (parent), enabling code reuse and extension.
- Q: What is encapsulation in JavaScript?
A: Encapsulation is a principle of restricting access to certain details of an object to protect its integrity, which can be achieved using closures and private fields in ES2022.
- Q: Explain what static methods are.
A: Static methods belong to the class itself rather than instances of the class and are called on the class directly:javascriptclass MyClass { static myStaticMethod() { // Code here } }
- Q: What is the
instanceof
operator?
A: The instanceof
operator is used to test whether an object is an instance of a specific class or constructor function.javascriptobj instanceof MyClass; // returns true or false
Advanced Concepts
- Q: What is the purpose of Web Workers?
A: Web Workers allow for running scripts in background threads, enabling parallel processing and preventing the main thread from being blocked, improving performance for computationally intensive operations.
- Q: What is the Shadow DOM?
A: The Shadow DOM is a web standard that allows developers to encapsulate a piece of DOM and CSS styles, providing isolated scopes for styles, preventing style conflicts.
- Q: What is Functional Reactive Programming (FRP)?
A: FRP is a paradigm for building interactive applications that respond to data changes over time using functional programming principles, commonly implemented using libraries like RxJS.
- Q: How do you optimize large applications in JavaScript?
A: Optimization can be achieved through techniques such as code splitting, lazy loading, tree shaking, optimizing asset sizes, and using efficient algorithms and data structures.
- Q: What are mixins in JavaScript?
A: Mixins are a way to add functionality from one class to another without using inheritance, allowing classes to share behavior:javascriptconst Mixin = { method() { // Behavior } }; class MyClass {} Object.assign(MyClass.prototype, Mixin);
- Q: What is the purpose of
Proxy
in JavaScript?
A: Proxy
is a built-in object that enables you to create a proxy for another object, allowing you to intercept and customize operations performed on that object (like property access, assignment, etc.).
- Q: How does the
Reflect
API work in JavaScript?
A: The Reflect
API provides methods for interceptable JavaScript operations, allowing for more controlled manipulation of objects and facilitating the work with proxies.
- Q: What are service workers?
A: Service workers are scripts that run in the background, separate from the web page, providing features like push notifications, background sync, and network proxying, enabling offline experiences.
- Q: What is the CSS Object Model (CSSOM)?
A: CSSOM is a set of APIs to manipulate CSS stylesheets and rules through JavaScript, allowing for dynamic changes to the appearance of web pages.
- Q: What is the purpose of the
Promise.all()
method?
A: Promise.all()
takes an array of Promises and returns a single Promise that resolves when all of the provided Promises have resolved, or rejects if any Promise is rejected.
Practical Implementation Questions
- Q: How can you measure the performance of a JavaScript application?
A: You can measure performance using the Performance
API, which provides methods to capture timestamps, monitor resource loading times, and analyze application performance metrics.
- Q: Describe how debouncing and throttling works.
A: Debouncing limits the rate at which a function can be called by only executing it after a specified delay, while throttling ensures a function is executed at most once in a specified time interval.
- Q:┬аWhat are the common methods to prevent XSS attacks?
A:┬аTo prevent XSS (Cross-Site Scripting) attacks, sanitize input, escape output, use Content Security Policy (CSP), and validate user input
Preventing XSS Attacks
- Q: What are common methods to prevent XSS attacks?
A: To prevent XSS (Cross-Site Scripting) attacks, you can:
- Sanitize user input by removing or escaping harmful characters.
- Escape output when rendering user-supplied content.
- Implement Content Security Policy (CSP) to restrict the sources from which scripts can be executed.
- Use JavaScript libraries that automatically handle escaping, such as React or Angular.
Practical Implementation Questions (Continued)
- Q: How can you handle errors in asynchronous code?
A: You can handle errors in asynchronous code by using try/catch
blocks within async
functions, or by chaining catch()
methods to Promises.
- Q: What is a Singleton pattern, and how can you implement it in JavaScript?
A: A Singleton pattern restricts a class to a single instance. You can implement it in JavaScript using closures to encapsulate the instance:
javascriptconst Singleton = (function() {
let instance;
function createInstance() {
return { /* instance properties */ };
}
return {
getInstance: function() {
if (!instance) {
instance = createInstance();
}
return instance;
}
};
})();
- Q: Explain the concept of a JavaScript throttle function.
A: A throttle function limits the number of times a function can execute over time. For instance, it allows a function to execute at most once in a specified duration:
javascriptfunction throttle(func, limit) {
let lastFunc;
let lastRan;
return function() {
const context = this;
const args = arguments;
if (!lastRan) {
func.apply(context, args);
lastRan = Date.now();
} else {
clearTimeout(lastFunc);
lastFunc = setTimeout(function() {
if (Date.now() - lastRan >= limit) {
func.apply(context, args);
lastRan = Date.now();
}
}, limit - (Date.now() - lastRan));
}
};
}
- Q: How do you create a custom event in JavaScript?
A: You can create a custom event using the CustomEvent
constructor. This allows you to dispatch and listen to the event within your application:
javascriptconst event = new CustomEvent('myEvent', { detail: { key: 'value' } });
document.dispatchEvent(event);
- Q: What are the differences between
addEventListener
and inline event handlers?
A: addEventListener
allows multiple event listeners to be attached to a single element and supports capturing and bubbling phases, while inline event handlers are directly defined in HTML elements and limit flexibility.
- Q: Explain the concept of deep cloning an object in JavaScript.
A: Deep cloning creates a new object that is a complete copy of an existing object, including nested objects. This can be achieved using libraries like Lodash (_.cloneDeep()
) or by using structured cloning (available via structuredClone()
in modern browsers). HereтАЩs a simple method using JSON:
javascriptconst cloneDeep = (obj) => JSON.parse(JSON.stringify(obj));
Miscellaneous Questions
- Q: What are the potential issues with using
eval()
in JavaScript?
A: Using eval()
can lead to security vulnerabilities (XSS attacks), performance issues, and debugging difficulties, as it executes code in the current scope.
- Q: Describe how to implement pagination in JavaScript.
A: Pagination can be implemented by managing the data displayed based on user interaction (e.g., “Next” and “Previous” buttons) and slicing the data set according to the current page:
javascriptfunction paginate(array, page_size, page_number) {
return array.slice((page_number - 1) * page_size, page_number * page_size);
}
- Q: Explain the concept of cross-origin resource sharing (CORS).
A: CORS is a security feature implemented by browsers to prevent web pages from making requests to a different domain than the one that served the page, unless explicitly allowed by the server through HTTP headers.
- Q: How can you prevent the default action of an event in JavaScript?
A: You can prevent the default action of an event using the event.preventDefault()
method within the event handler:
javascriptdocument.querySelector('form').addEventListener('submit', function(event) {
event.preventDefault(); // Prevent the form from submitting
});
- Q: What is lazy loading in JavaScript?
A: Lazy loading is a design pattern that postpones loading of resources until they are actually needed, which can significantly improve performance and reduce initial load times.
Advanced Topics and Concepts
- Q: What is the difference between a
WeakMap
and a Map
?
A: A WeakMap
holds weak references to its keys, allowing for garbage collection of keys when there are no other references to them. In contrast, a Map
holds strong references, meaning its keys cannot be garbage collected as long as the map exists.
- Q: Explain how the
set
data structure works in JavaScript.
A: A Set
is a built-in object that stores unique values of any type, whether primitive values or object references. It provides methods like add()
, delete()
, and has()
.
javascriptconst mySet = new Set();
mySet.add(1);
mySet.add(2);
- Q: What is the performance implication of using templating engines in JavaScript?
A: Templating engines can improve developer productivity and maintainability when rendering dynamic HTML. However, they might negatively impact performance if not optimized, as they introduce additional parsing and rendering overhead.
- Q: Describe JavaScript’s
new
operator.
A: The new
operator creates a new instance of an object, essentially as follows: it creates a new object, binds this
to the new object, executes the constructor function, and returns the new object (unless the constructor returns an object).
- Q: What is the Observer design pattern?
A: The Observer pattern is a behavioral design pattern where an object (subject) maintains a list of its dependents (observers) and notifies them automatically of any state changes, promoting a subscription-based model. It can be implemented using EventListeners in JavaScript.
More Advanced and Technical Questions
- Q: What is the purpose of the
reduce()
method in arrays?
A: The reduce()
method executes a reducer function on each element of the array, resulting in a single output value, which can be useful for summation, flattening arrays, or transforming data structures.
javascriptconst sum = [1, 2, 3].reduce((acc, cur) => acc + cur, 0); // 6
- Q: How can you detect memory leaks in JavaScript?
A: Memory leaks can be detected using browser developer tools by monitoring heap snapshots and analyzing the retained objects over time. Tools like the Chrome DevTools Performance tab can also help identify potential leaks through profiling.
- Q: What are JavaScript modules, and how do you create them?
A: JavaScript modules are reusable pieces of code that can export and import various values (functions, objects, etc.) between different files using export
and import
statements.
javascript// myModule.js
export const myFunction = () => { /* implementation */ };
// main.js
import { myFunction } from './myModule.js';
- Q: What is the purpose of the
window.onload
method?
A: The window.onload
event is triggered when the entire page (including all dependent resources such as stylesheets and images) has fully loaded, making it a suitable place to run scripts that require the DOM to be fully rendered.
- Q: Explain how you would implement a simple cache in JavaScript.
A: A simple cache can be implemented using an object or a Map
, storing key-value pairs that can be retrieved and set as needed. For example:
javascriptconst cache = {};
function getCachedData(key) {
return cache[key] || null;
}
function setCachedData(key, value) {
cache[key] = value;
}
Closing Questions
- Q: What are some key differences between ES5 and ES6?
A: Key differences include the introduction of let
and const
for variable declarations, arrow functions, template literals, destructuring assignment, and the class
syntax. ES6 also introduced Promises and modules.
- Q: How can you implement a simple routing mechanism in a single-page application (SPA)?
A: You can implement routing in an SPA by using the History API
to manipulate the browser’s history and render content based on the current URL:
javascriptwindow.addEventListener('popstate', (event) => {
renderPage(event.state);
});
- Q: Describe the concept of “first-class functions” in JavaScript.
A: In JavaScript, functions are first-class citizens, meaning they can be treated like any other variable: they can be assigned to variables, passed as arguments to other functions, returned from functions, and stored in data structures.
- Q: What is the
Object.freeze()
method used for?
A: Object.freeze()
prevents new properties from being added to an object and existing properties from being removed or modified, effectively making the object immutable.
- Q: What are the typical use cases for using
setTimeout()
and setInterval()
?
A: setTimeout()
is used to delay the execution of a function once after a specified duration, while setInterval()
is used to repeatedly execute a function at specified intervals until it is stopped.
Additional Questions
- Q: How can you create a recursive function in JavaScript?
A: A recursive function is a function that calls itself to solve a smaller instance of the same problem until a base condition is met:
javascriptfunction factorial(n) {
return n <= 1 ? 1 : n * factorial(n - 1);
}
- Q: How do you manage state in a JavaScript application?
A: State management can be achieved through various patterns and libraries, including local states within components, centralized state management using libraries like Redux or MobX, and context API in React.
- Q: What is the difference between synchronous and asynchronous iteration?
A: Synchronous iteration processes items one at a time, blocking subsequent operations until each item is processed. Asynchronous iteration allows operations to occur concurrently and can be paused and resumed, often utilizing Promises or async generators.
- Q: What are JavaScript decorators?
A: Decorators are functions that modify or enhance the behavior of classes, methods, or properties, often used in frameworks like Angular and TypeScript (still a proposal in standard JavaScript).
- Q: What is the significance of
Array.prototype.filter()
?
A: filter()
creates a new array with all elements that pass the test implemented by the provided function, facilitating the creation of subsets of arrays based on specific conditions.
- Q: Describe how to implement a simple debounce utility function.
A: A debounce function prevents a function from being called repeatedly within a specified timeframe:
javascriptfunction debounce(func, delay) {
let timeout;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, args), delay);
};
}
- Q: What is the purpose of
Symbol
in JavaScript?
A: Symbol
is a primitive data type used to create unique identifiers for object properties, reducing the chance of property name collisions.
javascriptconst mySymbol = Symbol('description');
- Q: How can you check for array equality in JavaScript?
A: To check for array equality, you can compare their lengths and values recursively, or use techniques like JSON.stringify()
or libraries like Lodash for deep comparisons.
- Q: Explain how you would implement a simple event system.
A: You can implement an event system using a central object to manage events and their corresponding listeners:
javascriptconst eventSystem = {
events: {},
on(event, listener) {
if (!this.events[event]) {
this.events[event] = [];
}
this.events[event].push(listener);
},
emit(event, data) {
if (this.events[event]) {
this.events[event].forEach(listener => listener(data));
}
}
};
- Q: What is the
typeof
operator used for?
A: The typeof
operator returns a string indicating the type of a variable, useful for type checking in JavaScript:
javascriptconsole.log(typeof "Hello"); // "string"
Final Questions
- Q: How can you implement a simple pub/sub pattern in JavaScript?
A: The publish/subscribe pattern allows objects to subscribe to events and get notified when those events are published:
javascriptconst PubSub = {
events: {},
subscribe(event, listener) {