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

Top comments (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

Thanks for sharing this idea!

Collapse
 
thebox193 profile image
Sir.Nathan (Jonathan Stassen)

Perfect! I love it!

Collapse
 
alibahaari profile image
Ali Bahaari

I appreciate that.

Timeless DEV post...

How to write a kickass README

Arguably the single most important piece of documentation for any open source project is the README. A good README not only informs people what the project does and who it is for but also how they use and contribute to it.

If you write a README without sufficient explanation of what your project does or how people can use it then it pretty much defeats the purpose of being open source as other developers are less likely to engage with or contribute towards it.