(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.
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 usingconsole.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.
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).
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 ?