DEV Community

loading...

Defining Functions

banesag profile image Banesa Guaderrama ・1 min read

alt text

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.

Discussion (1)

pic
Editor guide
Collapse
shaunie2fly profile image
Shaun

Nice explanation ;-).

You have a small typo in one of the code examples :-)

const goodbye = function bye( ) {
console.log(‘Bye World’);
};