Trampling guide: JavaScript deconstructing assignment

The opening

Since the release of ES6 in 2015, it is now essential to use ES6 syntax in projects such as const let class =>, etc. Today I stumbled while using ES6 destruct assignment…

Here is the scene of the crash

In project development I often use deconstructed assignment to get Object properties or Array values

# Object to deconstruct attributesconst result = { a: 'a'.b: 'b' }
# Use deconstruction to get a and Bconst { a, b } = result
Copy the code
# Array to deconstructconst list = [1.2.3]
const [item, ...rest] = list
Copy the code

However, I stumbled while deconstructing an object with a null attribute in the project

# this is how the data is returned in the background{
  username: '',
  identity: 'admin',
  avatar: null. token: 'f0a74a994e84e8ed3be11ed9f4bb5417' } Copy the code

Then set the default values for Avatar and username when deconstructing the data

const { username = 'Default user', identity = 'ADMIN', avatar = 'https://unavatar.now.sh/github/hom' } = result
Copy the code

In the following use of Avatar, it is found that avatar with the value of NULL is not assigned as the default attribute, resulting in the following VUEX assignment error. It worked fine when I changed the assignment statement to ES5’s default assignment syntax

const avatar = result.avatar || 'https://unavatar.now.sh/github/hom'
Copy the code

Then I went to the MDN documentation on deconstructing assignments and figured out why. It is also recommended that if you are in doubt about Javascript or CSS during development, the first place to look is the MDN documentation

What is deconstruction assignment

The destruct assignment syntax is a Javascript expression. By deconstructing assignments, attributes/values can be taken from objects/arrays and assigned to other variables.

We use object and array values a lot in JavaScript development, and traditionally it’s worth using them through. Or [], and there’s a new way to use it in ES6, which is to deconstruct assignments.

The basic use

A common way to use this is to get an array or object value as a literal [] or {}

Array destruct assignment

let a, b, rest;
[a, b] = [10.20];

console.log(a);
// expected output: 10
 console.log(b); // expected output: 20  [a, b, ...rest] = [10.20.30.40.50];  console.log(rest); // expected output: Array [30,40,50] Copy the code

Object destruct assignment

({ a, b } = { a: 10.b: 20 });
console.log(a); / / 10
console.log(b); / / 20

({a, b, ... rest} = {a: 10.b: 20.c: 30.d: 40});
console.log(a); / / 10 console.log(b); / / 20 console.log(rest); // {c: 30, d: 40} Copy the code

Regular use

Destruct assignments often use assignments to default values, and use = to add the default value of a property, just as you used the default argument to function

let a, b;

[a=5, b=7] = [1];
console.log(a); / / 1
console.log(b); / / 7
Copy the code
let {a = 10, b = 5} = {a: 3};

console.log(a); / / 3
console.log(b); / / 5
Copy the code

The problem

This article appears because of unexpected results when using the default values of the deconstructed assignment binding. We have no problem setting default values for properties that do not exist in the source object, but when we deconstruct the source object’s existing properties, the value of the property determines whether we set default values successfully

The phenomenon of

const { a = '1', b = '2' } = { a: 'a' }
# output:
# a = 'a'
# b = '2'

const { a = '1', b = '2' } = { a: 'a'.b: null } # output: # a = 'a' # b = null  const { a = '1', b = '2', c = '3', d = '4', e = '5' } = let object = { a: 'a'.b: null.c: undefined.d: false.e: ' ' } # output: # a = 'a' # b = null # c = '3' # d = false # d = ' ' Copy the code

We can see that the default assignment will only succeed if the value is undefined, and when we use ES5 syntax to bind the default and deconstruct the assignment, the result is a little different

const result = { a: 'a'.b: null.c: undefined.d: false.e: ' ' }

# a
let a = result.a || '1'
# output: a = 'a'
 # b let b = result.b || '2' # output: b = '2'  # c let c = result.c || '3' # output: c = '3'  # d let d = result.d || '4' # output: d = '4'  # e let e = result.e || '5' # output: e = '5' Copy the code

If there is some surprise, the default assignment using ES5 is not the same as the result of deconstructing the assignment. The default value can be assigned when the attribute value of ES5 is null undefined false”

thinking

When we see the result of the assignment, we need to think about why this result occurs. 3 min……

Deconstruction assignment

In the documentation of MDN we see this sentence

To prevent fetching an object with a value of undefined from the array, you can set the default value for any object in the array to the left of the expression.

Object default value binding is a feature added to the base of array. When does an attribute name have a value of undefined appear? If the variable is not defined or the value of the variable is set to undefined, null “false” will be used in the parsing of the variable, so the assignment will fail by default

function (a, b = '2') {
  // function content
}
Copy the code

When using the default value of a function, the default resolution skips default assignment whenever there is an argument at the current function location, so whether you are null or “” is passed into the function in the original format.

So in future development, if we only bind default values based on the presence or absence of attributes, we can use deconstructed assignment

use||The assignment

We will use the default assignment in ES5 to determine the attribute name and | | plus defaults to bind

const a = result.a || '1'
Copy the code

Is due to the use of the | | to judge object worthy of existence, so as long as the object attribute values can be converted to Boolean false, the default binding will succeed, so in this paper we use null undefined false “‘ can the assignment successfully.

If you use the | | to bind a default value, also need to note that because of | | is to convert the value to true and false for short circuit operation, so if the value of the object itself is false, if your default rendering is other types of values, For example, I use ‘1’ and false in my example or the default is true

const result = { a: false }
# Here is an example of an errorconst is = result.a || true
Copy the code

Did you find any problems in the example above? The value of is is always true, and the original value of result is ignored. This may cause some non-repeatable bugs

conclusion

After the above discussion, we found that after using the default binding, deconstruction assignment to determine whether the attribute value is undefined, then in the program using the | | to determine whether to need to the property of the Boolean value to false the default binding

const result = { a: ' ' }

let { a, b = 'default b' } = result

let a = a || 'default a'
Copy the code

Using the method used in the sample code we can do the right thing with the default value properties we want to bind.

reference

  • MDN deconstructs the syntax of assignment

More content

For more content, please pay attention to GitHub, Zhihu @Big Handprint, or follow my official account @full stack Developer. I will share some full stack development content from time to time, thanks for sharing


This article is formatted using MDNICE