DEV Community

Heru Hartanto
Heru Hartanto

Posted on • Updated on

Type of function

Using a function is a good way to contain spesific task so you can call it whenever you need, In simple term function is a block of code that is design to perform spesific task. Usually structure of function look like this

function functionName(argument_1, argument_2, argument_n){ 
// code to be executed 
Enter fullscreen mode Exit fullscreen mode

There are various type of functions that you can use depending what your need

Named functions

Create function by giving it name, this is the most common way to create a function

function Add(num1,num2){
    return num1+num2
Enter fullscreen mode Exit fullscreen mode

Imediate Invoke functions

Call a function as soon as they are declared, the benefit of this function is no variable are created so doesn't take up space in the global object or global memory

    return num1 + num2
Enter fullscreen mode Exit fullscreen mode

Anonymous functions

It's the opposite of named functions, a functions without a name, however unlike Immediate invoke functions anonymous function are not executed as soon as they declared.

Usually we need anonymous functions when function is very short in size or when passing a function as an argument to another function such as inside setInverval

var sum = function(num1,num2) { return num1 + num2}

Enter fullscreen mode Exit fullscreen mode

Recursive functions

A function that keeps calling itself until the conditions is failed

function countDown(number){
    var newNumber = number -1;
    if(newNumber > 0){
Enter fullscreen mode Exit fullscreen mode


Function that are part of an object called method

let person = {
        return `${this.firstName} ${this.lastName}`
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

aboss123 profile image
Ashish Bailkeri

Short and to the point, good for beginners!