Use Destructuring Assignment to Assign Variables from Objects - illogical method

Use Destructuring Assignment to Assign Variables from Objects - illogical method
0

#1

can someone explain it to me? what is the benefit of this simple indication other than reducing the number of lines? an illogical method:

const {length : len} = str; // I wrote it but i could not understand logic

Your code so far


function getLength(str) {
  "use strict";

  // change code below this line
 
  const {length : len} = str;
  
  // change code above this line

  return len; // you must assign length to len in line

}

console.log(getLength('FreeCodeCamp'));

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-to-assign-variables-from-objects


#2

Perhaps a more useful example of destructuring from an object would be something like this:

const person = { name: { first: "Jane", last: "Doe" }, email: "foo@email.com" };
const { first, last } = person.name;
// first == "Jane", last == "Doe"; 

Destructuring is a convenient way to extract multiple values from an object or array, and the {length: len} syntax, while confusing, is also useful:

const person = { name: { first: "Paul", last: "Harvey" }, email: "bar@email.com" };
const { first : firstName, last: lastName } = person.name;
// read the above as "person.name.first AS firstName", "person.name.last AS lastName"
// firstName == "Paul", lastName == "Harvey"; 

For a single instance, this might not be so useful. But another possible application, suppose I had to iterate over an array of people and use each to populate a table row. I could use Array.map() to extract each object, and destructuring to conveniently access the object properties:

// convenient place to store my HTML
var studentTable = document.querySelector("#student-table tbody");

// A collection of student records
let students = [
  { name: 
    { first: "Zaphod",
      last: "Beeblebrox" },
    email: "foo@email.com"
  },  { name: 
    { first: "Arthur",
      last: "Dent" },
    email: "bar@email.com"
  }, { name: 
    { first: "Tricia",
      last: "MacMillan" },
    email: "baz@email.com"
  }];
  
/***
 * Here, I want to take each student record and create a
 *  DOM node for it. I will use template literals, and I
 *  want a convenient way to access properties of each student.
 *  so I'll use destructuring!
 ***/
students = students.map(person => {
  // extract the name, rather than using
  //  person.name.first or person.name.last repeatedly
  const { first: firstName, last: lastName } = person.name;
  
  // I'll use a template literal, and rather than the long property accessor
  //  I've created shorter descriptive variable names.
  const row = `<tr>
  <td class='row-header'></td>
  <td class='first-name'>${firstName}</td>
  <td class='last-name'>${lastName}</td>
  <td><button class='edit-btn' value='Edit'>Edit</button> <button class='delete-btn' value='delete'>Delete</button></td>
</tr>`;
  
  // Append the row into the table body...
  studentTable.insertAdjacentHTML("beforeend", row);
  // store the HTML into the person object...
  person.domEl = row;
  // and return the person object.
  return person;

}) // end students.map();

// Let's view that updated object.
console.log(students);

This isn’t a complete implementation of destructuring, but it illustrates where being able to assign properties to custom-named variables can be useful. If you wish to see this functional, here’s a fiddle.

Also, and this is a rant, note that I’ve commented the BEJABBERS out of my code. That is intentional. If I were to be coding and someone else have to try to decipher what I’ve done, time may be wasted trying to understand how I was thinking. Commenting saves time and aggravation. Also, it will often help when debugging your own code – if the comment says what the intended purpose of a given line is and the actual result differs, it will help to pinpoint possible errors. Take the time to comment!!


#3

Your code has been blurred out to avoid spoiling a full working solution for other campers who may not yet want to see a complete solution.

In later challenges you will appreciate the ability to destructure ojbects in this manner. It definitely streamlines the code as pointed out by @snowmonkey. Another advantage comes when you start destructuring a functions parameters. This is covered near the end of the ES6 section, but I will explain the benefit here, so that when you see it later, you will hopefully make the connection.

Let’s say I have manually created a large nested object like the following which represents classes a student might take in school.

let myClasses = {
  English: {
    credits: 3,
    meets: 'Monday, Wednesday',
    professor: 'Dr. Poet',
    gradedWork: {
      homework: {
        percent: 0.2,
        grades: [
          {
            date: '08-16-2018',
            grade: 96
          },
          {
            date: '09-01-2018',
            grade: 90
          }
        ]
      },
      quizzes: {
        percent: 0.4,
        grades: [
          {
            date: '08-17-2018',
            grade: 87
          },
          {
            date: '09-03-2018',
            grade: 91
          }
        ]
      },
      tests: {
        percent: 0.4,
        grades: [
          {
            date: '10-15-2018',
            grade: 89
          },
          {
            date: '11-01-2018',
            grade: 95
          }
        ]
      }
    }
  },
  Physics: {
    credits: 5,
    meets: 'Monday, Wednesday, Friday',
    professor: 'Dr. Einstein',
    gradedWork: {
      homework: {
        percent: 0.1,
        grades: [
          {
            date: '08-4-2018',
            grade: 90
          },
          {
            date: '09-02-2018',
            grade: 91
          }
        ]
      },
      quizzes: {
        percent: 0.6,
        grades: [
          {
            date: '08-12-2018',
            grade: 87
          },
          {
            date: '09-20-2018',
            grade: 98
          }
        ]
      },
      tests: {
        percent: 0.3,
        grades: [
          {
            date: '10-11-2018',
            grade: 92
          },
          {
            date: '11-10-2018',
            grade: 90
          }
        ]
      }
    }
  }
};

Now let’s say I have a function called calcGrade, which accepts an object (a subject property of myClasses) and calculates the student’s grade for just the subject object. I could write the following functions and use destructuring in various places to make the calculations easier to read:

/* uses parameter object destructuring in the reduce callback function 
parameters to isolate the grade property */
const avgGrade = grades => grades.reduce((sum, { grade }) => sum + grade, 0) / grades.length;

/* uses object destructuring in the functions parameters, to create 
readable variable names used in the calculation which is returned */
const calcGrade = ({
  gradedWork: {
    homework: { percent: hmPerc, grades: hm },
    quizzes: { percent: qzPerc, grades: qz },
    tests: { percent: testPerc, grades: test }
  }
}) => hmPerc * avgGrade(hm) + qzPerc * avgGrade(qz) + testPerc * avgGrade(test)

const { Physics: grades } = myClasses; // basic object destructuring to get the applicable subject object
console.log('My Physics grade is ' + calcGrade(grades)); // displays 'My Physics grade is 91.85'

#4

I appreciate your great definition about destructuring. Thanks.

Regards,