Reputation: 19688
If I am trying to declare a variable and I need to provide a default case because it won't let me create the key without a value, I thought I could make the same basic value for all empty variables, but it still be of the type I want it to be when I actually assign it the value.
var x = "";
var y = 0;
var z = null;
I know that JS is pretty good about knowing which type (except those crazy situations between strings and numbers), but would null
be able to be over-written by all types, and then that variable would be of that type?
so if we had var x = "";
then x is a String already. Obviously if I did var x = "something"
then it would still be a String, or if I did var x = 12
then it would change the type and the value.
What is the type if it is assigned null
?
So what is your suggestion for a placeholder value for a variable that just needs to be created?
Upvotes: 0
Views: 67
Reputation: 57703
A default value is not the same as no value. Sometimes it's important to be able to make that distinction.
Since you do need some way to detect if you have a value you can use a value that indicates that the value is undefined, like: undefined
. This does mean that your dictionary is initially empty.
Depending on your data types you can also use null
. Of course if null
is a possible value you can't use it. If you have no safe undefined value you can have another property say something about the value, like is value X set: yes/no
(this is one step in the direction of a schema / meta data).
A tip I can give you is that if you have data, with strongly typed data types, work on a schema language to describe the data. You will get the undefined
value detection basically for free.
Upvotes: 1
Reputation: 11666
null = Object;
undefined = no type specified
In Javascript, everything is an Object of some form or other, unless it has not been associated with any data, in which case it is undefined
.
So you probably want something like:
var defaults = {
beats: "",
numberOfBeats: 0,
representation: undefined
};
Then in your code you could query whether the representation
index has any data in it by:
if(typeof defaults['representation'] === "undefined"){
// representation has not yet been defined
}
Upvotes: 1
Reputation: 8189
var x;
x = 6;
typeof x // 'number'
x = '6';
typeof x // 'string'
x = null;
typeof x // 'object'
x = {};
typeof x // 'object'
x = 3;
typeof x // 'number'
Upvotes: 1
Reputation: 46873
The typeof null
is "object"
And it's a common mistake that novice js programmers make to assume that undefined
and null
are the same (they're not).
Upvotes: 1