PDA

View Full Version : Variable Initialization


hand
09-19-2002, 05:45 AM
Hi All,
I was wondering if anyone could tell me if it makes a difference, in terms of memory processing or script execution, how variables are initialized. It's probably a silly question. Have a look at the 'msg' variable script below:

<script>
function a()
{
var msg
//some statements here
msg="something"
msg+="another thing"
return msg
}

function b()
{
var msg=""
//some statements here
msg+="something"
msg+="another thing"
return msg
}
</script>

Does the different ways that the 'msg' variable is initialized have any impact on a script? In other words, whats the difference between the two?
TIA

umm
09-19-2002, 11:44 AM
I don't know much about the processing side of it but as I understand it, when the first msg var is initialised it can be any data type (e.g. object, string, number). It becomes a string later, but it could have been assigned any data type as the script processed.

The second var is intialised as a string right from the start. I think, but am not sure that it would probably remain a string unless it was converted to another data type later on, such as with the parseInt() method which converts a string to a number.

Variables can vbe quite elastic.

hth

beetle
09-19-2002, 03:51 PM
umm is pretty much right. Javascript variables pretty much only care about the datatype when when you are doing something to/with the value. Take this examplevar temp = ""; // Initialized as a string
temp = 5; // Assigned a number, temp is now an integer
temp += 6; // Increment by 6Above, I'm not really doing anything with the value, I'm just assigning it a new value, so the pre-existing type has no precedence. So when I now add another integer (6) temp now holds the value of 11.
Note: the acutal javascript datatype for integers and floats are labeled as 'number'

Now, let's look at another examplevar temp = ""; // Initialized as a string
temp += 5; // Increment by 5
temp += 6; // Increment by 6So what does temp look like now? Since I use the increment operator (+=) I'm adding to the value that is already existing (not re-assigning, as in example #1). So, even though I'm adding integers, the variable type is obeyed, and temp now holds "56" (as a string) and not 11.

The one advantage to declaring a variable without a type is that it remains undefined until you give it a value. For examplefunction assignVal(whattype) {
var holder;
if (whattype == 'text')
holder = "";
if (whattype == 'integer')
holder = 0;
if (typeof holder == 'undefined')
alert("Type not specified");
else return holder;
}Now, this example really only suits itself, but I think I made my point.

One more thing I'd like to add, is about the identical operator (===). Unlike the equate operator (==) the identical operator checks for equality with the value AND datatype.alert((3 == "3")); // Alerts true
alert((3 === "3")); // Alerts falseHappy coding :D

mordred
09-19-2002, 11:46 PM
I'd like to add my 0.02 Euros to your original question (the impact of these two different approaches), but from a different perspective:

IMO the relative gain in memory usage from initializing a variable as undefined vs. a string literal is pretty much neglectable. Far more important for me would be the readability of my code - and there's where the second approach becomes preferable for me. Because I already see on the first sight that this variable seems to be used to store a string. Whereas with an undefined variable, I have to dig through the code to find the actual lines the type of this variable gets set... and in big scripts with a lot of procedural processing, this can be a real PITA (especially when this variable is later used in different datatype contexts).

Well, that's just my opinion, and it's heavily influenced by the well-known quote of Knuth:

"Premature optimization is the root of all evil"

RadarBob
09-20-2002, 01:32 PM
Initializing variables is always a good thing. Then you know what it's initial state is. As mentioned above Javascript sets uninitialized variables automatically to 'undefined' - so the state is known, but again we don't know what type it's supposed to be at this point. Also, 'undefined' is not == null or zero, so it's not a proper substitute for these.

In other programming languages not initializing variables is more risky. If not initialized, the variable will take on the "value" of whatever is in the bytes of memory that variable is assigned to. Who knows what leftover garbage is there from the last program to use that memory.

NOTE also that variables defined without "var" in front have gobal scope - even if they are defined within a function. Good idea to always use "var" to avoid any potential scope problems or name conflicts.

mordred
09-20-2002, 02:39 PM
Originally posted by RadarBob
Also, 'undefined' is not == null or zero, so it's not a proper substitute for these.

I know what you mean, but I think you rather meant 'undefined' === null, because an undefined value will be evaluated to the appropriate type when in a simple equality comparison like.

Ok, ok, I'll freely admit I'm a language lawyer now, and I duck for cover... ;)

RadarBob
09-20-2002, 04:05 PM
I know what you mean, but I think you rather meant 'undefined' === null, because an undefined value will be evaluated to the appropriate type when in a simple equality comparison like.


Your Honor! I object! from Pure JavaScript, the Bible (or should be!) of JavaScript language lawyers, i quote:

... undefined is a concept rather than a keyword like the null data type. Undefined is equivalent to NaN for numbers, the string 'undefined' for strings, and false when dealing with Boolean values.

. . .

Keep in mind that 'undefined ' is a special JavaScript value.

So, I suppose without testing at this point:

var aVariable; // the value is literally "undefined"?
aVariable == null; // would evaluate false
aVariable == 0; // would evaluate false
aVariable == 'undefined'; // would evaluate true
aVariable == NaN; // would evaluate true
aVariable == false // would evaluate true

It's not that "aVariable" was type-converted, but that it's "undefined" state is equivalent to certain other "state-less" conditions.

Also, being equivalent to the string 'undefined' makes sense and is consistant. If not, then there would have to be some extra-special symbol, much like that of "the artist formerly known as Prince." A symbol that is otherwise totally without meaning and has no pronounciation!

Judge: "objection sustained. The defendant's testimony will be stricken from the record; the jury will disregard this testimony."

mordred
09-20-2002, 04:48 PM
:)

Not so fast:


var x;
alert(x == null); // alerts 'true'
alert(x === null); // alerts 'false'


I agree that my statement was imperfect, it was meant to only illustrate the point that due to javascripts type-juggling feature variables evaluate to something different than they are based on what is on the other (in my example, right) side of the comparison statement. Of course you're right, the variable itself does not get converted to a new type, that's why I wrote "evaluated".

Argghl, I didn't want to sound like a nitpicker, but obviously I did...

RadarBob
09-20-2002, 08:14 PM
Well, wadda know. I confirmed your results. Also all of the other tests, both = = and = = = were "false" as well, in spite of what the book I quoted said.
Argghl, I didn't want to sound like a nitpicker, but obviously I did...
Nah. Programming languages are precicly demanding. Besides it's fun to pick at nits from time to time. All in the spirit of learning (vis-a-vis showing off).:thumbsup:

mordred
09-20-2002, 09:30 PM
Good to know, I was under the impression that my remarks would be perceived as inappropriate and rude - you know, I'm not a native english speaker, so I sometimes have a hard deal with putting my point into words that are accurate enough (especially when it comes to ironic remarks).

[i]Originally posted by RadarBob
Nah. Programming languages are precicly demanding. Besides it's fun to pick at nits from time to time. All in the spirit of learning (vis-a-vis showing off)

Fine, full ACK to that :thumbsup:

hand
09-20-2002, 09:39 PM
Wow, thanks for the replies everyone. I've got a bit to go through here. I'll be back with questions!