Press ESC to close

JavaScript functions

0 1693

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:


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);

In this lesson we have introduced functions in JavaScript, in the next lessons we will deepen the subject with other examples.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Introduction to JavaScript language

Learn JavaScript – basic concepts

Other stories

alert JavaScript

Next Story

JavaScript for loop

Previous Story