Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One var per function in JavaScript?

I've been using JSLint to make me feel bad about my JavaScript. It is great, by the way. There is one check that I don't quite understand and I'd like your views, please.

From jslint.com:

In languages with block scope, it is usually recommended that variables be declared at the site of first use. But because JavaScript does not have block scope, it is wiser to declare all of a function's variables at the top of the function. It is recommended that a single var statement be used per function.

What is the last sentance in bold really saying? I think I should be declaring multiple variables like this?

var foo = 1, bar = 2; 

And, is the "wise" part just a programming style to discourage errors down the line or is there more to it than that?

Thanks for your help.

like image 466
Scott McKenzie Avatar asked Aug 05 '09 23:08

Scott McKenzie


People also ask

What is VAR function in JavaScript?

The var statement declares a variable. Variables are containers for storing information. Creating a variable in JavaScript is called "declaring" a variable: var carName; After the declaration, the variable is empty (it has no value).

Can you assign a variable to a function JavaScript?

It is possible to use a function expression and assign it to a regular variable, e.g. const factorial = function(n) {...} .

Is there VAR in JavaScript?

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 .

What is the difference between VAR and function in JavaScript?

A variable is something, which stores data. A function is a bunch of code, which can be executed, if you call. But a function can be a variable, too, as it stores data and values, too. See the following syntax: var functionname = function(){} .


1 Answers

The problem is that, whether you realise it or not, javascript invisibly moves all the var declarations to the top of the function scope.

so if you have a function like this

var i = 5; function testvar () {      alert(i);      var i=3; } testvar(); 

the alert window will contain undefined. because internally, it's been changed into this:

var i = 5; function testvar () {      var i;      alert(i);      i=3; } testvar(); 

this is called "hoisting". The reason crockford so strongly advocates var declarations go at the top, is that it makes the code visibly match what it's going to do, instead of allowing invisible and unexpected behavior to occur.

like image 111
Breton Avatar answered Oct 21 '22 09:10

Breton