JavaScript functions are fundamental blocks of code, consisting of one or more instructions, which perform one or more actions.
A function in JavaScript is defined by the keyword function followed by the name of the function and by the arguments, however optional, enclosed in round brackets and separated by commas. The instructions are then placed between the curly brackets.
To call a function then simply indicate the name of the function and the arguments in parentheses, if any.
JavaScript functions – first example
Let’s first take an example by creating a simple welcome function that starts an alert with a welcome message.
So we don’t insert any parameters in round brackets.
function welcome(){
alert('Welcome in coding creativo');
}
A function in this way is only defined, that is, it does nothing until it is called.
To recall it (invoke it), the name of the function followed by the round brackets is sufficient.
So here’s an example:
welcome();
JavaScript functions – return instruction
In the body of the functions there may be a return statement that is used to return a value or data.
Let’s take another example where we use parameters. We define a sum function with two placeholder values a and b.
Inside the curly brackets we insert the calculation of the sum of the two numbers and return the result to the function.
function sum(a,b){
return a + b;
}
So we invoke the sum function indicating the real values in brackets and store the value it returns in a variable sumNumbers.
We then display the value obtained in the browser console.
var sumNumbers = somma(5,6);
console.log(sumNumbers);
In this lesson we have introduced functions in JavaScript, in the next lessons we will deepen the subject with other examples.
Some useful links
Introduction to JavaScript language
Learn JavaScript – basic concepts