Explicit zero-initialization of vars

A

Archos

Is it recommended make zero-initialization of vars explicit?

By example:

`var i = 0` instead of `var i` // for an integer
`var s = ""` instead of `var s` // for a string
 
M

Michael Haufe (TNO)

Is it recommended make zero-initialization of vars explicit?

By example:

`var i = 0`  instead of `var i` // for an integer
`var s = ""` instead of `var s` // for a string

No.
 
J

Jukka K. Korpela

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top