Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!weretis.net!feeder4.news.weretis.net!eternal-september.org!feeder.eternal-september.org!mx04.eternal-september.org!.POSTED!not-for-mail From: "Jukka K. Korpela" Newsgroups: comp.lang.javascript Subject: Re: Explicit zero-initialization of vars Date: Wed, 28 Dec 2011 15:44:05 +0200 Organization: A noiseless patient Spider Lines: 36 Message-ID: References: <7351867e-b6e5-457f-a080-bd03a2db9006@t30g2000vbx.googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Injection-Date: Wed, 28 Dec 2011 13:44:03 +0000 (UTC) Injection-Info: mx04.eternal-september.org; posting-host="ngroV0xYIIv0dzjhyZhv5A"; logging-data="23934"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX19ohZT7o+XNMx2GEh8hnuxQ" User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:8.0) Gecko/20111105 Thunderbird/8.0 In-Reply-To: <7351867e-b6e5-457f-a080-bd03a2db9006@t30g2000vbx.googlegroups.com> X-Antivirus-Status: Clean X-Antivirus: avast! (VPS 111228-0, 28.12.2011), Outbound message Cancel-Lock: sha1:jSEpfvwEkfhhlerbgPoLEWgxheg= Xref: x330-a1.tempe.blueboxinc.net comp.lang.javascript:9723 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/