- Declare object literals with new shorthand
- Destructure arrays and objects to assign values
- Write dynamic code with the rest and spread operators
- Shorthand object literals
- Template literals (Template strings)
- Default parameters
- Arrow functions
- For-of and For-in loops
- Object & Array destructuring
- Spread operator
- Rest operator
Bellow are 3 examples of creating the same cohort
object using 3 different techniques.
-
Building & accessing objects with dot notation
let cohort = { } class.code = 'g105' class.size = 14 console.log(cohort.code) //'g105'
-
Building objects with object literal notation
let cohort = { code: 'g105', size: 14 } console.log(cohort.code) //'g105'
-
Use existing variables with object shorthand (ES6)
let code = 'g105' let size = 14 let cohort = { code, size } console.log(cohort.code) //'g105'
-
We can extract multiple properties from an object at the same time using ES6 object destructuring.
let cohort = { code: 'g105', size: 14, quality: 'excellent' } let { code, size, quality } = cohort console.log(code) //'g105'
-
The same destructuring syntax works on arrays as well:
let a = 'Roger' let b = 'Wes' let c = 'Scott' let array = [ a, b, c ] let [ first, second, third ] = array console.log(first, second, third) // Roger Wes Scott
The spread operator, ...
, allows expressions to be expanded into multiple parameters, variables or values.
-
Copy arrays
let array = [ 1, 2, 3 ] let copy1 = array let copy2 = [ ...array ]
-
What would happen if you pushed a new value into
copy1
vscopy2
?Your answer...
-
Concatenate arrays
let wdi = [ 'Roger', 'Wes', 'Scott' ] let dsi = [ 'Jack', 'Miles', 'Matt' ] let allInstructors = [ ...wdi, ...dsi ]
-
Add elements of existing array into a new array
let languages = [ 'Javascript', 'Ruby', 'Python' ] let newLangs1 = [ languages, 'Swift' ] let newLangs2 = [ ...languages, 'Swift' ]
-
What is the difference between the two new arrays above?
Your answer...
-
Pass elements of array as arguments to a function
function sum(x, y, z) { return x + y + z } let nums = [1, 2, 3] sum(...nums) // 6
The rest operator, ...
, looks very similar to spread. Instead of expanding values of an array, rest combines values or parameters into a new array.
- Capture all parameters into an array
function sum(...nums) { let total = 0 for (num of nums) { total += num } return total } sum(1, 2, 3) // 6
https://repl.it/@scottyhurlow/ES6-ExitTicket
- Video on object destructuring: https://www.youtube.com/watch?v=RJaRRS27100