Skip to content

Functions

sergio edited this page Nov 10, 2020 · 9 revisions

JavaScript loves functions.

JavaScript makes this love clear from our first encounter with functions. It makes functions first-class data. Functions, that is to say, "frozen" work, can be passed around like "primitive" data (Strings or Integers, etc.). JavaScript passes around its functions, shoves them to Arrays, makes them accessible via a key in an Object, and more. Few other programming languages share this point of view.

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
const Calculator = {
  add: function(a,b) {
    return a + b;
  },
  subtract: function(a,b) {
    return a - b
  },
  multiply: function(a,b) {
    return a * b
  },
  divide: function(a,b) {
    return a / b;
  }
}

Inner Functions

function outer(greeting, msg="It's a fine day to learn") { // 2
  let innerFunction =  function(name, lang="Python") { // 3
    return `${greeting}, ${name}! ${msg} ${lang}` // 4
  }
  return innerFunction
}

outer("Hello")("student", "JavaScript") // 1, 5
//=> "Hello, student! It's a fine day to learn JavaScript"

Keep in mind, it's not the case that we have to invoke functions like this:

outer("Hello")("student", "JavaScript")

We could:

let storedFunction = outer("Hello")
// ... lots of other code
storedFunction("student", "JavaScript")
//=> "Hello, student! It's a fine day to learn JavaScript"
let fn = function(multiplier) {
    function(fare) { return fare * multiplier }
}

fn(3)(4) //=> 12

let fn_custom = fn(3)

fn_custom(4) //=> 12
function sayHello(name="") {
  console.log(`Hello${name}`)
}

let sayHola = function(name="") {
  console.log(`Hola${name}`)
}

functionUsingCallback(sayHello, sayHola, function(name="") {
  console.log(`Ni Hao${name}`)
})

function functionUsingCallback(en, es, zh, name){
  en()
  es()
  zh()
}

/* Prints */
//=> Hello
//=> Hola
//=> Ni Hao

let [answer, theBase] = (
  function(thingToAdd) {
    let base = 3
    return [
      function() { return base + thingToAdd },
      function() { return base }
    ]
  }
)(2)
answer() //=> 5
console.log(`The base was ${theBase()}`)
// OUTPUT: The base was 3

Clone this wiki locally