DEV Community

Cover image for Popular Ways To Write JavaScript Functions
Francisco Moretti
Francisco Moretti

Posted on • Originally published at franciscomoretti.com

Popular Ways To Write JavaScript Functions

What is Function Syntax? đź“ť

JavaScript offers various ways to define functions, each with its own strengths and use cases. Here are the most commonly used methods:

Function Declaration

Function Declaration provides a straightforward syntax for defining functions.

function functionName(parameters) {
    // Function body
    return expression
}
Enter fullscreen mode Exit fullscreen mode

Usage: Perfect for defining functions that need to be hoisted, meaning they can be called before they are declared.

Function Expression

Function Expression assigns a function to a variable.

var functionName = function(parameters) {
    // Function body
    return expression
};
Enter fullscreen mode Exit fullscreen mode

Usage: Useful for anonymous functions or when you want to assign a function to a variable.

Arrow Function (ES6)

Arrow Function introduces a concise syntax.

const functionName = (parameters) => {
    // Function body
    return expression
};
Enter fullscreen mode Exit fullscreen mode

Usage: Provides a concise syntax, especially handy for short, one-liner functions. It also maintains the lexical this, making it particularly useful for callbacks and event handlers.

Arrow Function with Implicit Return (ES6)

Arrow Function with Implicit Return offers a shorthand for arrow functions. This example returns the expression.

const functionName = (parameters) => expression;
Enter fullscreen mode Exit fullscreen mode

Usage: Offers a shorthand for arrow functions when the function body consists of a single expression.

Top comments (0)