Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is "var" needed in js? [duplicate]

Tags:

javascript

var

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

sometime, I saw people doing this

for(var i=0; i< array.length; i++){  //bababa  } 

but I also see people doing this...

for(i=0; i< array.length; i++){  //bababa  } 

What is the different between two? Thank you.

like image 618
Tattat Avatar asked Jul 30 '11 06:07

Tattat


People also ask

When should I use VAR in JS?

Always declare JavaScript variables with var , let , or const . The var keyword is used in all JavaScript code from 1995 to 2015. The let and const keywords were added to JavaScript in 2015. If you want your code to run in older browser, you must use var .

Why is var needed?

Risk managers use VaR to measure and control the level of risk exposure. One can apply VaR calculations to specific positions or whole portfolios or use them to measure firm-wide risk exposure.

Do you need to say VAR in JavaScript?

In Javascript, it doesn't matter how many times you use the keyword “var”. If it's the same name in the same function, you are pointing to the same variable. This function scope can be a source of a lot of bugs.

Is VAR optional in JS?

"Optional" is perhaps an unfortunate choice of words, as var is optional in the sense that an assignment statement can be successfully interpreted with or without it, but not optional in the case where you want to explicitly declare a variable in local scope.


1 Answers

The var keyword is never "needed". However if you don't use it then the variable that you are declaring will be exposed in the global scope (i.e. as a property on the window object). Usually this is not what you want.

Usually you only want your variable to be visible in the current scope, and this is what var does for you. It declares the variable in the current scope only (though note that in some cases the "current scope" will coincide with the "global scope", in which case there is no difference between using var and not using var).

When writing code, you should prefer this syntax:

for(var i=0; i< array.length; i++){     //bababa } 

Or if you must, then like this:

var i; for(i=0; i< array.length; i++){    //bababa } 

Doing it like this:

for(i=0; i< array.length; i++){    //bababa } 

...will create a variable called i in the global scope. If someone else happened to also be using a global i variable, then you've just overwritten their variable.

like image 52
aroth Avatar answered Oct 12 '22 05:10

aroth