JavaScript Functions as JavaScript Variables

DZone 's Guide to

JavaScript Functions as JavaScript Variables

A JavaScript Function is a JavaScript Variable until it is executed (evaluated). Read on for a full explanation.

· Web Dev Zone ·
Free Resource

Function Basics. Level Set!

If you are coming from a programming background, you all know what declaring a function means, right? It looks something like this in JavaScript. Some programming languages enforce specifying a return type. JavaScript does not, but let’s keep that discussion for some other time.

function add(x,y) {
return x+y;

Having declared a function just makes it available for use in your program. It does not execute it right away (of course!). In order to execute the function in JavaScript, we drop the keyword “function” and pass actual values within the parentheses, such as shown below.


Instead of declaring and executing the functions in 2 different steps, JavaScript also provides an approach to declare and execute the function immediately. This is also called as IIFE (stands for: Immediately-invoked Function Expression). An example is shown below.

function add(x,y) {
) ();

In this example, please look at specifically how parentheses are used. Note: Semi-colon is not mandatory in JavaScript, but is usually a good practice to separate blocks of code.

Here Comes the VARIABLE Part.

Let’s start with an example to explain this.

var add = function(x,y) {
return x+y;

This is a valid declaration of a function in JavaScript, rather a powerful one (I think). It is not only declaring the function, but also storing the declaration in the variable named add. This is close to storing the result of an expression in a variable, except for the difference that the expression is evaluated (executed) and the result is stored in the variable versus in this case, the function is not executed to store the result in the variable. Thus, the variable is now the function declaration and therefore, the following call will still provide the same result as it did in the earlier declaration. Test this code out in your browser console window. (TIP: If you are using Chrome browser, click Ctrl+Shift+i and find your console window, usually in the bottom half. You may simply copy/paste each line one by one. This way you don't have to write an entire JavaScript file for this quick test.)

function add(x,y){console.log("ADD:" + (x+y) )};
var sum = function(x,y){console.log("SUM:" + (x+y) )};
add(3,4); sum(3,4);
RESULT: (In your console window)
ADD: 7
SUM: 7

So, where does this lead to?

It leads to an important concept that makes JavaScript very powerful. My opinion is that this is important to understand another very important feature in JavaScript called as callback.

We will try to end this blog with an example that would allow you to look forward into callbacks.

Last Step. Passing Functions as Parameters to Another Function.

Now that we have established that a function can be stored in (actually, assigned to) a variable, these variables can be passed as parameters to another function. Thus, instead of executing the function and passing the result as a parameter to the function, the entire function declaration can be passed as a parameter. This is huge! Isn’t it? Maybe an example will make it more convincing. So here we go.

  var A = function() {
    console.log(“I am A");
  var B = function(a) {  // ‘a’ is function declaration passed to ‘B'
    console.log(“I am B”);
    a(); // note we are actually executing the function ‘a' here
// Now let’s call function B here which takes declaration of function A as the parameter

RESULT: (In your console window)
I am B
I am A

If you have used JavaScript to a certain extent, especially for creating client-side events such as timeout or intervals, notice that you are already passing a function to the setTimeout and setInterval JavaScript functions. Check out this example. There are two implementations of setTimeout but both essentially provide the same result.

/* *************************************************
   setTimeout has 2 parameters, 
   1. a function to doSomething
   2. timeout value in milliseconds
************************************************* */
// This will write to console after 1 second
  setTimeout( function() {
    console.log(“Timed out from setTimeout”);
  }, 1000 );

       var doSomething = function() {
          console.log(“Timed out from function write");

// This also writes to console after 1 second
// Function write is passed to setTimeout function 
  setTimeout(doSomething, 1000);

Looking Ahead Into Callback

As mentioned half way in the blog, this powerful concept of declaring functions and assigning them to variables sets foundation for another powerful concept called Callback. So, I’d like to conclude this blog by summarizing the concept and then providing an example by putting this together in a small application logging utility (which you can build upon for use in your application).


A function is just a declaration until it is explicitly evaluated. The declaration can be assigned to a variable, which can then be passed as a parameter to another function.

Thus, a JavaScript Function is a JavaScript Variable until it is executed (evaluated).

Example: Logging Utility

   var writeLog = function( txt, format) {
       console.log( format(txt) );

var formatErr = function(text) { return "[E]" + new Date() + ":" + text; };
var formatWarn = function(text) { return "[W]" + new Date() + ":" + text; };

if(errorOccured) {
  var errText = "Error occurred. Terminating.";
  writeLog(errtext, formatErr);
} else {
  var warnText = "Warning occurred. Continuing.";   
   writeLog(warntext, formatWarn);

Do you have anything to add? Please feel free to express your point of view, provide examples, and/or ask questions.

functions, javascript, variables

Published at DZone with permission of Mangesh Pise , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}