JavaScript Destructuring


JavaScript Destructuring Interview with follow-up questions

1. What is destructuring in JavaScript and why is it used?

Destructuring (ES6) is syntax for unpacking values from arrays or properties from objects into distinct variables in a single, readable statement.

// Array — positional
const [first, second] = [10, 20];

// Object — by key, with renaming
const { name, age: years } = { name: "Ada", age: 36 };

Why it's used and the features interviewers probe:

  • Defaults: const { theme = "light" } = settings; (applies only when the value is undefined).
  • Nested: const { address: { city } } = user;.
  • Rest: const [head, ...tail] = list; or const { id, ...rest } = obj; to collect the remainder.
  • Function parameters: destructure an "options object" with defaults — function f({ page = 1, size = 20 } = {}) {} — the trailing = {} matters so calling f() with no args doesn't throw.
  • Swapping without a temp: [a, b] = [b, a];.
  • Returning multiple values by destructuring a returned array/object.

Gotcha to mention: array destructuring works on any iterable (strings, Map, Set), and destructuring null/undefined throws — pair it with a default like = {}.

↑ Back to top

Follow-up 1

Can you provide a code example of destructuring?

Sure! Here's an example of array destructuring:

const numbers = [1, 2, 3, 4, 5];

const [first, second, ...rest] = numbers;

console.log(first); // Output: 1
console.log(second); // Output: 2
console.log(rest); // Output: [3, 4, 5]

And here's an example of object destructuring:

const person = {
  name: 'John Doe',
  age: 30,
  city: 'New York'
};

const { name, age, city } = person;

console.log(name); // Output: 'John Doe'
console.log(age); // Output: 30
console.log(city); // Output: 'New York'

Follow-up 2

What are the benefits of using destructuring?

There are several benefits of using destructuring in JavaScript:

  1. Concise syntax: Destructuring allows you to extract values from arrays or properties from objects in a more concise and readable way.
  2. Variable assignment: Destructuring can be used to assign values to variables in a single line of code.
  3. Swapping variable values: Destructuring makes it easy to swap the values of two variables without using a temporary variable.
  4. Function arguments: Destructuring can be used to extract values from objects or arrays and pass them as arguments to functions more easily.
  5. Default values: Destructuring allows you to set default values for variables in case the extracted value is undefined or missing.

Follow-up 3

Can destructuring be used with arrays?

Yes, destructuring can be used with arrays. You can extract values from an array and assign them to variables using array destructuring syntax. You can also use array destructuring to skip certain values or assign default values to variables.

Here's an example:

const numbers = [1, 2, 3, 4, 5];

const [first, second, ...rest] = numbers;

console.log(first); // Output: 1
console.log(second); // Output: 2
console.log(rest); // Output: [3, 4, 5]

Follow-up 4

Can destructuring be used with objects?

Yes, destructuring can also be used with objects. You can extract properties from an object and assign them to variables using object destructuring syntax. You can also use object destructuring to assign default values to variables or rename properties.

Here's an example:

const person = {
  name: 'John Doe',
  age: 30,
  city: 'New York'
};

const { name, age, city } = person;

console.log(name); // Output: 'John Doe'
console.log(age); // Output: 30
console.log(city); // Output: 'New York'

Follow-up 5

What happens if you try to destructure a property that doesn't exist in the object?

If you try to destructure a property that doesn't exist in the object, the value assigned to the variable will be undefined. This can be useful when you want to provide default values for properties that may not exist in the object.

Here's an example:

const person = {
  name: 'John Doe',
  age: 30
};

const { name, age, city } = person;

console.log(name); // Output: 'John Doe'
console.log(age); // Output: 30
console.log(city); // Output: undefined

2. How can you use destructuring to swap variables?

Array destructuring lets you swap two variables in one line, with no temporary variable:

let a = 1;
let b = 2;

[a, b] = [b, a];

console.log(a, b); // 2 1

How it works: the right side [b, a] builds a new array from the current values before any assignment happens, then destructuring assigns those positions back to a and b. Because the right-hand array is evaluated first, there's no clobbering.

Follow-ups interviewers may add:

  • It generalizes to rotating more than two: [a, b, c] = [c, a, b];.
  • ASI gotcha: if the previous line doesn't end in a semicolon, a leading [ can be misparsed as indexing into the previous expression. Either keep semicolons or prefix with one: ;[a, b] = [b, a];.
  • It's purely a swap of bindings — for primitives this is a true value swap; for objects it just swaps which reference each variable holds.
↑ Back to top

Follow-up 1

Can you provide a code example of swapping variables using destructuring?

Sure! Here's an example:

let x = 10;
let y = 20;

