Javascript Destructuring & Operators
Array De-structuring
Array de-structuring is a feature in JavaScript that allows you to extract values from arrays and assign them to variables in a concise and expressive way. It provides a more readable and cleaner syntax when working with arrays.// Basic array destructuring const numbers = [13, 26, 39, 43, 56]; // Destructuring assignment const [first, second, third] = numbers; console.log(first); // Output: 13 console.log(second); // Output: 26 console.log(third); // Output: 39
You can skip elements by leaving empty spaces in the de-structuring pattern,
const numbers = [12, 24, 36, 48, 50]; const [first, , third] = numbers; console.log(first); // Output: 12 console.log(third); // Output: 36
You can also use default values in case an element is undefined,
const numbers = [1, 2]; const [first = 0, second = 0, third = 0] = numbers; console.log(first); // Output: 1 console.log(second); // Output: 2 console.log(third); // Output: 0 (default value)
Object De-structuring
In JavaScript, object destructuring is a feature that allows you to extract values from objects and bind them to variables in a more concise and readable way.// Object to destructure const person = { firstName: 'John', lastName: 'Doe', age: 30, address: { city: 'New York', country: 'USA' } }; // Destructuring assignment const { firstName, lastName, age, address: { city, country } } = person; // Using the extracted values console.log(firstName); // 'John' console.log(lastName); // 'Doe' console.log(age); // 30 console.log(city); // 'New York' console.log(country); // 'USA'
You can also provide default values in case the property is undefined,
const { firstName, lastName, age, job = 'Developer' } = person; console.log(job); // 'Developer' (if person.job is undefined)
You can use an alias for the variable name during de-structuring,
const { firstName: first, lastName: last } = person; console.log(first); // 'John' console.log(last); // 'Doe'
Spread operator
In JavaScript, the spread operator (...) is a syntax that allows an iterable, such as an array or an object, to be expanded into individual elements or key-value pairs. It provides a concise way to copy arrays, merge arrays, and clone objects.
i) Spread with Arrays - Copying an Arrayconst originalArray = [1, 2, 3]; const copiedArray = [...originalArray]; console.log(copiedArray); // [1, 2, 3]
ii) Spread with Arrays - Concatenating Arrays
const array1 = [1, 2, 3]; const array2 = [4, 5, 6]; const concatenatedArray = [...array1, ...array2]; console.log(concatenatedArray); // [1, 2, 3, 4, 5, 6]
iii) Spread with Arrays - Adding Elements to an Array
const originalArray = [1, 2, 3]; const newArray = [...originalArray, 4, 5]; console.log(newArray); // [1, 2, 3, 4, 5]
iv) Spread with Object - Copying an Object
const originalObject = { key1: 'value1', key2: 'value2' }; const copiedObject = { ...originalObject }; console.log(copiedObject); // { key1: 'value1', key2: 'value2' }
v) Spread with Objects - Merging objects
const object1 = { key1: 'value1' }; const object2 = { key2: 'value2' }; const mergedObject = { ...object1, ...object2 }; console.log(mergedObject); // { key1: 'value1', key2: 'value2' }
vi) Spread with Objects - Modifying Object Properties
const originalObject = { key1: 'value1', key2: 'value2' }; const modifiedObject = { ...originalObject, key2: 'newvalue2' }; console.log(modifiedObject); // { key1: 'value1', key2: 'newvalue2' }
vii) Spread in Function Arguments - Passing Array Elements as Arguments
const numbers = [1, 2, 3]; const sum = (a, b, c) => { a + b + c; } console.log(sum(...numbers)); // 6
viii) Spread in Function Arguments - Combining Default and Spread Parameters
const defaultValues = { x: 1, y: 2 }; const getUserPosition = ({ x, y, ...rest }) => ({ x, y, ...rest }); console.log(getUserPosition(defaultValues)); // { x: 1, y: 2 }
Rest Pattern
Rest parameters allow you to represent an indefinite number of arguments as an array. They are indicated by the ellipsis (...) followed by the parameter name.function sum(...numbers) { return numbers.reduce((acc, num) => acc + num, 0); } console.log(sum(1, 2, 3, 4)); // Output: 10
Nullish Coalising Operator
The nullish coalescing operator (??) provides a concise way to handle default values in cases where null or undefined should be treated differently from falsy values like 0 or an empty string.
The nullish coalescing operator returns the right-hand operand when the left-hand operand is null or undefined; otherwise, it returns the left-hand operand.let variable1 = null; let variable2 = "Hello, World!"; let result = variable1 ?? variable2; console.log(result); // Output: Hello, World!
In this example, variable1 is null, so the nullish coalescing operator returns the value of variable2. If variable1 had been undefined, the result would still be Hello, World!.
This operator is especially useful when you want to provide a default value for a variable or expression but want to avoid using the default value when the variable is explicitly set to null or undefined.
Prior to the introduction of the nullish coalescing operator, the logical OR (||) operator was often used for default values, but it has the behaviour of considering falsy values (0, false, "", etc.) as well, which might lead to unintended results in some cases. The nullish coalescing operator helps to specifically target null and undefined.Optional Chaining (?.)
Optional chaining (?.) allows you to handle properties and methods on potentially null or undefined values without causing a Type Error. It simplifies code and makes it more concise when dealing with nested object structures.// Without optional chaining let result; if (obj && obj.property1 && obj.property1.property2) { result = obj.property1.property2; } else { result = undefined; }
And here's the equivalent code using optional chaining,
// With optional chaining const result = obj?.property1?.property2;
In the second example, if obj, property1, or property2 is null or undefined at any point, the expression short-circuits, and result will be assigned undefined instead of causing an error.