Irbisa · Cheatsheet

JavaScript for React

Closures, scope, this, prototypes, equality, the event loop, promises and async/await, modules, immutability, array methods

Junior Developer · 21 questions

  1. 01

    What is the difference between var, let and const, and what is the temporal dead zone?

    var is function-scoped, hoisted with the value undefined and can be redeclared.

    function demo() {  console.log(a); // undefined: var is hoisted and initialized  // console.log(b); // ReferenceError: b is in the temporal dead zone  var a = 1;  let b = 2;…
  2. 02

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

    === compares without type conversion: the values must have the same type and value.

  3. 03

    What is the difference between primitive and reference types in JavaScript?

    Primitives (string, number, bigint, boolean, undefined, null, symbol) are immutable values copied on assignment.

  4. 04

    What is the difference between null and undefined?

    undefined means no value was ever assigned: an uninitialized variable, a missing property or argument, a function without return.

  5. 05

    What is a closure, and where do closures show up in React?

    A closure is a function together with the variables of the scope where it was created.

    function createCounter() {  let count = 0; // captured by the closures below  return {    increment: () => ++count,    get: () => count,  };…
  6. 06

    What does this code log, and how do you make it log 0, 1, 2?

    for (var i = 0; i < 3; i++) {  setTimeout(() => {    console.log(i);  }, 0);}

    It logs 3 three times.

  7. 07

    What does this code log, and why can a function declaration be called before its line while a function expression cannot?

    console.log(greet());console.log(typeof hello); function greet() {  return 'hi';} var hello = function () {  return 'hello';}; console.log(hello());console.log(wave()); var wave = () => 'wave';

    It logs hi, undefined and hello, then throws TypeError: wave is not a function.

  8. 08

    What do destructuring, spread and rest, optional chaining ?. and nullish coalescing ?? do?

    Destructuring unpacks object and array values into variables; spread ... expands an iterable or object into another; rest ... collects what is left; ?. returns undefined instead of throwing when the left side is null or undefined; ?? gives a fallback only for null and undefined.

    const settings = { volume: 0, theme: null, user: { name: 'Ada' } }; const { volume, theme = 'light', ...others } = settings;console.log(volume, theme); // 0 null: the default applies only to undefinedconsole.log(others); // { user: { name: 'Ada' } }…
  9. 09

    Which array methods do you use most in React code, and which of them mutate the array?

    map, filter, find, some, every, reduce and slice return new values and leave the array alone, which is what React state needs.

    const cart = [  { id: 1, title: 'Book', price: 12 },  { id: 2, title: 'Pen', price: 2 },  { id: 3, title: 'Lamp', price: 30 },];…
  10. 10

    What is the difference between a shallow and a deep copy, and how do you make each?

    A shallow copy creates a new top-level object but shares the nested objects with the original; a deep copy duplicates every level.

    const user = { name: 'Ada', address: { city: 'London' } }; const shallow = { ...user };shallow.address.city = 'Paris';console.log(user.address.city); // Paris: the nested object is shared…
  11. 11

    How is this determined in JavaScript, and how do arrow functions differ?

    For a regular function this depends on the call: obj.method() gives obj, call, apply and bind set it explicitly, new gives the new object, and a plain call gives undefined in strict mode.

    const user = {  name: 'Ada',  greet() {    return `Hi, ${this.name}`;  },  greetLater() {…
  12. 12

    How does prototypal inheritance work, and what does the class keyword add to it?

    Every object has a hidden link to another object, its prototype.

    class Animal {  constructor(name) {    this.name = name;  }  speak() {    return `${this.name} makes a sound`;…
  13. 13

    What is the difference between named and default exports, and how do ES modules differ from CommonJS?

    A module has any number of named exports, imported by exact name in braces, and at most one default export, imported under any name.

    // math.jsexport const PI = 3.14159;export function area(r) {  return PI * r * r;}export default function round(n) {…
  14. 14

    What is a Promise, and how does async/await relate to it?

    A Promise is an object for a value that arrives later: it starts pending and settles once, either fulfilled with a value or rejected with an error.

    async function loadUser(id) {  try {    const response = await fetch(`/api/users/${id}`);    if (!response.ok) throw new Error(`HTTP ${response.status}`);    return await response.json();  } catch (error) {…
  15. 15

    What is the difference between Promise.all, Promise.allSettled, Promise.race and Promise.any, and when do you use each?

    All four take several promises and return one.

    const ok = (value, ms) => new Promise((resolve) => setTimeout(() => resolve(value), ms));const fail = (reason, ms) =>  new Promise((_, reject) => setTimeout(() => reject(new Error(reason)), ms)); const results = await Promise.allSettled([ok('profile', 50), fail('feed down', 10)]);console.log(results.map((r) => r.status)); // ['fulfilled', 'rejected']…
  16. 16

    How do you handle errors in async/await code, and what happens to a promise rejection that nobody catches?

    Wrap the await in try/catch where you can do something about the failure, and let it propagate elsewhere: a rejection travels up through every function that awaits it, like a thrown exception.

    async function loadDashboard(userId) {  showSpinner();  try {    // Promise.all attaches a handler to both requests at once    const [profile, orders] = await Promise.all([      fetchJson(`/api/users/${userId}`),…
  17. 17

    How does the JavaScript event loop work: what are the call stack, microtasks and macrotasks?

    JavaScript runs one piece of code at a time on a call stack.

  18. 18

    In what order does this code log, and why?

    console.log('1'); setTimeout(() => console.log('2'), 0); Promise.resolve().then(() => console.log('3')); (async () => {  console.log('4');  await null;  console.log('5');})(); console.log('6');

    It logs 1, 4, 6, 3, 5, 2.

  19. 19

    Find the bug: saveAll logs "done" before any user is saved.

    async function saveAll(users) {  users.forEach(async (user) => {    await saveUser(user);  });  console.log('done');}

    forEach ignores the promises its callback returns, so saveAll never waits for them: it logs done immediately, and a failed save becomes an unhandled rejection instead of an error the caller can catch.

  20. 20

    How do you implement debounce, and when do you use it instead of throttle?

    debounce delays a call until a burst of events has been quiet for N ms, so only the last call runs, for example a search request after the user stops typing.

    function debounce(fn, delay) {  let timerId;  function debounced(...args) {    clearTimeout(timerId);    timerId = setTimeout(() => fn.apply(this, args), delay);  }…
  21. 21

    What causes memory leaks in a single-page React app, and how do you find them?

    A leak is memory that stays reachable after you stop needing it, so the garbage collector cannot free it.