JavaScript Flashcards

(60 cards)

1
Q

What is the difference between var, let, and const in JavaScript?

A

var is function-scoped and can be redeclared; let is block-scoped and can be reassigned; const is block-scoped and cannot be reassigned, but its value (if an object) can be mutated.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What does this refer to in JavaScript?

A

this refers to the context in which a function is called. In global scope, it’s the window object (browser) or global (Node.js). In an object method, it refers to the object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is a closure in JavaScript?

A

A closure is a function that retains access to its outer scope’s variables even after the outer function has finished executing.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the event loop in JavaScript?

A

The event loop is a mechanism that handles asynchronous tasks by processing the call stack and pushing tasks from the callback queue to the stack when it’s empty, enabling non-blocking I/O.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is the difference between == and === in JavaScript?

A

== performs type coercion before comparison, while === checks for both value and type equality.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How does prototypal inheritance work in JavaScript?

A

Objects inherit properties and methods from a prototype object. Each object has a \_\_proto\_\_ property linking to its prototype.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is a Promise in JavaScript?

A

A Promise is an object representing the eventual completion or failure of an asynchronous operation. It has states (pending, fulfilled, rejected) and methods like .then(), .catch(), and .finally().

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Explain async and await in JavaScript.

A

async declares a function that returns a Promise. await pauses execution inside an async function until a Promise resolves.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is the difference between null and undefined?

A

null is an explicit assignment indicating no value, while undefined means a variable is declared but not assigned.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is event delegation in JavaScript?

A

Event delegation uses event bubbling to handle events on a parent element for its children, reducing the number of event listeners.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What are arrow functions, and how do they differ from regular functions?

A

Arrow functions (=>) have a concise syntax and lexically bind this to the enclosing context, unlike regular functions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is the purpose of Object.defineProperty?

A

Object.defineProperty defines or modifies a property on an object, allowing control over its value, writability, enumerability, and configurability.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Explain the concept of hoisting in JavaScript.

A

Hoisting moves variable and function declarations to the top of their scope during compilation. var variables are hoisted and initialized as undefined; let and const are hoisted but not initialized.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is a generator function in JavaScript?

A

A generator function (declared with function*) returns an iterator and can pause execution with yield.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is the difference between map, filter, and reduce?

A

map transforms each element into a new array; filter creates an array with elements passing a test; reduce accumulates elements into a single value.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How does try...catch work in JavaScript?

A

try...catch handles errors: code in the try block is executed, and if an error occurs, control moves to the catch block.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is a WeakMap in JavaScript?

A

A WeakMap is a collection where keys must be objects, and entries are weakly referenced, allowing garbage collection if the key is no longer referenced.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Explain the bind method.

A

The bind method creates a new function with a fixed this value and optional preset arguments.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What is memoization, and how can it be implemented in JavaScript?

A

Memoization caches function results for given inputs to improve performance.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What are JavaScript modules, and how do they work?

A

Modules encapsulate code using import and export syntax, enabling reusable, scoped code.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is currying in JavaScript, and how is it implemented?

A

Currying transforms a function with multiple arguments into a sequence of functions, each taking one argument. Example: const curry = (fn) => (a) => (b) => fn(a, b); const add = curry((a, b) => a + b); add(2)(3); // 5.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

How does this behave in an arrow function compared to a regular function?

A

In arrow functions, this is lexically bound to the enclosing scope’s this value, while in regular functions, this depends on how the function is called (e.g., obj.method(), call, or apply).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What is the purpose of the class syntax in JavaScript?

A

The class syntax is syntactic sugar for constructor functions, providing a cleaner way to create objects with prototypes for inheritance. Example: class MyClass { constructor() {} }.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

How does the super keyword work in JavaScript classes?

A

