Different ways to declare function in JavaScript.

ยท

3 min read

jsfunc.jpg

A function is a block of organized, reusable code that is used to perform a single, related action .

In JavaScript , we can declare a function in different ways :

1. Using function keyword followed by function name

//  example 1
function sum(a, b) {          // function declaration
           return a+b ;
}

// In console
> sum(2,3)                  // function call
< 5                              ## 


// example 2
function foo() {              // foo() function declaration
           const bar = 'hash node !' ;
           return bar ;
}

// In console
> foo()                              // foo function call
< "hash node !"

2. function expression

const sum = function(a,b) {
           return a+b ;
} ;              // end with ';' , shows it is an expression

// In console
> sum(2,4)
< 6

const bar = function() {
           return 'hash node !' ;
} ;

// In console
> bar()
< "hash node !"

The function above is called an anonymous function (a function without a name)

Functions stored in variables do not need function names. They are always invoked (called) using the variable name. The function above ends with a semicolon because it is a part of an executable statement.

3. Arrow function

//  a and b are parameters
multiply = (a,b) => { return a*b ;} 

// In console
> multiply(2,3)
< 6



// we can remove parenthesis and return keyword
multiply = (a,b)=>a*b ;

// In console
>  multiply(2, 3)
<  6



// if we have single parameter
print_name =  name => { return name ;}

// In console
> print_name('foo bar')
< "foo bar"


// no parameter
fun = () => {
    const foo = 'foo';
    return `this is ${foo}`;          // template literal
}

// In console
> fun()
< "this is foo"

This is my first blog , hope you liked it !

Thank you .