functions

April 13, 2023 - Reading time: 5 minutes

Dividing the code into functions is essential.

Basically, a function can take an input (from zero to several parameters - a parameter can be a function) and provide a result whenever it's called.

In JavaScript, a function is a value.

Named function

Declaration

A declared function is visible in the whole script.

function sayHello() {
console.log("hello")
}

The function name is usually a verb briefly describing the action. One function should do one action. Here's how to call it:

sayHello() // consols "hello"

Return

When reached, the return keyword makes the function stop and returns the results if any (default return value is undefined)

function checkAge(age) {  return age >= 18 ? true : false;}
checkAge(18) // returns true
checkAge(10) // returns false

A function can update variables without returning anything. For instance (from FreeCodeCamp) :

let sum = 0;

function addSum(num) {
  sum = sum + num;
}

addSum(3); // sum variable now equals 3
console.log(addSum(3)) // returns undefined

Default parameter value

Consider this function expecting three parameters:

function add(a, b, c) {  
return a + b + c
}

If a parameter is not passed on, it's value is considered as undefined.

add(4, 2) // returns NaN (Not a Number)

You can specify a default value if the parameter is omitted:

function addition(a, b, c = 0) {  
return a + b + c
}
add(4, 2) // returns 6

Rest parameter

The rest parameter (...param) is useful if we want a function to work with a variable number of arguments. Arguments passed this way are stored as an array. Check out this example:

function howMany(...args) {
  return args.length;
}
console.log(howMany(0, 1, 2)); // returns 3
console.log(howMany("string", null, [1, 2, 3], { })); // returns 4

JSON object parameter

If parameter order does not matter, you can use a JSON object as a parameter:

function myFunction(params) {
  // do something
}

myFunction( { prop1: value1, prop2: value2 } );

Anonymous function

Anonymous or expressed functions are useful when we don't need to re-use them anywhere else in the code. It exists once it's reached. Here are two use-cases with possible syntax:

Calculate a value and pass it to a variable

Examples from FreeCodeCamp:

const myFunc = function() {
  const myVar = "value";
  return myVar;
}

With ES6 it can be shortened into an arrow function:

const myFunc = () => {
  const myVar = "value";
  return myVar;
}

Note that if we only want a value to be returned, then "return" keyword as well as brackets surrounding the code can be omitted.

const myFunc = () => "value";

If we need to pass arguments, the same principle as for named functions applies, except than parenthesis enclosing the parameter can be omitted if there's only one parameter:

const doubler = item => item * 2;
doubler(4);

const multiplier = (item, multi) => item * multi;
multiplier(4, 2);

Create an objet

Consider this object literal declaration (from FreeCodeCamp) which returns an object containing two properties:

const getMousePosition = (x, y) => ({
  x: x,
  y: y
});

Since ES6 a syntactic sugar exists. It eliminates the redundancy:

const getMousePosition = (x, y) => ({ x, y });

Here, x will be converted to x: x.

Auto-executed function

Write the function into parenthesis and call it at the end with parenthesis as well. This is call a IIFE notation.

(function(a) {
  console.log(a);
})("hey");