Es6 Destructuring
Es6 Destructuring
ES6HOME
What is Destructuring
Destructuring makes it easy to extract array values from any index.
Using Destructuring
With destructing, we can assign array items to variables:
const userdata = ['John', 'john@gmail.com', '123451234'];
const [name,email, phone] = userdata ; // assiging array values to different variables.
When destructuring arrays, Keep in mind the order of the variables that you are providing. To extract only name,phone write the following way.
const [name,,phone] = userdata ;
MOVETOP↑
Destructuring with Array Default values
The following example shows how Array Destructuring Assignment will work with array Default value.
const userdata = ['John', 'john@gmail.com', '123451234'];
onst [name = "John", email = "john@gmail.com"] = ["Doe"];
console.log(name); // Deo
console.log(email); // john@gmail.com
Using array destructurning in function
<script>
// Define an array with two array values:
const profile = ["John", "Doe"];
// Define a function with one destructuring array containing two parameters:
function getUserData([fname, lname]) {
return `My name is ${fname} ${lname}.`;
}
// Invoke data while passing the profile array as an argument:
data = getUserData(profile);
document.write(data);
</script>
ES6HOME
Comments
Post a Comment