Skip to content
sergio edited this page Nov 9, 2020 · 10 revisions

Deconstructing

NOTE how for Objects we use const {} and for arrays const []

const doggie = {
  first: 'Buzz',
  breed: 'Great Pyrenees',
  fur_color: 'black and white',
  activity_level: 'sloth-like',
  favorite_food: 'hot_dogs'
};
 
const { first, breed } = doggie;

and with arrays:

const dogs = ['Great Pyrenees', 'Pug', 'Bull Mastiff']

const [medium, small, giant] = dogs
console.log(medium, small, giant) // Great Pyrenees, Pug, Bull Mastiff

const [, small, giant] = dogs
console.log(small, giant) //  Pug, Bull Mastiff

rest and spread

rest:

function muppetLab(a, b, ...muppets) {
  console.log(a, ' ', b); // Dr. Bunson Beaker

  console.log(muppets); // ["Miss Piggy", "Kermit", "Animal"]
  console.log(muppets[0]); // Miss Piggy
  console.log(muppets.length); // 3
}

muppetLab("Dr. Bunson", "Beaker", "Miss Piggy", "Kermit", "Animal")

spread:

function add(a, b, c) {
  return a + b + c ;
}
const arr = [1, 2, 3];

add(...arr); // returns 6

It's all about context. If the three dots occur when you are calling the function, then it's the spread operator. If they happen when you're defining the function, it's the rest parameter.


Anonymous Functions

IIFE: Instantly-Invoked Function Expression

(function(x){ return x + 3 })(2) //=> 5
let fn = function(x){ return x + 3 }(2)
fn //=> 5

Clone this wiki locally