Functions

Page section: posts

(See the old functions page too)

Function declarations

So functions can be written in different ways.

The original way is called function declarations:

function functionName() {
 // code to execute`  
}

Function declarations are hoisted meaning that although they may be below something they need in the js file they cans still work because they behave as though they’re at the top.

Function declaration also do not require a semi-colon at the end, though function expressions, like all expressions do.

Parameters

Functions can take parameters inside the brackets. These are local variables to be used inside the function. Simply by adding them in the parentheses you are creating them.

function add(num1, num2) {
    alert( num1 + num2 );
}

This will work when the function is called:

add(475, 1045);

These values are called arguments.

You can set default values for the parameters

function add(num1=12, num2=24) {
    alert( num1 + num2 );
}

from arrays

You can also use array notation in functions:

let nums = [34, 82];

add(nums[0], nums[1]);

If the function is called without paramenters, add(), or with just one paramenter the default values will be used instead.

Using return

In her article on functions Tania Rascia’s introductory statement reads: “A function is a block of code that performs an action or returns a value”.

The return statement ends function execution and specifies a value to be returned to the function caller.

MDN docs

When the return keyword is used, the function ceases to execute and the value of the expression is returned. Although in this case the browser will display the value in the console, it is not the same as using console.log() to print to the console. Invoking the function will output the value exactly where the function was invoked. This value can be used immediately or placed into a variable.

Tania Rascia

The function can set up to do the calculation but not display it anywhere (such as the console or an alert message).

function subtract(x, y) {
    return x - y;
};
// It can then be used elsewhere
console.log(subtract(12, 7))

NB. You don’t need to use return in function expressions.

In abbreviated arrow functions where the curly braces are omitted you should also omit the return key word also.

const sumof = function add(x, y) {
    return x + y;
}
<button onclick="alert(sumof(23, 73));">Add two numbers</button> 

NB. return is not necessary in arrow functions

Calling a function

A function does nothing until it’s called or invoked.

To call the function:

functionName()

The same is true it’s stored in a variable such as:

const myFunc = () => {
    // some code...
}

then you would use myFunc() to call it.

You can add parameters to the function:

function divide(a, b) {
    alert(a / b);
}

When you call the function the paramenters are called arguments:

divide(45, 16)

Functions vs Methods

Functions and methods are more or less the same thing. However methods are defined an associated with objects and they’re called using dot notation:

myElement.toUpperCase();

Function expressions

You can store a function in a variable. These are called function expressions.

const add = function addition(a, b) {
    return a + b
}

You can now invoke the function in the same way as function declarations. To use the add function expression above:

add(2, 3)

NB. Function expressions are not hoisted the way function declarations are. So like variables they are best defined at the top of the code before being called.

Anonymous functions

In function expressions the function name can be omitted. This creates an anonymous function:

const add = function (a, b) {
    return a + b
}

Arrow functions

Arrow functions have become the default way of writing functions for many. They abbreviate the syntax even further. Take out the the word function and put a => after the parentheses.

Arrow functions are always anonymous functions and a type of function expression.

Tania Rascia

const add = (a, b) => {
    return a + b
}

NB. If there is only one parameter you don’t need the brackets BUT if there is no parameter you need empty brackets.

The curly braces can be omitted if there is only one statement and the key word return should be omitted too which is implied in this kind of statement.

const add = a => a + 5;

const fives = () => 5 + 5;

const multiply = (x, y) => x * y;

todos.forEach((todo) => console.log(todo));

Callback functions

The last forEach() example is a callback function.

A callback is a function that is passed into another function as an argument to be executed later. (Developers say you “call” a function when you execute a function, which is why callbacks are named callbacks).

zellwrk.com

Callback functions are functions that are passed to another function as one of their arguments. In the example below the forEach() method uses an anonymous function to log each value to the console.

A more verbose way of writing this (not using an arrow function) could be:

todos.forEach(function(todo) {
    console.log(todo);
});

Here’s another example where the function is a separate function declaration:

let names = ['Tim', 'Joe', 'Bob', 'Sam', 'Suz'];

function logThem(name, index) {
  console.log(name + ' at index ' + index);
}