super calls the parent class’s constructor or methods in a subclass. Example: class Child extends Parent { constructor() { super(); } } invokes the Parent constructor.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
What is a higher-order function in JavaScript?
A higher-order function takes a function as an argument or returns a function. Example: `const withLog = (fn) => (...args) => { console.log('Calling'); return fn(...args); };`.
26
Explain the difference between `call`, `apply`, and `bind` methods.
`call` invokes a function with a specified `this` and arguments individually; `apply` uses an array of arguments; `bind` creates a new function with a fixed `this` and optional preset arguments.
27
How can you implement a private variable in a JavaScript class?
Private variables are implemented using the `#` prefix in classes. Example: `class MyClass { #privateVar = 42; getPrivate() { return this.#privateVar; } }`.
28
What is the role of `Object.create` in JavaScript?
`Object.create` creates a new object with a specified prototype. Example: `const obj = Object.create({ x: 1 });` creates `obj` with `{ x: 1 }` as its prototype.
29
How does JavaScript’s `Proxy` object work?
A `Proxy` wraps an object to intercept operations like property access or assignment. Example: `const proxy = new Proxy(target, { get: (obj, prop) => obj[prop] });`.
30
What is the purpose of `Symbol` in JavaScript?
`Symbol` creates unique, immutable identifiers, often used as object keys to avoid property name collisions. Example: `const sym = Symbol('id'); obj[sym] = 42;`.
31
Explain the `new` keyword in JavaScript.
The `new` keyword creates an instance of a constructor function, sets `this` to the new object, links it to the constructor’s prototype, and returns the object.
32
What is a thunk in JavaScript?
A thunk is a function that wraps an expression to delay its evaluation. Example: `const thunk = () => computeExpensiveValue();` evaluates only when called.
33
How does `Object.seal` differ from `Object.freeze`?
`Object.seal` prevents adding or removing properties but allows modifying existing ones; `Object.freeze` prevents all modifications, including property values.
34
What is the Temporal Dead Zone (TDZ) in JavaScript?
TDZ is the period where `let` or `const` variables are hoisted but inaccessible before their declaration, causing a `ReferenceError` if accessed.
35
Explain partial application in JavaScript.
Partial application fixes some arguments of a function, returning a new function with fewer parameters. Example: `const partial = (fn, a) => (...b) => fn(a, ...b);`.
36
How do you implement inheritance using `class` syntax?
Use `extends` to inherit from a parent class, with `super` to call the parent’s constructor or methods. Example: `class Dog extends Animal { bark() { return 'Woof'; } }`.
37
What is the purpose of `WeakSet` in JavaScript?
`WeakSet` stores weakly referenced objects, allowing garbage collection if no other references exist. It’s not iterable and is used for tracking objects without preventing cleanup.
38
Explain the `Reflect` API in JavaScript.
The `Reflect` API provides methods for interceptable operations like property access (`Reflect.get`) or object creation (`Reflect.construct`), often used with `Proxy`.
39
What is tail call optimization, and does JavaScript support it?
Tail call optimization reuses the stack frame for recursive calls in tail position. JavaScript engines (e.g., V8) don’t fully support it in practice, despite ES6 specification.
40
How can you create a deep copy of an object in JavaScript?
A deep copy duplicates all nested objects. Example: `const deepCopy = (obj) => JSON.parse(JSON.stringify(obj));` or use libraries like Lodash for complex cases.
41
What is the JavaScript call stack, and how does it work?
The call stack tracks function execution in a LIFO (Last In, First Out) order. When a function is called, its execution context is pushed onto the stack; when it completes, it’s popped off. Example: `function a() { b(); } function b() { console.log('b'); } a();` pushes `a`, then `b`, executes `b`, then `a`. (O(1) push/pop).
42
How do primitive types differ from objects in JavaScript?
Primitive types (string, number, bigint, boolean, undefined, symbol, null) are immutable and stored directly. Objects are mutable, stored as references. Example: `let x = 5; let y = x; y = 10;` `x` stays 5 (primitive). `let obj1 = {a: 1}; let obj2 = obj1; obj2.a = 2;` `obj1.a` becomes 2 (reference).
43
What is the difference between value types and reference types?
Value types (primitives) store the value directly; reference types (objects, arrays) store a memory address. Example: `let a = 1; let b = a; b = 2;` `a` is 1. `let arr1 = [1]; let arr2 = arr1; arr2.push(2);` `arr1` is `[1, 2]` (same object).
44
What is type coercion in JavaScript, and how does it affect `==`?
Type coercion is automatic type conversion. `==` coerces types before comparison, e.g., `'5' == 5` is true (string to number). Use `===` to avoid coercion. Example: `'5' === 5` is false (different types). Avoid `==` to prevent unexpected results.
45
How does `===` differ from `==`, and what does `typeof` do?
`===` (strict equality) checks value and type without coercion; `==` (loose equality) coerces types. `typeof` returns a variable’s type. Example: `5 === '5'` is false; `5 == '5'` is true; `typeof 5` is `'number'`. Note: `typeof null` returns `'object'` (quirk).
46
What is the difference between function scope and block scope?
Function scope (var) limits variables to functions; block scope (let, const) limits to blocks `{}`. Example: `if (true) { var x = 1; let y = 2; } console.log(x);` logs 1; `console.log(y);` errors (y is block-scoped).
47
What is lexical scope in JavaScript?
Lexical scope means variables are accessible based on their physical code location. Inner functions access outer scope variables. Example: `function outer() { let x = 10; function inner() { console.log(x); } inner(); }` logs 10.
48
What is an IIFE, and why is it used?
An IIFE (Immediately Invoked Function Expression) is a function that runs immediately. Used to avoid polluting global scope. Example: `(function() { let x = 1; console.log(x); })();` logs 1, `x` is not global.
49
How does the JavaScript event loop work with the message queue?
The event loop processes the call stack, then the message queue (callbacks, e.g., `setTimeout`) and microtasks (Promises). Example: `setTimeout(() => console.log('timeout'), 0); Promise.resolve().then(() => console.log('promise'));` logs 'promise', then 'timeout' (microtasks first).
50
What is the difference between `setTimeout` and `requestAnimationFrame`?
`setTimeout` schedules a callback after a delay (ms); `requestAnimationFrame` schedules before the next browser repaint, ideal for animations. Example: `requestAnimationFrame(() => console.log('frame'));` runs at ~60fps, smoother than `setTimeout`.
51
What is a closure, and how is it used in JavaScript?
A closure is a function that retains access to its outer scope’s variables. Example: `function outer() { let x = 10; return () => x++; } let fn = outer(); console.log(fn());` logs 10, then 11. Used for data encapsulation.
52
How do higher-order functions work in JavaScript?
Higher-order functions take or return functions. Example: `function map(arr, fn) { return arr.map(fn); } console.log(map([1, 2], x => x * 2));` logs `[2, 4]`. Common in functional programming (e.g., `map`, `filter`).
53
What is the purpose of `map`, `reduce`, and `filter` in JavaScript?
`map` transforms each element; `filter` selects elements; `reduce` aggregates to a single value. Example: `[1, 2, 3].map(x => x * 2)` → `[2, 4, 6]`; `.filter(x => x > 1)` → `[2, 3]`; `.reduce((sum, x) => sum + x, 0)` → 6.
54
What is a pure function, and why is it important?
A pure function returns the same output for the same input, with no side effects. Example: `function add(a, b) { return a + b; }` is pure. Importance: Predictable, testable, reduces bugs in functional programming.
55
How does `this` work in JavaScript, and how do `call`, `apply`, and `bind` modify it?
`this` refers to the function’s execution context (e.g., object for methods). `call` and `apply` set `this` and invoke immediately; `bind` sets `this` for later. Example: `function fn() { console.log(this.x); } fn.call({x: 1});` logs 1.
56
What is prototype inheritance in JavaScript?
Objects inherit properties/methods via their prototype chain. Example: `function Dog() { this.bark = true; } Dog.prototype.speak = () => 'woof'; let dog = new Dog(); console.log(dog.speak());` logs 'woof'. Accessed via `__proto__` or `Object.getPrototypeOf`.
57
How do Promises work in JavaScript?
Promises handle async operations with states (pending, fulfilled, rejected). Example: `new Promise((resolve, reject) => setTimeout(() => resolve('Done'), 1000)).then(console.log);` logs 'Done' after 1s. Chains with `.then`, handles errors with `.catch`.
58
What is `async/await`, and how does it simplify Promises?
`async` functions return Promises; `await` pauses execution until a Promise resolves. Example: `async function fetchData() { let data = await fetch('/api'); return data.json(); }` simplifies `fetch().then(res => res.json())`.
59
What is Big O notation, and how does it apply to JavaScript?
Big O measures algorithm efficiency (time/space). Example: `for (let i = 0; i < n; i++) {}` is O(n) (linear). In JavaScript, array `push` is O(1), but `shift` is O(n) due to reindexing.
60
What is currying, and how is it implemented in JavaScript?
Currying transforms a function to take arguments one at a time. Example: `function curry(fn) { return x => y => fn(x, y); } let add = curry((a, b) => a + b); console.log(add(2)(3));` logs 5. Useful for function composition.