Defining a function
Function Declarations
There are different ways to define a function in JavaScript, but I will cover three of the most common.
Function Literal
To define a function literal, you can use a function declaration:
function hello( ) {
console.log(βHello World!β);
}
The syntax of this function starts by starting with the function keyword and is followed by the name assigned to the function, in this case βhelloβ followed by parenthesis and finally followed by a block of code for the function.
Function Expressions
Function expressions is another way to define a function, this is done by assigning an anonymous function to a variable:
const bye = function ( ) {
console.log(βBye Worldβ);
};
It is called anonymous function because it does not have a name. It is just created and assigned to a variable.
But, you can also create a named function expression:
const bye = function bye( ) {
console.log(βBye Worldβ);
};
In this case the name of the function is βbyeβ and it is assigned to the variable βgoodbyeβ.
Function ( ) Constructors
We can also create a function by using the Constructor Function ( ). Itβs body is entered as a string:
const hi = new function (βconsole.log(βHi Worldβ); ) ;
Although this is another way to define a function, it is not recommended because there are some problems associated with placing a string inside the function body, specially because of the different number of quotation marks in the console.log.
ES6 introduced a new way to define functions using arrow notation, named 'Arrow Function, but I will make a new blog about it.
Top comments (1)
Nice explanation ;-).
You have a small typo in one of the code examples :-)
const goodbye = function bye( ) {
console.log(βBye Worldβ);
};