Different ways to declare a function in javascript

Ajay Yadav
5 min readOct 3, 2020
Different Ways To Declare A Function In JavaScript

A javascript function is a fundamental building block of code that is designed to define once and called multiple times to perform a different-different task. Also, there are different ways to declare the function in javascript.

A javascript function is executed when “something” invokes it (calls it) using the invoke method.

Basic Syntax

function validFunctionName(parameter){ 
return statement;
}

Example of javascript function

function add(x) { 
return x + x;
}
add(10); // 20

In the above, a javascript code snippet is a valid function name and is a parameter that is a pass to function when the function is invoked.

And x + x is a statement and the return keyword is used to return the value from a function. Now, add(10) is a function invoke with value 10 passes to function as a parameter. As a result, the function returns 20 value after addition.

To know more about the javascript function click here.

I have something more for you -

Check out our daily javascript quiz -

  1. JavaScript Quiz — switch case can change a variable value
  2. JS Quiz — zero date can give get full year method
  3. JS Quiz — does set object really store duplicate object
  4. JavaScript Quiz — what does the async array map function return

Ways To Declare Javascript Function

In javascript, there are different-different ways to declare a javascript function which you will be going to learn in this tutorial.

So, make sure to go through all the points as it will help you not only in javascript interviews but also during project development.

Also, you will understand when to use a specific function type in certain circumstances.

A. Function Declaration

A Function Declaration defines a named function. To create a function declaration you use the function keyword followed by the name of the function.

Function declarations are hoisted which allowing the function to be used before it is defined.

Example of a function declaration

The following example uses a function declaration.

// function declaration

function mutiplyByTwo(num) {
return num * 2;
}
mutiplyByTwo(22); // => 44 mutiplyByTwo(11); // => 22

B. Function Expression

A function expression is defined by the function keyword followed by an optional function name. And an optional list of parameters in a pair of parenthesis (para1, para1..., paramN) and a pair of curly braces {...} that contain a function body.

However, the function can be named or anonymous function.

Examples of a function expression

The following example uses a javascript function expression with the const keyword.

// Function expressionconst count = function(array) { 
return array.length;
}
count([1, 3, 5, 7, 9]); // => 5 const fullName = function(firstName, lastName) {
return `${firstName} ${lastName}`;
}
fullName("JS", "Startup"); // => "JS Startup"

Most importantly, function expression creates a function object that can be used in a different-different situation.

As function expression declares with named function and anonymous function.

C. Function Constructor (new Function)

In Javascript, functions are the first-class object. A function is a regular object of type function. A function can also be declared using a function constructor with a new keyword.

Example of function constructor

First, Let’s create a function that adds two numbers:

const numberOne = 10, numberTwo = 15;const sumFunction = new Function(numberOne, numberTwo, 'return numberOne + numberTwo' ); sumFunction(10, 15) // => 25

D. Arrow Function

An arrow function is defined using a pair of parenthesis () that contains the list of parameters (param1, param2, ..., paramN), followed by a fat arrow => and a pair of curly braces {...} that contains a function body.

Therefore, an arrow function Expression is a shorter syntax for writing function expressions. Arrow functions do not create their own value.

Some Examples of Arrow Function

The following example uses an arrow function.

A. Function Keyword Replace By Fat Arrow Function

const square = (value) => { 
return value * value
}
square(10); // 100const square = (value) => value * value; square(10); // 100

C. Remove on a single parameter

const square = value => value * value; square(10); // 100

D. Function Have No Parameter

const getName = () => console.log("JS Startup"); getName(); // JS Startup

or

const getName = _ => console.log("JS Startup"); getName(); // JS Startup

As there are also other ways to declare arrow function which you can find during project development.

E. Generator Function

ES6 introduced a Generator Function which is a new way to declare and working with a function. The generator function returns a generator object.

Most importantly, generator function syntax is similar to a function expression, function declaration, or method declaration. In other words, it’s same as other just that it requires a star character *.

A generator (*) is a function that can stop midway and then continue from where it stopped. In short, a generator appears to be a function but it behaves like an iterator.

Generator Function Syntax

function* ()

Example of a generator function

The following example uses a generator function with star *.

function * generatorFunction() { 
yield 'JS ';
console.log('I will be printed after the pause');
yield 'Startup!';
}
const generatorObject = generatorFunction(); console.log(generatorObject.next().value); // => JS // It will be printed after the pause console.log(generatorObject.next().value); // => Startup console.log(generatorObject.next().value); // => undefined

In the above statement, the first function is declared then it’s used step by step process.

Note: async/await is based on generators.

F. Function Shorthand method

In javascript, the function Shorthand method definition can be used in a method declaration on object literals and ES6 (ES2015) classes. We can define them using a function name, followed by a list of parameters in a pair of parenthesis (param1, param2, …, paramN) and a pair of curly braces { … } that delimits the body statements.

The following example uses a shorthand method definition in an object literal:

Example of Function Shorthand Method Definition

const room = { 
items: [],
add(...items) {
this.items.push(...items);
},
get(index) {
return this.items[index];
}
};
room.add('JS', 'Startup', 'JavaScript'); room.get(1); // Startup

So, add() and get() methods in objects are defined using short method definition. These methods are called as usual: room.add(...) and room.get(...).

Conclusion

To participate in our javascript quiz or challenges, tutorial, tips & tricks make sure to join our jsstartup newsletter. So, you can able to participate in our daily challenges & learn the javascript concept.

And last but not the least, don’t forget to like, comment and share. It gives us a morale boost to remain to continue. Also, join our Facebook Page

If you have any questions, please feel free to ask me in the comment section and also let me know if you have any suggestions. As suggestions are always welcome.

If you like this article please give me a clap.

Originally published at https://jsstartup.com on October 3, 2020.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Ajay Yadav
Ajay Yadav

Written by Ajay Yadav

Nothing special just willing to help and share my knowledge with everyone.

No responses yet

Write a response