names.forEach( logThem );

This makes the function reusable. All you need do is use the last line, names.forEach( logThem ); but change the word names to a different array name.

Alternatively everything could be compacted into one line by declaring the array on the forEach() and using an arrow function:

['bus', 'lorry', 'plane'].forEach(name => console.log(name));

using todos.forEach((todo) => console.log(todo));.

Calling function expressions

This invokes the cube function:

const cube = z => {
    z = prompt("number?");
    alert(z * z * z);
}

It is called the same way as regular functions:

<button onclick="cube()">cube</button>

Using map

Arrow functions are a concise way to use filters like map.

Below a new array is created multiplying each array value by 2.

const newArray = [1, 2, 3, 4].map(num => num * 2);

const newArray2 = [1, 2, 3, 4].filter(num => num % 2 === 0);

The this binding

In an object that contains a function the function can use this to refer to the anything in the whole function. However if an arrow function is used then this is scoped to the function itself so a regular function maybe necessary.

let person = {
    firstName = 'Joe',
    lastName = 'Bloggs',
    getName = function() {
        return this.firstName + " " + this.lastName;
    }
}

Local and Global Scope at the same time

You can have a variable with local and global scope. That is defined firstly within a function and then outside of it but both with the same name. The local will take precedence over the global version.

So this works:

function square(num) {
    num = prompt("wot number u want?");
    alert(num *= num);
}

with

<button onclick="square(); alert(num)">square()</button>

Date

A current time and date stamp can be created using:

const nuDate = new Date();

Today ?

  1. Tania Rascia article on functions
  2. Tania on Arrow functions
  3. All Tania’s JS articles
  4. Sitepoint on Fat Arrow Functions
View contents of: /static/js/tryout-arrays.js
const fruit = ["apples", "bananas", "cantaloupe", "dorians"];

const scientificFruit = [
  "Bell pepper",
  " Chile pepper",
  " Corn kernel",
  " Cucumber",
  " Eggplant",
  " Jalapeño",
  " Olive",
  " Pea",
  " Pumpkin",
  " Squash",
  " Tomato",
  " Zucchini",
];

const todos = [
  {
    id: 1,
    text: "Take out rubbish",
    isCompleted: true,
  },
  {
    id: 2,
    text: "Meet with boss",
    isCompleted: true,
  },
  {
    id: 3,
    text: "Dental appointment",
    isCompleted: false,
  },
];

function showFruit() {
  document.getElementById("fruitlist").innerHTML = fruit;
}

function fruitLoops(frt) {
  document.getElementById("fruit-loops").innerHTML += frt + '<br>';
}

const butt1 = document.getElementById("listfruit");

butt1.addEventListener("click", () => {
  document.getElementById("fruitlist").innerHTML = fruit;
});

const butt2 = document.getElementById("fruit2");

butt2.addEventListener("click", function () {
  document.getElementById("fruitlist").innerHTML = fruit[1];
});

const butt3 = document.getElementById("scientific");

butt3.addEventListener("click", function () {
  document.getElementById("fruitlist").innerHTML = scientificFruit;
});

const butt39 = document.getElementById("copying");

butt39.addEventListener("click", function () {
  const otherFruit = fruit.slice(1, 3);
  console.log("what apphen?");
  alert(`A new array called otherFruit now contains ${otherFruit}`);
});

// For buttons showing Array Methods

let myVar = [[1, "tree"], 2, 3, 4, 5, 6];
const mySubVar = ["frog", "Linsang", "stink badger"];

const showMyVar = document.getElementById("show-my-var");
const smvList = document.getElementById("smv-list");

function listMyVar() {
  smvList.innerHTML = ``;
  for (let i = 0; i < myVar.length; i++) {
    smvList.innerHTML += `<li>${myVar[i]}</li>`;
  }
}

showMyVar.addEventListener("click", () => {
  listMyVar();
});

const resetMyVar = document.getElementById("reset-my-var");

resetMyVar.addEventListener("click", () => {
  myVar = [[1, "tree"], 2, 3, 4, 5, 6];
  listMyVar();
  //   alert("reset");
});

Table of Contents