473,569 Members | 2,735 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Use of 'var' in FOR initialiser

If I have some code in a function that looks something like this:

if (x) {
for (var i = 0; i < a; i++) {
//blah
}
} else {
for (var i = 0; i < b; i++) {
//blah
}
}

JSLint tells me that "Identifier 'i' already declared as var" but I
thought it was correct practice to stick 'var' in front of the variable
in a FOR statement's initialiser. What is the correct use of 'var' in
this situation?

Andrew Poulos
Jan 17 '06 #1
5 1493
Andrew Poulos said the following on 1/17/2006 7:53 AM:
If I have some code in a function that looks something like this:

if (x) {
for (var i = 0; i < a; i++) {
//blah
}
} else {
for (var i = 0; i < b; i++) {
//blah
}
}

JSLint tells me that "Identifier 'i' already declared as var" but I
thought it was correct practice to stick 'var' in front of the variable
in a FOR statement's initialiser. What is the correct use of 'var' in
this situation?


I would use var i so that i stays local instead of becoming a global
variable.

As to why JSLint throws a caution up is something you would have to ask
Douglas about. It may see both declarations and trigger the note.

Try change it to something like this:

if (x) {
for (var i = 0; i < a; i++) {
//blah
}
} else {
for (var j = 0; j < b; j++) {
//blah
}
}

To see if that satisfies JSLint. If it does, then it is seeing both and
raising the issue when it shouldn't be (not to me anyway).

--
Randy
comp.lang.javas cript FAQ - http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Jan 17 '06 #2
On 17/01/2006 12:53, Andrew Poulos wrote:
if (x) {
for (var i = 0; i < a; i++) {
//blah
}
} else {
for (var i = 0; i < b; i++) {
//blah
}
}

JSLint tells me that "Identifier 'i' already declared as var"
That's because it is. There is no block scope in ECMAScript so the
declaration can appear anywhere that is legal, including the end of the
code, and still have the desired effect (initialisation must be done in
a timely fashion, though).

The most obvious variation is, of course:

var i;
if(x) {
for(i = 0; i < a; ++i) {
/* ... */
}
} else {
for(i = 0; i < b; ++i) {
/* ... */
}
}
but I thought it was correct practice to stick 'var' in front of the
variable in a FOR statement's initialiser.


Not particularly. The important thing is to make variables that should
be local, well, local. Whether that's accomplished in the initialiser of
a for statement, or elsewhere, doesn't matter all that much.

[snip]

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Jan 17 '06 #3
Andrew Poulos wrote:
If I have some code in a function that looks something
like this:

if (x) {
for (var i = 0; i < a; i++) {
//blah
}
} else {
for (var i = 0; i < b; i++) {
//blah
}
}

JSLint tells me that "Identifier 'i' already declared
as var" but I thought it was correct practice to stick
'var' in front of the variable in a FOR statement's
initialiser. What is the correct use of 'var' in this
situation?


Some languages, such a Java, are block-scoped and declaring variables
within - for - makes those variables only visible within the following
block. When following the general programming axiom that no variable
should be given more scope than it absolutely needs you would want the -
i - variables to be scoped to just the - for - blocks, and so have to
declare the variable for each block.

The scoping units of javascript are functions. If a variable is declared
within a function (and at any point within that function) then it is
visible to the entire function and declared from the moment the function
starts to execute. (As javascript enters then execution contexts of a
function, for each variable declaration within a function body, a named
property is created on the Variable/Activation object for that execution
context (a process called "variable instantiation") , providing the local
variables for the execution of the function). It doesn't matter where
within a function body a variable declaration is to be found, the
resulting local variables exist prior to the execution of the first
statement within the function. (Initial local variable creation does not
include the assignment of (non-default) values to those variables, the
values are not assigned until the assignment expressions within the
function body are executed).

The practical upshot of putting - var i - in each - for - statement is
that the - i - variable is declared twice within the same scope (and it
is this that JSLint is objecting to). In practice all javascript does
when a variable is declared twice in the same scope is to repeat the
process of variable instantiation for that variable, which will not
effect how the subsequent code executes.

It is widely felt (and this is opinion, though often informed by
experience) that local variables should be declared at the beginning of
the scope to which they apply, and once only. In javascript that would
mean declaring all function local variables at the start of a function
body. JSLint's attitude is a push in this sort of 'best practice'
direction, rather than a requirement of the language itself.

Richard.
Jan 17 '06 #4


Andrew Poulos wrote:
If I have some code in a function that looks something like this:

if (x) {
for (var i = 0; i < a; i++) {
//blah
}
} else {
for (var i = 0; i < b; i++) {
//blah
}
}

