DEV Community

Ali Bahaari
Ali Bahaari

Posted on

Three types of functions in JavaScript!

JavaScript

There are 3 ways which functions can be declared in JavaScript.
In this article, I'm going to show you and compare these.

Named Functions

This type receives a name for the function declaration:

function myFunction(text) {
    console.log(text);
}

myFunction('Hello World!');
Enter fullscreen mode Exit fullscreen mode

Anonymous Functions

This type doesn't receive explicitly any name for declaration. Instead, the function will be assigned to a variable for invoking.

const myFunction = function(text) {
    console.log(text);
}

myFunction('Hello World!');
Enter fullscreen mode Exit fullscreen mode

Arrow Functions

This type is similar to lambda functions in other programming languages. It doesn't receive explicitly any name (it will be assigned to a variable for invoking) and the structure is so simpler.

const myFunction = (text) => {
    console.log(text);
}

myFunction('Hello World!');
Enter fullscreen mode Exit fullscreen mode

BOOM! Now you've been learning 3 types of function declaration in JavaScript which may help you a lot in developing web applications and etc.

You can or may want to connect with me through the networks I've put on my website: Ali Bahaari's Website

Discussion (4)

Collapse
parenttobias profile image
Toby Parent

In the case of the first, this is not really advisable. You see, saying

function myFunction(){/* body */}
Enter fullscreen mode Exit fullscreen mode

JavaScript parses and does this:

var myFunction = function myFunction(){}
Enter fullscreen mode Exit fullscreen mode

Why might that be a bad thing? Because var will hoist, and usually to the global scope. The AitBnB style guide does a great job of explaining why this is an antipattern.

Collapse
alibahaari profile image
Ali Bahaari Author

Thanks for sharing this idea!

Collapse
thebox193 profile image
Sir.Nathan (Jonathan Stassen)

Perfect! I love it!

Collapse
alibahaari profile image
Ali Bahaari Author

I appreciate that.