Domanda di colloquio di Synechron

explain destructuring for Array, Object or String in JavaScript, and what are uses?

Risposta di colloquio

Anonimo

8 mar 2024

Array destructuring allows you to unpack values from arrays into distinct variables. const numbers = [1, 2, 3, 4, 5]; const [first, second, ...rest] = numbers; Uses: Simplifying array manipulation by extracting specific elements. Swapping variable values without using temporary variables. Object destructuring allows you to extract properties from objects and assign them to variables with matching names. const person = { name: 'John', age: 30, country: 'USA' }; const { name, age } = person; Uses: Simplifying code when working with objects by extracting only the needed properties. Renaming variables during assignment. String destructuring is a less common use case but still possible in JavaScript. It allows you to break down a string into its individual characters. const [firstChar, secondChar, ...restChars] = 'Hello'; Uses: Extracting characters from a string for specific manipulations. Handling strings in a more granular manner.