JSLint tells me that "Identifier 'i' already declared as var" but I
thought it was correct practice to stick 'var' in front of the variable
in a FOR statement's initialiser. What is the correct use of 'var' in
this situation?


Well with JavaScript any var declaration is "hoisted" to the beginning
of the execution context so you could do
var i;
if (x) {
for (i = 0; i < a; i++) {
//blah
}
} else {
for (i = 0; i < b; i++) {
//blah
}
}
and probably that lint tool won't bark anymore and you have the same
semantics as before.
But as in many other languages you can declare and use loop variables
just for the loop scope I would not change the coding style of
for (var i
in JavaScript just because a lint tool barks about a redeclared
variable. That is nothing wrong in your code example and in JavaScript,
better one var declaration too much (without changing the semantics) but
one missing (with the drastic side effect of creating a global variable).

--

Martin Honnen
http://JavaScript.FAQTs.com/
Jan 17 '06 #5
Martin Honnen wrote:
Well with JavaScript any var declaration is "hoisted" to the beginning
of the execution context so you could do
var i;
if (x) {
for (i = 0; i < a; i++) {
//blah
}
} else {
for (i = 0; i < b; i++) {
//blah
}
}
and probably that lint tool won't bark anymore and you have the same
semantics as before.
But as in many other languages you can declare and use loop variables
just for the loop scope I would not change the coding style of
for (var i
in JavaScript just because a lint tool barks about a redeclared
variable. That is nothing wrong in your code example and in JavaScript,
better one var declaration too much (without changing the semantics) but
one missing (with the drastic side effect of creating a global variable).


I agree that jslint barks is not always a good reason to change code style,
and that declaring variables is better than not to declare them at all (see
also the previous discussion on surprising IE scope chain behavior.)

However, whenever a variable is redeclared, you get a warning in the
JavaScript console of Gecko-based browsers (unless you filter all warnings,
where some of them such as "_un_declar ed variable" are indeed helpful).
This tends to disturb me, especially when debugging code. Therefore I
watch for that I declare a variable only once per execution context; if I
reuse a variable in more than one loop in the same context, I declare the
variable only in the first loop or more seldom, as Richard said, before
the first loop.

Another way to follow the code style known from block scoping without
causing warnings would be to use a different iterator variable in every
independent loop. AFAIK I do not do that; reason: keep your execution
context clean.
PointedEars
Jan 17 '06 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
3211
by: Gavin Andrews | last post by:
I use log4j for logging and tend to include the following snipet in all my classes... public class MyClass { // Logging Declarations private static String _className; private static Category _cat; static {
9
2652
by: Bart Nessux | last post by:
Are these equivelent? Is one approach prefered over the other #check to see if var contains something... if so proceed. if var is not None: continue #check to see if var is empty... if so prompt user again.
2
2529
by: John Harrison | last post by:
What are the rule concerning calling member functions from an initialiser list? Suppose I have class C : public B { public: C() : x(), y(f()), z() {} private: Y f(); X x;
2
3053
by: Martin Zimmermann | last post by:
Hi. Is it allowed to dereference 'this' in a constructors initialiser list to initialize a reference? (for later use) Is this code legal or illegal? class Foo; class Bar
0
1413
by: Tim Sharrock | last post by:
We have hit an internal compiler error when processing a very long array initialiser (for a lookup table). Most of the compiler versions we tried compiled the code successfully, but very slowly (one person reported hours, but I have not seen that personally), but one failed: Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 13.10.3077...
1
2595
by: Alasdair | last post by:
Hi, I'm wondering if there is any way of getting around the "too many initialiser" error when giving initial values for an array. I'm trying to make a random word generator, so I need long lists of words. Help?
1
1697
by: Frederick Gotham | last post by:
I have set up an online poll: http://snappoll.com/poll/130337.php to ask C++ programmers whether they want aggregate initialiser syntax to be added to the Standard. Here's is how it works: struct MyAgg { int a; double b; }; class MyClass {
10
2224
by: Marc Gravell | last post by:
Given a generic method "of T", is there a good way of ensuring that any static ctor on T has executed? Following code demonstrates (TestClass1) that via generics you can use the Type instance long before the static ctor fires. With a generic class and the "new()" clause, I can force this in the static ctor of the generic class, but this is...
22
3586
by: Tomás Ó hÉilidhe | last post by:
I've been developing a C89 microcontroller application for a while now and I've been testing its compilation using gcc. I've gotten zero errors and zero warnings with gcc, but now that I've moved over to the micrcontroller compiler I'm getting all sorts of errors. One thing I'd like to clarify is the need (in C89) for a compile- time...
0
7694
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7609
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8118
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
7964
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6278
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5217
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3636
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1208
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
936
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.