Functions - JavaScript

Functions - JavaScript

Quite often we need to perform similar action in many places of the script. e.g. suppose we need to show some message after action/task(i.e. user logs in/out).

A function is sub-program or main building block of program designed to perform a particular action/task.

Functions allows code to be called many times without repetition. Functions are executed when they are called. Values can be passed into functions and used within the function.

  • Local Variables - variables declared inside function, only visible inside that function. Values passed to a function as parameters are copied to its local variables.
  • Outer(Global) Variables - variables declared outside function.
  • Parameters - values can be passed to function as parameter.
  • Default Values - function can have default values as well.
  • Returning Value - A function can return a value back into the calling code as the result.
Functions should be short and do exactly one thing. If that thing is big, maybe it’s worth it to split the function into a few smaller functions.

Function Declaration vs Function Expression

Funciton Declaration-                 Funciton Expression-

function sum(a, b) { 		      let sum = function(a, b) {
     return a + b;			 return a + b;
}				      }
declared as seperate statement.	      created & explicitly assigned to variable.

It can be called earlier than it      It is created when the execution reaches it and 
is defined. Usable inside 	      is usable only from that moment.
block/script, if declared inside 
block then it cant be visible 
outside block

cannot pass as parameter.	      can be used to pass as parameter.

Nice article Moreshwar Boramanikar. You can use GitHub gist for codes to look good in the article. Reference: gist.github.com

To view or add a comment, sign in

Explore content categories