HomeWeb DevelopmentThe Importance of Functions in JavaScript

The Importance of Functions in JavaScript

The main difference between JavaScript and most other languages is that JavaScript allows us to create a function as a stand alone entity, and to pass it as an argument to a method, which can accept it as a parameter, just as we can any other object type.

This allows us to create compact code that is easy to understand, partially because functions can appear anywhere in the code where an expression can appear. This feature can eliminate the need to pollute your code with unnecessary names when a function isn’t going to be referenced from multiple places within the code. Functions are the fundamental building blocks for reusable code libraries.

In JavaScript, functions are first-class objects. Functions can be:

  • created via literals
  • assigned to variables/array entries/properties of other objects
  • passed as arguments to functions
  • returned as values from functions
  • and can even possess properties that can be dynamically created and assigned.

Functions in JavaScript are treated like any other object in the language, with the exception that they can be invoked in an asynchronous manner.

Let’s take a look at a chunk of code from John Resig & Bear Bibeault’s Secrets of the JavaScript Ninja to prove my point.

/****Three different ways of defining functions*******/
	function isNimble(){ return true; } 
	var canFly = function(){ return true; }; 
	window.isDeadly = function(){ return true; }; 
	log(isNimble, canFly, isDeadly);

/*****Example showing how the order of function definition does not matter******/
	var canFly = function(){ return true; }; 
	window.isDeadly = function(){ return true; }; 
	assert( isNimble() && canFly() && isDeadly(), "Still works, even though isNimble is moved." );
	function isNimble(){ return true; }

/********Where can assignments be accessed?**********/
	assert( typeof canFly == "undefined", "canFly doesn't get that benefit." ); 
	assert( typeof isDeadly == "undefined", "Nor does isDeadly." ); 
	var canFly = function(){ return true; }; 
	window.isDeadly = function(){ return true; };

/******Functions can be defined below return statements********/
	function stealthCheck(){ 
	  assert( stealth(), "We'll never get below the return, but that's OK!" );
	  return stealth();
	  function stealth(){ return true; } 
	}
	stealthCheck();

So go out there, and write some reusable code that hinges on the power of functions in your code.