Functions are one of the fundamental building blocks in JavaScript. A function is a set of statements that performs a particular task of the program. This task could be just a little part of a program or even the whole program.
function sayHi()
{
console.log('Hello!');
}
==> as many as times as you invoke the function, that many times it will execute the code between the curly braces.
( in our case: 'Hello!');
sayHi();
// keyword function parameters (if any)
// ^ name ________|
// | | |
function sayHello() {
// the code or so called the body of the function
// return an expression (if needed)
}
// function declaration with a parameter
function sayHello(language) {
switch (language) {
case 'fr':
console.log('Bonjour!');
break;
case 'ger':
console.log('Hallo!');
break;
case 'esp':
console.log('Hola!');
break;
default:
console.log('Hello!');
}
}
// function invocation with or without an argument
sayHello('ger'); // => Hallo!
sayHello('fr'); // => Bonjour!
sayHello('esp'); // => Hola!
sayHello(); // => Hello!
- Parameter is the variable between the parentheses which is part of the function declaration. In the case above: The
language
variable. Note that this word is a placeholder and can be any word possible.- Argument is the value passed to the function at the moment of its invocation. In the case above: The different strings
ger
,fr
, oresp
that are passed and stored in the parameter.
// we passed argument "ger"
// |
// -----------
// |
sayHello('ger'); // => Hallo!
// we passed argument "fr"
sayHello('fr'); // => Bonjour!
// we passed argument "esp"
sayHello('esp'); // => Hola!
// we didn't pass any arguments, so the default part was executed
sayHello(); // => Hello!