You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
By using [destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) syntax we can unpack values from arrays, or properties from objects, into distinct variables:
2409
+
2410
+
```javascript
2411
+
const { firstName } = { firstName:'Lydia' };
2412
+
// ES5 version:
2413
+
// var firstName = { firstName: 'Lydia' }.firstName;
2414
+
2415
+
console.log(firstName); // "Lydia"
2416
+
```
2417
+
2418
+
Also, a property can be unpacked from an object and assigned to a variable with a different name than the object property:
2407
2419
2408
-
When we unpack the property `name` from the object on the right-hand side, we assign its value `"Lydia"` to a variable with the name `myName`.
console.log(firstName); // Uncaught ReferenceError: firstName is not defined
2427
+
```
2428
+
2429
+
Therefore, `firstName` does not exist as a variable, thus attempting to access its value will raise a `ReferenceError`.
2430
+
2431
+
**Note:** Be aware of the `global scope` properties:
2409
2432
2410
-
With `{ name: myName }`, we tell JavaScript that we want to create a new variable called `myName` with the value of the `name` property on the right-hand side.
2433
+
```javascript
2434
+
const { name:myName } = { name:'Lydia' };
2435
+
2436
+
console.log(myName); // "lydia"
2437
+
console.log(name); // ""
2438
+
```
2411
2439
2412
-
Since we try to log `name`, a variable that is not defined, `undefined` is returned on the left side assignment. Later, the value of `Lydia`is stored through the destructuring assignment.
2440
+
`name` is a global scope property, so when javascript is unable to find the name as a local variable, it looks at the _outer scopes_, which in this case is **window/global**, so it can be accessed via `window.name`.
0 commit comments