kornfridge
kornfridge

Reputation: 5200

Why can I reference a variable not yet defined in Javascript?

When creating the function foo here, I reference a variable fromTheFuture the hasn't been declared yet. This actually works as expected, but why? Is it considered dangerous or bad practice?

var foo = function(x) {
  return fromTheFuture * x;
};

var fromTheFuture = 5;

console.log(foo(10));

I can see this being very convenient though, if you have several functions that wants use each other in a cycle fashion - without having to declare them all with var in the beginning of the method.

Upvotes: 1

Views: 953

Answers (3)

Gyan Chandra Srivastava
Gyan Chandra Srivastava

Reputation: 1380

the reasone behined it in javascript it define all varible first and then start initializing and then after if somewhere it need its intialization point it try intializized called one first

Upvotes: 1

Bogdan Gavril MSFT
Bogdan Gavril MSFT

Reputation: 21478

Yes, the entire script is processed first, the variables added to the "data store" and only then the execution is performed.

However, this is not encouraged as it makes the code hard to read. If you want to know more about javascript code quality, check out jslint. It's a sort of FxCop for js. Try copy-pasting your code in there.

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324740

By the time foo is called, fromTheFuture is defined. More accurately, due to hoisting, your code is essentially:

var foo, fromTheFuture;
foo = function(x) {return fromTheFuture*x;};
fromTheFuture = 5;
console.log(foo(10));

If you were to call foo(10) before fromTheFuture=5, you would get NaN.

Upvotes: 5

Related Questions