Basics
What is JavaScript?
- JavaScript is a high-level, interpreted scripting language used primarily to create dynamic and interactive effects in web browsers.
What are the different data types in JavaScript?
- String, Number, BigInt, Boolean, Undefined, Null, Object, Symbol.
What is the difference between
==
and===
?==
checks for equality with type coercion, while===
checks for equality without type coercion.
How do you declare a variable in JavaScript?
- Using
var
,let
, orconst
. Example:let x = 10;
- Using
What is a function in JavaScript?
- A function is a block of code designed to perform a particular task, executed when it is invoked.
What is a closure?
- A closure is a function that retains access to its lexical scope, even when the function is executed outside that scope.
What is the difference between
null
andundefined
?null
is an assignment value representing no value or object, whileundefined
means a variable has been declared but not assigned a value.
What is the purpose of
this
in JavaScript?this
refers to the object that is executing the current function.
How does JavaScript handle asynchronous operations?
- JavaScript uses callbacks, Promises, and Async/Await for handling asynchronous operations.
What is event bubbling?
- Event bubbling is a mechanism where events propagate from the target element up to the root element.
Intermediate
What are JavaScript prototypes?
- Prototypes are a way to achieve inheritance in JavaScript by adding methods and properties to an object's prototype.
What is the event loop in JavaScript?
- The event loop is a mechanism that allows JavaScript to perform non-blocking operations by executing code in response to events.
What are Promises in JavaScript?
- Promises are objects representing the eventual completion (or failure) of an asynchronous operation and its resulting value.
What is the purpose of
async
andawait
?async
andawait
simplify working with Promises by allowing asynchronous code to be written in a synchronous style.
What is the difference between
let
andconst
?let
allows reassignment, whileconst
does not allow reassignment after the variable is initialized.
What is a higher-order function?
- A higher-order function is a function that takes one or more functions as arguments or returns a function.
Explain the concept of "hoisting".
- Hoisting is JavaScript's default behavior of moving declarations to the top of their scope before code execution.
What are arrow functions?
- Arrow functions provide a shorter syntax for writing functions and do not have their own
this
context.
- Arrow functions provide a shorter syntax for writing functions and do not have their own
What is a callback function?
- A callback function is a function passed into another function as an argument to be executed later.
How can you create an object in JavaScript?
- Using object literals
{}
, constructorsnew Object()
, or theObject.create()
method.
- Using object literals
Advanced
What is the difference between
call()
,apply()
, andbind()
?call()
andapply()
invoke a function with a specifiedthis
value and arguments, whilebind()
returns a new function with a specifiedthis
value and initial arguments.
What are JavaScript modules?
- JavaScript modules allow code to be split into separate files with
import
andexport
statements for better organization and reuse.
- JavaScript modules allow code to be split into separate files with
What is the
Symbol
type?Symbol
is a unique and immutable primitive value used as an identifier for object properties.
How do you handle errors in JavaScript?
- Using
try...catch
blocks to handle exceptions andfinally
to execute code regardless of the outcome.
- Using
What is the
arguments
object?- The
arguments
object is an array-like object available within functions that contains all the arguments passed to the function.
- The
What are
Set
andMap
in JavaScript?Set
is a collection of unique values, whileMap
is a collection of key-value pairs with keys of any type.
What is the
Object.freeze()
method?Object.freeze()
prevents modifications to an object, making it immutable.
What is the difference between
Object.seal()
andObject.preventExtensions()
?Object.seal()
prevents adding or removing properties but allows modifications, whileObject.preventExtensions()
only prevents adding new properties.
What is the difference between
apply()
andbind()
?apply()
immediately invokes the function with a giventhis
value and arguments, whilebind()
returns a new function with a specifiedthis
value and initial arguments.
What is the
Proxy
object?Proxy
is an object that allows you to define custom behavior for fundamental operations (e.g., property lookup, assignment, enumeration).
DOM and Browser
What is the DOM?
- The Document Object Model (DOM) is a programming interface for web documents that represents the structure of a document as a tree of objects.
How can you manipulate the DOM using JavaScript?
- By using methods like
getElementById()
,querySelector()
,createElement()
, and manipulating properties and methods of DOM nodes.
- By using methods like
What is the difference between
innerHTML
andtextContent
?innerHTML
gets or sets the HTML content of an element, whiletextContent
gets or sets the text content, ignoring HTML tags.
What is event delegation?
- Event delegation is a technique where a single event handler is attached to a parent element to manage events for its child elements.
What is
document.createElement()
used for?- It creates a new HTML element specified by the tag name provided.
What is
localStorage
andsessionStorage
?localStorage
persists data across sessions, whilesessionStorage
only persists data for the duration of the page session.
What is
fetch()
?fetch()
is a modern API for making network requests, returning a Promise that resolves with the Response object.
What are
XMLHttpRequest
andfetch()
?- Both are used for making network requests, but
fetch()
is more modern and provides a simpler API.
- Both are used for making network requests, but
What is the difference between
clientHeight
andoffsetHeight
?clientHeight
is the height of an element including padding but not borders, whileoffsetHeight
includes padding, borders, and scrollbars.
What are
window.onload
anddocument.onload
?window.onload
fires when the entire page (including images and iframes) has loaded, whiledocument.onload
fires when the DOM is fully loaded.
Performance and Optimization
How can you improve the performance of a JavaScript application?
- By optimizing code, reducing DOM manipulation, using lazy loading, minimizing reflows and repaints, and using Web Workers.
What are Web Workers?
- Web Workers allow JavaScript to run in background threads, enabling multi-threaded processing.
What is a memory leak in JavaScript?
- A memory leak occurs when memory is not released properly, leading to increased memory usage and potential performance issues.
How can you prevent memory leaks in JavaScript?
- By ensuring proper garbage collection, avoiding global variables, and removing event listeners and references to unused objects.
What is "debouncing" and "throttling"?
- Debouncing limits the rate at which a function is executed by waiting for a pause in events, while throttling ensures a function is called at most once in a specified time interval.
What is lazy loading?
- Lazy loading is a design pattern where resources are loaded only when needed, improving initial page load performance.
What is a "reflow" and "repaint"?
- Reflow is the process of recalculating the layout of elements, while repaint involves redrawing parts of the page.
What is the
requestAnimationFrame()
method?- It schedules a function to be called before the next repaint, making it suitable for animations.
What is code splitting?
- Code splitting is a technique where JavaScript code is divided into chunks to be loaded on demand, improving load times.
What are the best practices for optimizing JavaScript performance?
- Minimize DOM manipulations, use event delegation, cache DOM references, and optimize loops and function calls.
ES6 and Beyond
What are template literals?
- Template literals allow for embedded expressions and multi-line strings using backticks (
`
).
- Template literals allow for embedded expressions and multi-line strings using backticks (
What are default parameters in functions?
- Default parameters provide default values for function parameters if no value or
undefined
is passed.
- Default parameters provide default values for function parameters if no value or
What is destructuring assignment?
- Destructuring assignment allows unpacking values from arrays or properties from objects into distinct variables.
What are spread and rest operators?
- The spread operator (
...
) expands iterables into individual elements, while the rest operator collects multiple elements into an array.
- The spread operator (
What is the
class
syntax in JavaScript?class
syntax provides a way to create objects and handle inheritance using a more traditional OOP approach.
What are
Map
andSet
in ES6?Map
is a collection of key-value pairs, andSet
is a collection of unique values.
What is the
Symbol
type used for?- Symbols are unique and immutable primitives used as property keys to avoid name collisions.
What are
async
functions?async
functions are functions that always return a Promise and allow for easier handling of asynchronous code withawait
.
What is the
Object.assign()
method?Object.assign()
copies values from one or more source objects to a target object.
What are
WeakMap
andWeakSet
?WeakMap
andWeakSet
are collections that hold weak references to objects, allowing for garbage collection of unused elements.
Advanced Concepts
What is the
Reflect
API?- The
Reflect
API provides methods to interact with and manipulate JavaScript objects, including traps for meta-programming.
- The
What is a
Proxy
object and how is it used?Proxy
objects enable custom behavior for fundamental operations such as property lookup, assignment, and function invocation.
What are
generators
in JavaScript?- Generators are functions that can be paused and resumed, using
yield
to produce a sequence of values.
- Generators are functions that can be paused and resumed, using
What is the
WeakRef
object?WeakRef
provides a way to hold a weak reference to an object, allowing it to be garbage collected when no other references exist.
What are tagged template literals?
- Tagged template literals allow custom processing of template literals by prefixing them with a function.
How does JavaScript's garbage collection work?
- JavaScript uses automatic garbage collection to manage memory, reclaiming memory occupied by objects that are no longer reachable.
What are
for...of
andfor...in
loops?for...of
iterates over iterable objects (like arrays), whilefor...in
iterates over enumerable properties of an object.
What is
Object.defineProperty()
?Object.defineProperty()
defines a new property or modifies an existing property on an object, with configurable attributes.
What is the difference between
Object.create()
andnew
?Object.create()
creates a new object with a specified prototype, whilenew
creates an instance of a constructor function.
What are "decorators" in JavaScript?
- Decorators are a proposal for adding annotations and meta-programming syntax for classes and properties.
Functional Programming
What is functional programming?
- Functional programming is a paradigm that treats computation as the evaluation of mathematical functions and avoids changing state and mutable data.
What is a pure function?
- A pure function is one that produces the same output given the same input and has no side effects.
What is currying?
- Currying is the technique of transforming a function that takes multiple arguments into a sequence of functions each taking a single argument.
What is memoization?
- Memoization is an optimization technique where results of expensive function calls are cached for reuse.
What are higher-order functions?
- Higher-order functions are functions that take other functions as arguments or return functions as their results.
What is
map()
?map()
is an array method that creates a new array with the results of applying a provided function to each element.
What is
filter()
?filter()
is an array method that creates a new array with all elements that pass a test provided by a function.
What is
reduce()
?reduce()
is an array method that executes a reducer function on each element, resulting in a single output value.
What is a functional pipeline?
- A functional pipeline is a series of functions executed in sequence, with each function passing its result to the next.
What is
compose()
?compose()
is a higher-order function that combines multiple functions into a single function where each function is executed from right to left.
Best Practices and Design Patterns
What are some best practices for writing clean JavaScript code?
- Use meaningful variable names, keep functions small and focused, write modular code, and follow consistent coding conventions.
What is the Singleton pattern?
- The Singleton pattern ensures a class has only one instance and provides a global point of access to that instance.
What is the Observer pattern?
- The Observer pattern defines a one-to-many dependency where changes to one object (the subject) are observed by multiple observers.
What is the Module pattern?
- The Module pattern is a design pattern that creates encapsulated modules to provide public and private interfaces.
What is the Factory pattern?
- The Factory pattern defines an interface for creating objects, but allows subclasses to alter the type of objects that will be created.
What is the Prototype pattern?
- The Prototype pattern creates new objects by copying an existing object, allowing for dynamic and flexible object creation.
What is the Decorator pattern?
- The Decorator pattern adds new functionality to objects dynamically without altering their structure.
What is the Strategy pattern?
- The Strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable.
What is Dependency Injection?
- Dependency Injection is a design pattern where an object receives its dependencies from an external source rather than creating them internally.
What is the Command pattern?
- The Command pattern encapsulates a request as an object, allowing parameterization of clients with queues, requests, and operations.
Modern JavaScript
What is optional chaining?
- Optional chaining (
?.
) allows accessing deeply nested properties without having to check if each reference is null or undefined.
- Optional chaining (
What is nullish coalescing?
- Nullish coalescing (
??
) returns the right-hand side operand when the left-hand side operand isnull
orundefined
.
- Nullish coalescing (
What is the
BigInt
type?BigInt
is a type that allows representing and manipulating arbitrarily large integers.
What is
Array.prototype.flat()
?flat()
is a method that flattens nested arrays into a single array with a specified depth.
What is
Array.prototype.flatMap()
?flatMap()
first maps each element using a mapping function and then flattens the result into a new array.
What are tagged template literals?
- Tagged template literals allow custom processing of template literals by prefixing them with a function.
What is
Object.fromEntries()
?Object.fromEntries()
transforms a list of key-value pairs into an object.
What are the
WeakMap
andWeakSet
types?WeakMap
andWeakSet
are collections that allow garbage collection of objects they hold references to.
What are private class fields?
- Private class fields are properties that are only accessible within the class that defines them, using
#
syntax.
- Private class fields are properties that are only accessible within the class that defines them, using
What is the
Intl
object? - TheIntl
object provides internationalization support for number, date, and time formatting, as well as message formatting.