Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does it mean when a variable equals a function? [duplicate]

Possible Duplicate:
JavaScript: var functionName = function() {} vs function functionName() {}

In JavaScript, what's the purpose of defining a variable as a function? I've seen this convention before and don't fully understand it.

For example, at some point in a script, a function is called like this:

whatever();

But where I would expect to see a function named whatever, like this:

function whatever(){  } 

Instead I'll see a variable called whatever that's defined as a function, like this:

var whatever = function(){  } 

What's the purpose of this? Why would you do this instead of just naming the function?

like image 494
daGUY Avatar asked Feb 27 '12 14:02

daGUY


People also ask

Can you set a function equal to a variable?

For example, a variable can be set equal to a function that returns a value between zero and four. Do not think that 'a' will change at random, it will be set to the value returned when the function is called, but it will not change again.

How do you make a variable equal another variable?

After a value is assigned to a variable using the assignment operator, you can assign the value of that variable to another variable using the assignment operator. var myVar; myVar = 5; var myNum; myNum = myVar; The above declares a myVar variable with no value, then assigns it the value 5 .

Can you set a variable equal to a function in Python?

If the variable has been previously defined, you can do that yes. If the variable has not been defined previously, you can't do that, simply because there is no value that could be passed to the function.

Can a variable be a function JS?

It is assigned a reference to a function, after which the function it references can be invoked using parentheses, just like a normal function declaration. The example above references anonymous functions... functions that do not have their own name. You can also use variables to refer to named functions.


2 Answers

Note: Please see the update at the end of the answer, declarations within blocks became valid (but quite complicated if you're not using strict mode).


Here's one reason:

var whatever;  if (some_condition) {     whatever = function() {         // Do something     }; } else {     whatever = function() {         // Do something else     }; } whatever(); 

You might see code like that in the initialization of a library that has to handle implementation differences (such as differences between web browsers, a'la IE's attachEvent vs. the standard addEventListener). You cannot do the equivalent with a function declaration:

if (some_condition) {     function whatever() {    // <=== DON'T DO THIS         // Do something     } } else {     function whatever() {    // <=== IT'S INVALID         // Do something else     } } whatever(); 

...they're not specified within control structures, so JavaScript engines are allowed to do what they want, and different engines have done different things. (Edit: Again, see note below, they're specified now.)

Separately, there's a big difference between

var whatever = function() {     // ... }; 

and

function whatever() {     // ... } 

The first is a function expression, and it's evaluated when the code reaches that point in the step-by-step execution of the context (e.g., the function it's in, or the step-by-step execution of global code). It also results in an anonymous function (the variable referring to it has a name, but the function does not, which has implications for helping your tools to help you).

The second is a function declaration, and it's evaluated upon entry to the context, before any step-by-step code is executed. (Some call this "hoisting" because something further down in the source happens earlier than something higher up in the source.) The function is also given a proper name.

So consider:

function foo() {     doSomething();     doSomethingElse();     console.log("typeof bar = " + typeof bar); // Logs "function"      function bar() {     } } 

whereas

function foo() {     doSomething();     doSomethingElse();     console.log("typeof bar = " + typeof bar); // Logs "undefined"      var bar = function() {     }; } 

In the first example, with the declaration, the declaration is processed before the doSomething and other stepwise code is run. In the second example, because it's an expression, it's executed as part of the stepwise code and so the function isn't defined up above (the variable is defined up above, because var is also "hoisted").

And winding up: For the moment, you can't do this in general client-side web stuff:

var bar = function foo() { // <=== Don't do this in client-side code for now     // ... }; 

You should be able to do that, it's called a named function expression and it's a function expression that gives the function a proper name. But various JavaScript engines at various times have gotten it wrong, and IE continued to get very wrong indeed until very recently.


Update for ES2015+

As of ES2015 (aka "ES6"), function declarations within blocks were added to the specification.

Strict mode

In strict mode, the newly-specified behavior is simple and easy to understand: They're scoped to the block in which they occur, and are hoisted to the top of it.

So this:

"use strict";  if (Math.random() < 0.5) {    foo();    function foo() {      console.log("low");    }  } else {    foo();    function foo() {      console.log("high");    }  }  console.log(typeof foo); // undefined

(Note how the calls to the functions are above the functions within the blocks.)

...is essentially equivalent to this:

"use strict";  if (Math.random() < 0.5) {    let foo = function() {      console.log("low");    };    foo();  } else {    let foo = function() {      console.log("high");    };    foo();  }  console.log(typeof foo); // undefined

Loose mode

Loose mode behavior is much more complex and moreover in theory it varies between JavaScript engines in web browsers and JavaScript engines not in web browsers. I won't get into it here. Just don't do it. If you insist on function declarations within blocks, use strict mode, where they make sense and are consistent across environments.

like image 59
T.J. Crowder Avatar answered Sep 21 '22 23:09

T.J. Crowder


this is so you can store functions in variables and e.g. pass them to other functions as parameters. One example where this is usefull is in writing asynchronous functions which are passed callbacks as arguments

var callback = function() { console.log('done', result)}  var dosomething = function(callback) {     //do some stuff here     ...     result = 1;     callback(result); } 

Since functions are objects in javascript you can extend them with properties and methods as well.

like image 35
joidegn Avatar answered Sep 20 '22 23:09

joidegn