Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.javascript > #9723

Re: Explicit zero-initialization of vars

From "Jukka K. Korpela" <jkorpela@cs.tut.fi>
Newsgroups comp.lang.javascript
Subject Re: Explicit zero-initialization of vars
Date 2011-12-28 15:44 +0200
Organization A noiseless patient Spider
Message-ID <jdf6f2$nbu$1@dont-email.me> (permalink)
References <7351867e-b6e5-457f-a080-bd03a2db9006@t30g2000vbx.googlegroups.com>

Show all headers | View raw


2011-12-28 10:53, Archos wrote:

> Is it recommended make zero-initialization of vars explicit?

There is no implicit zero-initialization. If you declare a variable 
without initializing it, its initial value is the special value 
undefined, of the special type undefined.

> By example:
>
> `var i = 0`  instead of `var i` // for an integer
> `var s = ""` instead of `var s` // for a string

Without the initializers (= 0 and = ""), both i and s would come to life 
with the value undefined. It's not an integer value, it's no a string 
value, it's - of type undefined. You can see this if you check out this:

var i;
alert(i);
alert(typeof i);

It is generally a good idea to initialize a variable on declaration, if 
a natural and useful initial value can be assigned to it, such as 0 for 
a counter or "" for a variable into which some string will be composed 
by catenating strings.

It is not a good idea to initialize a variable with a dummy value just 
to make it initialized. Every variable _is_ initialized by language 
rules in JavaScript, and the special value undefined is often more 
useful than a dummy neutral value like 0 or "". If your code runs wild 
and uses the value of a variable to which no proper value has been 
assigned, it's better to "see" the variable value as undefined, as it 
logically is.

-- 
Yucca, http://www.cs.tut.fi/~jkorpela/

Back to comp.lang.javascript | Previous | Next — Previous in thread | Find similar | Unroll thread


Thread

Explicit zero-initialization of vars Archos <raul.san@sent.com> - 2011-12-28 00:53 -0800
  Re: Explicit zero-initialization of vars "Michael Haufe (TNO)" <tno@thenewobjective.com> - 2011-12-28 05:19 -0800
    Re: Explicit zero-initialization of vars Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2011-12-28 16:48 +0100
  Re: Explicit zero-initialization of vars "Jukka K. Korpela" <jkorpela@cs.tut.fi> - 2011-12-28 15:44 +0200

csiph-web