[x, y] = [y, x];

console.log(x); // Output: 20
console.log(y); // Output: 10

Follow-up 2

What are the benefits of swapping variables using destructuring?

Swapping variables using destructuring has a few benefits:

  1. It provides a concise and readable way to swap the values of variables.
  2. It eliminates the need for a temporary variable.
  3. It can be used with arrays or objects, allowing for more flexibility.

Follow-up 3

Is it possible to swap variables without destructuring?

Yes, it is possible to swap variables without using destructuring. One common approach is to use a temporary variable to hold the value of one variable while swapping the values. Here's an example:

let a = 1;
let b = 2;

let temp = a;
a = b;
b = temp;

Follow-up 4

What happens if you try to swap variables that are not defined?

If you try to swap variables that are not defined, you will get a ReferenceError because the variables are not declared. Make sure to declare and initialize the variables before swapping them.

3. How can you use destructuring to assign default values?

You supply a fallback with = in the destructuring pattern. The default kicks in only when the matched value is undefined — including a missing property or array slot:

const person = { name: "Ada" };
const { name = "John", age = 30 } = person;
console.log(name); // "Ada"  (present → default ignored)
console.log(age);  // 30     (missing → default used)

The crucial gotcha interviewers test: null does NOT trigger the default — only undefined does.

const { count = 5 } = { count: null };
console.log(count); // null, not 5

More follow-ups:

  • Works the same in arrays by position: const [x = 1, y = 2] = [10]; // 10, 2.
  • Defaults can be computed and can reference earlier-destructured variables: const { a = 1, b = a * 2 } = {};a = 1, b = 2.
  • Combine with renaming: const { name: userName = "guest" } = obj;.
  • Very common in function params: function f({ retries = 3 } = {}) {} — the outer = {} lets f() work with no argument.
↑ Back to top

Follow-up 1

Can you provide a code example of assigning default values using destructuring?

Sure! Here's an example:

const { name = 'John', age = 30 } = person;
console.log(name); // Output: 'John'
console.log(age); // Output: 30

Follow-up 2

What are the benefits of assigning default values using destructuring?

Assigning default values using destructuring can provide the following benefits:

  1. It allows you to provide fallback values for properties that may be undefined or null.
  2. It simplifies the code by eliminating the need for manual checks for undefined or null values.
  3. It improves code readability by making the default values explicit.
  4. It reduces the chances of runtime errors caused by accessing undefined or null values.
  5. It allows you to provide default values for multiple properties in a single line of code.

Follow-up 3

What happens if you try to assign a default value to a property that already exists in the object?

If you try to assign a default value to a property that already exists in the object, the default value will not be used. Instead, the existing value of the property will be assigned to the variable. Here's an example:

const person = { name: 'John', age: 30 };
const { name = 'Default Name', age = 40 } = person;
console.log(name); // Output: 'John'
console.log(age); // Output: 30

Follow-up 4

Can you assign default values to array elements using destructuring?

No, you cannot assign default values to array elements using destructuring. Destructuring with default values only works for objects, not arrays. If you want to assign default values to array elements, you can use array destructuring combined with the logical OR operator. Here's an example:

const [name = 'John', age = 30] = person;
console.log(name); // Output: 'John'
console.log(age); // Output: 30

4. How can you use destructuring in function parameters?

You can destructure directly in the parameter list, so the function pulls out exactly the fields it needs — far cleaner than accepting an object and reading opts.x, opts.y inside:

function createUser({ name, age = 18, isAdmin = false }) {
  return `${name}, ${age}, admin: ${isAdmin}`;
}

createUser({ name: "Ada", age: 36 }); // "Ada, 36, admin: false"

This is the standard "options object" pattern — callers pass named arguments in any order, and defaults fill the gaps. Array destructuring works in params too: function dist([x, y]) { ... }.

The gotcha interviewers almost always check: provide a default for the whole parameter so calling with no argument doesn't throw.

// Without `= {}`, createUser() throws — can't destructure undefined
function createUser({ name, age = 18 } = {}) { /* ... */ }
createUser(); // safe now

Follow-ups: you can rename ({ id: userId }), nest ({ address: { city } }), and combine with rest (function f({ a, ...others }) {}) right in the signature.

↑ Back to top

Follow-up 1

Can you provide a code example of using destructuring in function parameters?

Certainly! Here's an example of using destructuring in function parameters:

function printUserDetails({ name, age }) {
  console.log(`Name: ${name}, Age: ${age}`);
}

const user = { name: 'John Doe', age: 25 };
printUserDetails(user);

In this example, the printUserDetails function expects an object with name and age properties as its parameter. By using destructuring in the function parameter, we can directly access and use the name and age variables within the function body.

