JavaScript Destructuring Arrays and Objects

Web Design Web Development

Description

In this Web Development tutorial we are going to learn about JavaScript Destructuring Arrays and Objects.

Def!

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

Content of this tutorial

HTML Code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"
    />
    <link rel="stylesheet" href="style.css" />
    <title>JavaScript Destructuring</title>
  </head>
  <body>
    <h1>JavaScript Destructuring</h1>
    <h2>Arrays & Object</h2>
    <script src="main.js"></script>
  </body>
</html>

CSS Code:


body {
  background-color: #f0db4f;
  color: #323330;
}

h1,
h2 {
  text-align: center;
}


Destructuring Arrays

const cars = ["Tesla", "BMW", "Audi", "Ferrari", "Ford"];

const Tesla = cars[0];
const BMW = cars[1];
const Tesla_BMW = cars[0] + " " + cars[1];

console.log(Tesla_BMW);

 Destructur cars

// const [car1, car2] = cars;
// console.log(car1, car2);

Skipping a element

If you wish to skip a element from the destructured array you can use “,” for the element you wish to skip or multiple “, , ,” if you wish to skip more the one element

const [car1, car2, , car4] = cars;
console.log(car1, car2, car4);

 Assignment separate from declaration


Def:  A variable can be assigned its value via destructuring, separate from the variable’s declaration.

let c1, c2;

[c1, c2] = cars;

console.log(c1, c2);

Assignment separate from declaration & Default values

 A variable can be assigned its value via destructuring, separate from the variable’s declaration.

[c1 = 7, c2 = 8] = [];

 A variable can be assigned a default, in the case that the value unpacked from the array is undefined.

[c1 = 7, c2 = 8] = [9];
console.log(c1); // 7 , 9
console.log(c2); // 8

 Parsing an array returned from a function


It’s always been possible to return an array from a function. Destructuring can make working with an array return value more concise.
 In this example, f() returns the values [1, 2] as its output, which can be parsed in a single line with destructuring.

function numbers() {  return [1, 2, 3];}
const [num1, , num2] = numbers();console.log(num1); // 1console.log(num2); // 3
const [c] = numbers();console.log(c); // 1


 Assigning the rest of an array to a variable

 When destructuring an array, you can unpack and assign the remaining part of it to a variable using the rest pattern aka the sppred operator:

const [a, ...rest] = [1, 2, 3];console.log(a); // 1console.log(rest); // [2, 3] newArray
const mixtArray = [1, 2, "Tesla", "Audi", true, false];const [, , , , ...bool] = mixtArray;
console.log(bool);


 Object Destructuring


 Basic assignment

const user = {  userId: 42,  is_verified: true,};
const { userId, is_verified } = user;
console.log(userId); // 42console.log(is_verified); // true

 Assignment without declaration// A variable can be assigned its value with destructuring separate from its declaration.

let a, b;
({ a, b } = { a: 1, b: 2 });

const user1 = {  // name: "Norbert",  age: 35,

address: {    city: "The City",    street: "Elm Str.",  },};
const { name, age } = user1;// console.log(name, age);


 Assigning to new variable names

 A property can be unpacked from an object and assigned to a variable with a different name than the object property.

const { name: firstName, age } = user1;// console.log(firstName, age);


 Default values in objects

 A variable can be assigned a default, in the case that the value unpacked from the object is undefined.

const { name: firstName = "Laura", age, dob = "Feb 15,1986" } = user1;

 If we add the dob to the object then the default value will be overietten.

 replace the name with “Laura” and // out of the object

console.log(firstName, age, dob);

const user2 = {  id: 13,  nick: "mbn",  fullName: {    firstName: "Norbert",    lastName: "Menyhart",  },};

const { id, ...restInfo } = user2;

console.log(restInfo);


Unpacking fields from objects passed as a function parameter

function userID({ id }) {  return id;}
function whoIs({ nick, fullName: { lastName: name } }) {  return `${nick} is ${name}`;}
console.log(userID(user2));
console.log(whoIs(user2));


For more information about JavaScript get the Complete Modern JavaScript Course NOW and become a javascript developer

https://norbertbm.com/web-development/web-dev-courses/

Modern JavaScript and NodeJS from Beginner to Advanced

Popular course:

https://www.udemy.com/course/30-html-css-javascript-projects-in-30-days-for-beginners/?couponCode=APR2021

30 HTML, CSS & JavaScript projects in 30 Days for Beginners

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.