DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • PWA on iOS, Part 5: Service Worker Updates, Cache, and Push
  • PWA on iOS, Part 4: What Add to Home Screen Really Does
  • PWA on iOS, Part 3: Chrome on iPhone Is WebKit Too. How One Engine Sets the Rules for PWAs on iOS
  • PWA on iOS, Part 2: HTTPS, Manifest and Service Worker

Trending

  • Member Spotlight: Raghava Dittakavi
  • Data Integration Landscape 2026: Event Streaming, API, and Batch in the Era of Agentic AI
  • How to Keep AI Agents From Going Rogue Using Docker Sandbox
  • You Do Not Need a PhD to Become an AI Engineer: The Essential Skill Stack

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. JavaScript
  4. JavaScript Functions as JavaScript Variables

JavaScript Functions as JavaScript Variables

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

By 
Mangesh Pise
·
May. 20, 16 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
18.6K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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.

add(3,4)
RESULT:
7

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) {
alert(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
B(A);

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).

Summary

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.

JavaScript

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

Opinions expressed by DZone contributors are their own.

Related

  • PWA on iOS, Part 5: Service Worker Updates, Cache, and Push
  • PWA on iOS, Part 4: What Add to Home Screen Really Does
  • PWA on iOS, Part 3: Chrome on iPhone Is WebKit Too. How One Engine Sets the Rules for PWAs on iOS
  • PWA on iOS, Part 2: HTTPS, Manifest and Service Worker

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook