functions that can be stored in variables or as properties or passed as arguments to other functions
function assert(message, expr) {
if (!expr) {
throw new Error(message)
}
assert.count++
return true
}
assert.count = 0
function definitions start with the
function
keyword
assert
is the function identifierfunctions can have one or more formal parameters called
arguments
functions have a body between
{}
functions may
return
something orundefined
by defaultfunctions can have properties like
count
var sum = function(a, b) {
return a + b
}
(function () {
console.log('Hello!')
})()
var calculator = {
sum: function (a, b) {
return a + b
},
times(a, b) { // ES6 Syntax
return a * b
}
}
console.log(calculator.sum(5, calculator.times(3, 5))) // 20
function say(something) {
if (typeof something == 'function') something()
}
say(function() {
console.log('Hi!')
})
function times(n) {
return function (m) {
return n * m
}
}
console.log(times(3)(5)) // 15
are those specified when declaring a function.
a
andb
are the formal parameters in the function below
function sum(a, b) { return a + b }
every function has an Array-like object called
arguments
containing the arguments passed to a function
function sum() { return arguments[0] + arguments[1] }
console.log(sum(2, 3)) // 5
global
function
block (new in ECMAScript 6)
function addToArray() {
var targetArr = arguments[0];
arguments.slice = Array.prototype.slice;
var add = arguments.slice(1);
return targetArr.concat(add);
}