-
Notifications
You must be signed in to change notification settings - Fork 0
JavaScript Tips
Vinesh Kannan edited this page Jun 28, 2022
·
2 revisions
For a formal introduction to modern JavaScript features, check out the documentation on MDN.
Try to access a key of an object and get undefined instead of an error if it does not exist.
const obj = { color: 'red' }
console.log(obj?.color) // 'red'
console.log(obj?.fontSize) // undefined
## Spreading
You can copy all the elements from an object or array by using the spread operator.
When you spread an object, any repeated keys will be overridden by the later values:
```js
const obj = { a: 1, b: 2, c: 3 }
const moreObj = { ...obj, c: 0, d: 4 }
console.log(moreObj) // { a: 1, b: 2, c: 0, 4 }You can use similar syntax to spread an array:
const arr = [1, 2, 3]
const moreArr = [...arr, 4, 5]
console.log(moreArr) // [1, 2, 3, 4, 5]You can separate an object or array into variables for each of its values by destructuring.
Destructuring objects by key name:
const props = { color: 'red', size: 14 }
const { color, size } = props
console.log(color) // 'red'
console.log(size) // 14Destructuring arrays by index:
// Example of the result of a failed data request,
// which returns a null response and an error message
const result = [null, "Error message"]
const [response, error] = result
console.log(response) // null
console.log(error) // "Error message"