Javascript arguments

From wikinotes


javascript ignores extra arguments passed to functions,
and assigns undefined to unsatisfied params


MDN: default params
MDN: arguments obj

Function Signature

function anniversary(name) { ... }
function anniversary(name, years = 1) { ... }    // default value (eval at call time, safe w/ mutable types )
function anniversary(name, ...invites) { ... }   // 'rest parameter' (friends array collects extra params)
function hello(name, message = "hello " + name)  // default params can refer to prev params

// keyword arguments
function log({msg, time =})
log({msg: "did thing"})


Arguments Object

The argument objects is an array that contains information about arguments passed to a function

function foo(a, b) {
  console.log(arguments.length) // number of args
  console.log(arguments[2])     // the 3rd arg

foo(1, 2, 3)

Spread array as arguments

You can use ...var to expand an array as function parameters.
Like splat, or list expansion in other languages.

function person(age, name, height)
person(...[123, "wesley", 5])