Follow-up 2

What are the benefits of using destructuring in function parameters?

Using destructuring in function parameters offers several benefits:

  1. Simplifies code: Destructuring allows you to extract specific values from objects or arrays, making your code more concise and readable.
  2. Avoids repetition: Instead of accessing object properties or array elements multiple times within a function, destructuring allows you to assign them to individual variables, reducing repetition.
  3. Provides default values: Destructuring in function parameters allows you to set default values for variables, ensuring that they have a value even if the corresponding property or element is undefined or missing.
  4. Enables selective extraction: Destructuring allows you to extract only the properties or elements you need, ignoring the rest. This can be useful when working with large objects or arrays.

Follow-up 3

Can you use destructuring with rest parameters?

Yes, you can use destructuring with rest parameters. Rest parameters are denoted by the ... syntax and allow you to capture multiple arguments into an array. By combining destructuring with rest parameters, you can extract specific values from the rest parameter array.

Here's an example:

function printNames(first, second, ...others) {
  const [third, fourth] = others;
  console.log(`First: ${first}, Second: ${second}, Third: ${third}, Fourth: ${fourth}`);
}

printNames('John', 'Doe', 'Jane', 'Smith', 'Alex', 'Brown');

In this example, the printNames function uses destructuring to extract the third and fourth names from the rest parameter others, which captures all the additional arguments passed to the function.

Follow-up 4

What happens if you try to destructure a parameter that doesn't exist in the function arguments?

If you try to destructure a parameter that doesn't exist in the function arguments, the value of that parameter will be undefined. This means that the variable assigned to the non-existent parameter will also be undefined.

Here's an example:

function printUserDetails({ name, age, email }) {
  console.log(`Name: ${name}, Age: ${age}, Email: ${email}`);
}

const user = { name: 'John Doe', age: 25 };
printUserDetails(user);

In this example, the printUserDetails function expects an object with name, age, and email properties as its parameter. However, the user object only has name and age properties. As a result, the email parameter will be undefined and the output will be Name: John Doe, Age: 25, Email: undefined.

5. How can you use destructuring to return multiple values from a function?

JavaScript functions can only return one value, but you can return an array or object and destructure it at the call site to get "multiple values."

Array — for a fixed, ordered set (the caller picks the names and order matters):

function minMax(nums) {
  return [Math.min(...nums), Math.max(...nums)];
}
const [min, max] = minMax([3, 1, 9]); // 1, 9

Object — usually preferred for clarity, since results are named and order-independent, and callers can ignore fields they don't need:

function getUser() {
  return { id: 1, name: "Ada", role: "admin" };
}
const { name, role } = getUser(); // grab only what you want

Follow-ups interviewers expect:

  • Array vs object: arrays are concise (and let React hooks like useState return [value, setter]), but objects are self-documenting and resilient to reordering or added fields.
  • You can apply renaming and defaults while destructuring the result: const { name: userName = "guest" } = getUser();.
  • This is the idiomatic JS substitute for languages' tuple/out-parameter features.
↑ Back to top

Follow-up 1

Can you provide a code example of returning multiple values from a function using destructuring?

Sure! Here's an example of returning multiple values from a function using array destructuring:

function getValues() {
  return [1, 2, 3];
}

const [a, b, c] = getValues();

console.log(a); // Output: 1
console.log(b); // Output: 2
console.log(c); // Output: 3

Follow-up 2

What are the benefits of returning multiple values from a function using destructuring?

Returning multiple values from a function using destructuring has several benefits:

  1. Clarity: Destructuring allows you to assign meaningful names to the returned values, making the code more readable and self-explanatory.
  2. Convenience: Destructuring eliminates the need for accessing individual values from an array or object manually. It provides a concise and convenient way to extract multiple values at once.
  3. Flexibility: Destructuring allows you to choose and extract only the values you need, ignoring the rest. This provides flexibility in handling different scenarios and simplifies the code.

Follow-up 3

Can you return multiple values from a function without using destructuring?

Yes, you can return multiple values from a function without using destructuring. One way to achieve this is by returning an array or an object containing the values you want to return. However, without destructuring, you would need to access the individual values manually using array indexing or object property access.

Follow-up 4

What happens if you try to destructure a value that the function does not return?

If you try to destructure a value that the function does not return, the value assigned to the variable will be undefined. For example, if a function returns an array with three values and you try to destructure four variables, the fourth variable will be assigned undefined. Similarly, if a function returns an object with certain properties and you try to destructure a property that does not exist, the variable will be assigned undefined.

Live mock interview

Mock interview: JavaScript Destructuring

Intermediate ~5 min Your own free AI key

Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.