JS Startup

Challenges, Tips & Tricks & Tutorials

Different ways to declare function in javascript

Different ways to declare function in javascript

JavaScript Function –

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, javascript code snippet, add is a valid function name and x is a parameter which is pass to function when the function is invoked.

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

To know more about javascript function click here.

I have something more for you –

Check out our 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

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 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, function can be named or anonymous function.

Examples of function expression

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

const count = function(array) { // Function expression
  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. Function can also be declare using function constructor with new keyword.

Example of function constructor

First, Let’s create a function that add 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 a arrow function.

A. Function Keyword Replace By Fat Arrow Function

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

B. Remove the return keyword

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

C. Remove bracket on 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 generator function

The following exmaple 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
// I will be printed after the pause

console.log(generatorObject.next().value); // => Startup
console.log(generatorObject.next().value); // => undefined

In the above statement, firstly function is declare 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 room object 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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top
0 Shares
Share via
Copy link