Javascript - Functions


Arrow Functions

Arrow functions is a more compact and limited version of a function expression.

var func = (arg1, arg2, ..., argN) => expression
var sum = (a, b) => a + b;
console.log(sum(5, 2);)

If only one argument exists, parentheses can be omitted:

var square = n => n ** 2

When there are no arguments, parentheses are still required.

Multi-line arrow functions require {}

var sum_square = (a, b) => {
    let sum = a + b;
    return sum ** 2;
}

Default Values

Javascript allows default parameter values

function func(apple="Apple") {return apple;}

Default parameters can be more complex, for example, a function can be call when a value is not given and the returned value will become the variable.

function func(apple=apples())

Things to keep in mind:

  • Arguments are passed by value, objects are passed by reference. Similar to Python.
  • Functions may access outer variables
  • Functions that don't return anything return undefined

Function Expressions

Function expressions are like lambda functions in other languages.

var sum = function(a, b) {
    return a + b;
}

var s = sum(5, 2);

Syntax

function name(param1, param2, param3) {
    // Code
    // C++ like return statement
}