1

Possible Duplicate:
Difference between using var and not using var in JavaScript

There are two ways I've seen people declare functions in javascript. Either:

foo = function()
{
  //Do stuff
}

or

var foo = function()
{
  //Do stuff
}

I'm new to javascript, and would like to know if there is a real difference between the two. Is one better to use than the other, or does it depend on the situation?

Community
  • 1
  • 1
CSturgess
  • 1,547
  • 2
  • 13
  • 29

3 Answers3

1

AFAIK, if you do not state var then your function will be assigned to the global scope (same scope level as the window object), however if you declare it as var it will be contained within its parent scope.

EDIT: to clarify after the response from Tomalak, the function will belong to its parent scope, however if the parent scope is a function which is executed, after execution of the enclosing function, any functions declared without var will be accessible within the global context.

James Shuttler
  • 1,344
  • 9
  • 15
0

There are two ways:

  • Declaring it in a variable
  • Using the default function declaration

In your case, you're trying to declare it in a variable. Declaring variables (whether function or not) start with the var syntax.

var foo = function() { }; // please note that semicolon (;)

When defining a function normally:

function foo() { }

So, again, in your case, the var is required, unless you pre-define it:

var foo;
foo = function() { };

Edit: As James stated, if you wish to define it in the global scope you can discard the var keyword. But to be honest it's still a better practise to predefine the variable if you wish to define it on another scope level.

Tim S.
  • 13,597
  • 7
  • 46
  • 72
0

It's better to declare with var, otherwise you may be affecting any other var within the global scope. Check for example this question for more information: What is the scope of variables in JavaScript?

Community
  • 1
  • 1
Miguel Ping
  • 18,082
  • 23
  • 88
  • 136