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.
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).
It is possible to use a function expression and assign it to a regular variable, e.g. const factorial = function(n) {...} .
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 .
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(){} .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With