DEV Community

Cover image for Different ways of writing functions in JavaScript
Mazin Idris
Mazin Idris

Posted on

Different ways of writing functions in JavaScript

in My first phase with Flatiron school i learned how to write functions in a deferent way.

What is a Function?

  • A function in JavaScript is similar to a procedure—a set of statements that performs a task or calculates a value, but for a procedure to qualify as a function, it should take some input and return an output where there is some obvious relationship between the input and the output.

Types of writing a function:

  • Function Declaration
  • Function Expression
  • Arrow Function

What is a Function Declaration:

  • The function declaration (function statement) defines a function with the specified parameters. You can also define functions using the Function constructor and a function expression

  • An example of a function declaration:

functions are declared with the following syntax.

function functionName(parameters) {
  // code to be executed
}
Enter fullscreen mode Exit fullscreen mode

Declared functions are not executed immediately. They are "saved for later use", and will be executed later, when they are invoked (called upon).

function myFunction(a, b) {
  return a * b;
}
Enter fullscreen mode Exit fullscreen mode

What is a Function Expression:

  • Function Expression is another way to define a function in JavaScript. Here we define a function using a variable and store the returned value in that variable.

  • An example of a function expression:

A function expression can be stored in a variable:

const x = function (a , b) {return a * b};
Enter fullscreen mode Exit fullscreen mode

After a function expression has been stored in a variable, the variable can be used as a function:

const x = function (a, b) {return a * b};
let z = x(4, 3);
Enter fullscreen mode Exit fullscreen mode

What is an Arrow Function:

  • Arrow functions are a new way to write anonymous function expressions, and are similar to lambda functions in some other programming languages, such as Python.

  • An example of a function arrow:

Before Arrow function

Piece = function() {
  return "One Piece!";
}
Enter fullscreen mode Exit fullscreen mode

After Arrow function

Piece = () => {
  return "One Piece!";
}
Enter fullscreen mode Exit fullscreen mode

It gets shorter! If the function has only one statement, and the statement returns a value, you can remove the brackets and the return keyword:

Piece = () => "One Piece!";
Enter fullscreen mode Exit fullscreen mode

Top comments (0)