When programming, we often need to use the same piece of code multiple times. We can do this by actually writing the same piece of code multiple times - or we can wrap the code blocks in a function that we can call as many times as we want.
Basically, a function is a code block performing a specific task.
A function declaration consist of:
The function keyword.
The name of the function (also known as the identifier) - in the example above, the name of the function is myGreeting.
A set of parentheses that may hold a number of parametres - in the example above, there are no parametres.
The code block that is meant to run when the function is called, enclosed in curly brackets.
To run the function, you need to call it:
Notice that we use the name (or the identifier) of the function followed by the parentheses to call it.
Parametres and arguments
In the example above, we store the name input we get from a prompt in a variable called nameInput. We then declare a function called myGreeting that takes one parametre: name. The function logs the string Greeting + the name that is passed as an argument to the console. When we call the function (last line), we use the name of the function myGreeting and pass the value of nameInput as argument to the function
ES2015 also made it possible to have a standard value that is used if an argument is not passed to a function that takes a parameter:
In the example above, we declare a function called myGreeting that takes one parametre: name. The parametre has a standard value: stranger. The function logs the string Greeting + the name that is passed as an argument, OR stranger if no argument is passed, to the console. In the function call, we don't pass an argument to the functions, which means that Greetings stranger! will be logged in the console.
In connection with function expressions the name of the function is often ommitted - and so the function is known as an anonymous function. They are often stored in variables, normally using the const keyword:
ES2015 introduced arrow functions as a shorter syntax for writing a function:
In the example above, we declare a function called greeting using the const keyword. We then assign a parametre to the function: name, enclosing it in parentheses. We then create an arrow that "leads us" to the code block of the function, enclosed in curly brackets.
The function call looks the same no matter how the function has been declared.