DEV Community

Md. Jamal Uddin
Md. Jamal Uddin

Posted on • Edited on

Different types of Functions in JavaScript

Different types of Functions in JavaScript

leaf
Photo by Markus Spiske on Unsplash

A JavaScript function is a block of code designed to perform a particular task.

MDN Says:

Functions are one of the fundamental building blocks in JavaScript. A function is a JavaScript procedure — a set of statements that performs a task or calculates a value. To use a function, you must define it somewhere in the scope from which you wish to call it.

A JavaScript function is executed when “something” invokes it (calls it).

Example:

function square(x) {
  return x * x;
}
square(10); // 100
Enter fullscreen mode Exit fullscreen mode

Basic Syntax:

function validFunctionName(parameter) {
  return statement;
}
Enter fullscreen mode Exit fullscreen mode

A function can have multiple parameters or no parameters at all. In the following example, bark does not list any parameter names, whereas power lists two:

bark( )

function bark() {
  return "woof-woof";
}
bark(); //   woof-woof
Enter fullscreen mode Exit fullscreen mode

power( )

function power(base, exponent) {
  let result = 1;
  for(let count = 0; count < exponent; count++) {
    result *= base;
  }
  return result;
}
power(2, 10); // 1024
Enter fullscreen mode Exit fullscreen mode

Function Expression:

A Function Expressions defines a named or anonymous function. An anonymous function is a function that has no name.

var fullName = function(firstName, lastName) {
 return `${firstName} ${lastName}`;
}
fullName("Jamal", "Uddin"); // Jamal Uddin
Enter fullscreen mode Exit fullscreen mode

Arrow Function:

An Arrow Function Expression is a shorter syntax for writing function expressions. Arrow functions do not create their own value.

We can write the arrow function in multiple ways:

First:

it just looks like a regular function expression but have arrow (=>) key.

const double = (value) => {
  return value * 2
}
double(10); // 20
Enter fullscreen mode Exit fullscreen mode

Second:

Omit the return keyword

const double2 = value => value * 2;
double2(10); // 20
Enter fullscreen mode Exit fullscreen mode

Third:

If our function have no parameter

const noise = () => console.log("Pling");
noise(); // Pling
Enter fullscreen mode Exit fullscreen mode
or
const noise2 = _ => console.log("Pling");
noise2(); // Pling
Enter fullscreen mode Exit fullscreen mode

Fourth:

If we have two or more parameter, you can must be used parenthesis

const addAll = (x, y, z) => x + y + z;

addAll(10, 20, 30); // 60
Enter fullscreen mode Exit fullscreen mode

Fifth:

We can use default value in our parameters

const multiply = (a = 2, b = 3, c = 1) => a * b * c;
multiply(2, 2, 2); // 8
multiply(2, 2);    // 4
multiply(3);       // 9
multiply();        // 6
Enter fullscreen mode Exit fullscreen mode

JavaScript is extremely broad-minded about the number of arguments you pass to a function. If you pass too many, the extra ones are ignored. If you pass too few, the missing parameters get assigned the value undefined.

Return:

Remember, the return keyword can ONLY be used inside of a function. let's take a look at another example.

function returnOnlyOnce(){
  return "Hello";
  return "Goodbye";
}
returnOnlyOnce(); // "Hello"
Enter fullscreen mode Exit fullscreen mode

We see from this example that the return keyword can only be executed once in a function. Once it is executed, the function is complete and no other lines of code will be executed.

Function Shorthand methods:

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

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

const fruits = {  
  items: [],
  add(...items) {
    this.items.push(...items);
  },
  get(index) {
    return this.items[index];
  }
};
fruits.add('mango', 'banana', 'guava');  
fruits.get(1); // banana
Enter fullscreen mode Exit fullscreen mode

add() and get() methods in fruits object are defined using short method definition. These methods are called as usual: fruits.add(...) and fruits.get(...).

Generator Function:

ES6 introduced a new way of working with functions and iterators in the form of Generators (or generator functions). 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.

Note: async/await is based on generators. Read more here.

Example:

