Variable value question

Variable value question
0

#1

When do you use the value of 0 and when do you use an empty array i.e. var array = 0; or var array = “”; ?


#2

JavaScript is free on variables.

You could start by defining a variable as a numbervar variable = 0; and later transform it (type casting) into an array or any other type of objects, even a function.

It is your choice and a style choice. I usually define my variables at the top of the code and if I know that I will be using that variable as an array, I define it like var myArray = [];

If it will be a number var myNumber = 0;

If you don’t know but you still want to define the variable you can define it without placing a value in it var noValueVariable;

The difference between the type definitions you mentioned is in the bits / bytes used by the variable. A number variable can be of size 0 to n bits, a character variable can be of size 0 to 8 bits, a special character variable can be from 0 to n bits, an array can be from 0 to n bits. A string is usually an array of characters (in languages like C it is actually how strings are built) so each member of the array is a character that can be from 0 to n bits. Hope this helps.


#3

If you’re wanting to initialize an empty array, then var arr = [] would be the better choice. The reason is that, while there are no values in the array, you’ve still created an array object and that object will have access to array methods like push.

var arr = [];

for (var i = 0; i < 11; i++) {
    arr.push(i);
}

If you tried that with var arr = 0 or var arr = "", you’d get an error saying the method isn’t found.