Functions in Javascript

ยท

2 min read

A function is just a collection of some behavior like printing or computing something. In Javascript function is defined using the function keyword, followed by the name of the function, followed by a parenthesis "()" and at the end, it is followed by curly braces "{}".

function print(){
    console.log("hello world");
}

Basically, a function consists of -

  • the name of a function,
  • a list of parameters, enclosed in parenthesis and separated by commas,
  • the statement enclosed in curly braces.

For example -

function addTwoNumbers(a,b){
     return a + b;
}

//for invoking a function we use the name of the function followed by a parenthesis.
addTwoNumbers(4,5); // output will be 9.

Function Expression- When a function is being treated as a value, then that function is called a function expression. Since they can be treated as values then we can also assign or store them in a variable. These types of value is referred as first-class values as the functions are treated as first-class citizens in Javascript. e.g

let addTwoNumbers = (a,b) => {
      return a + b;
} 

addTwoNumbers(4,6); // output will be 10

Function Statement- It is just like a normal function. e.g

function addTwoNumbers(a,b){
      return a + b;
}

The major difference between function expression and function statement is hoisting. Hoisting is a phenomenon in Javascript where you can access the variables before their initialization. e.g If we invoke a function statement and a function express before defining it, then function expression will throw a Type-error, unlike function statement.

The reason behind this behavior is as we know that in function expression, functions are treated as values which are stored in a variable or identifier. During the memory allocation phase, undefined is stored in a variable and you can't call or invoke undefined.

For more information on memory allocation click this ๐Ÿ‘‰๐Ÿผ ram.hashnode.dev/javascript-and-its-behaviour .

Callback Function- It a function is passed as an argument to another function while invoking another function then the argument function is called as a callback function. e.g.

function print(callBack){
    console.log("This is normal function.");
    callBack();
}

function callBackFunction(){
    console.log("This is callback function.");
}

print(callBackFunction);

// The output will be as follows 
// This is normal function.
// This is callback function.

If you found this article helpful, please hit the like button and feel free to comment below! Iโ€™d be happy to talk ๐Ÿ˜ƒ.

If you enjoyed the article and want updates about my new articles, please follow me here and on Twitter @dev_ram9047.