function * generatorFunction() { 
  yield 'Hello, ';
console.log('I will be printed after the pause');  
  yield 'World!';
}
const generatorObject = generatorFunction();
console.log(generatorObject.next().value);
console.log(generatorObject.next().value);
console.log(generatorObject.next().value);
// output should be following below.
// Hello, 
// I will be printed after the pause
// World!
// undefined
Enter fullscreen mode Exit fullscreen mode

Function with: new Function

The Function constructor creates a new Function object.

var sum = new Function('a', 'b', 'return a + b');
console.log(sum(2, 6)); // 8
Enter fullscreen mode Exit fullscreen mode

Source of truth:

P.S: English is not my native language and this is my very first English article so if you have found any mistake please pardon me also hearts to encourage me to write more articles.

Happy Programming! :)

Who Am I?

This is Md. Jamal Uddin working as a Software Developer based in Dhaka, Bangladesh. I love to learn new things and share them with others. Playing with cutting technologies is my hobby and working with legacy is my day job :). Connect me on Twitter and LinkedIn

Top comments (16)

Collapse
 
gmartigny profile image
Guillaume Martigny

Nice article. Small comment, on the third arrow function example, when you write :

const noise2 = _ => console.log("Pling");
Enter fullscreen mode Exit fullscreen mode

There's an unused parameter named _ instead of no parameter. Both are valid anyway, just wanted to point out the difference ;)

Collapse
 
jaamaalxyz profile image
Md. Jamal Uddin

Yeah! It's intentional. Only for showing variation. Thanks so much for your comment.

Collapse
 
gypsydave5 profile image
David Wickes • Edited

Very comprehensive!

Couple of typos:

Your default parameters examples has ; instead of , between the arguments

const multiply = (a = 2, b = 3, c = 1) => a * b * c;
Enter fullscreen mode Exit fullscreen mode

You're missing a ' on your new Function example:

var sum = new Function('a', 'b', 'return a + b');
Enter fullscreen mode Exit fullscreen mode

(I love that you introduce the Function constructor by the way - hours of fun for everyone there)

Collapse
 
jaamaalxyz profile image
Md. Jamal Uddin • Edited

Bull's eye man! truly I have read my post more than 10 times :) and two of my friends proofread it but no one figured it out. I will be more prepared next time. thanks.

Collapse
 
victordeflos profile image
victordeflos

i am a beginner in coding i am currently finishing frond end courses and for the final test i need an idea to be able to make some program in react. please help or some page on the web where I could find examples and printed codes. thank you very much

Collapse
 
waqardm profile image
Waqar Mohammad

Nice article dude. Your English is great too. Keep it up

Collapse
 
jaamaalxyz profile image
Md. Jamal Uddin

Thanks

Collapse
 
thomasabishop profile image
Thomas Bishop

Very helpful article and admirably free of waffle. Nice work :)

Collapse
 
jaamaalxyz profile image
Md. Jamal Uddin

Thanks

Collapse
 
tamalchowdhury profile image
Tamal Chowdhury

Very in depth and helpful.

Collapse
 
jaamaalxyz profile image
Md. Jamal Uddin

Thanks man!😍

Collapse
 
alvarocaceresmu profile image
Álvaro Cáceres Muñoz

Nice article! You managed to make me understand generators for the first time XD.

By the way, could you please give me a practical use case of the Function consctructor? Thank you

Collapse
 
jaamaalxyz profile image
Md. Jamal Uddin

here is an example Function constructor with implementing a class and you know JavaScript class is a syntactic sugar over the function structure.


class Animal {
  constructor(name, energy) {
    this.name = name
    this.energy = energy
  }
  eat(amount) {
    console.log(`${this.name} is eating.`)
    this.energy += amount
  }
  sleep() {
    console.log(`${this.name} is sleeping.`)
    this.energy += length
  }
  play() {
    console.log(`${this.name} is playing.`)
    this.energy -= length
  }
}

const leo = new Animal('Leo', 7)

wanna know more, please check out this stackoverflow thread

Thanks!

Collapse
 
entrptaher profile image
Md Abu Taher

Go forth!

Collapse
 
jaamaalxyz profile image
Md. Jamal Uddin

Thanks bro 😍 to see you here.

Collapse
 
victordeflos profile image
victordeflos

and whether there is a torrent site for developers or a community.