Explicit declaration of array type required?

D

d.adamkiewicz

Hello Folks

I was wondering if the following could be better written:

var myObject = {};
/*
in this case explicit declaration seems to be mandatory
otherwise 'myObject.ala has no properties' error occurs
*/
if (typeof myObject["ala"] == "undefined") {
myObject["ala"] = [];
}

myObject["ala"].push("ela");

Regards
Darek
 
T

Thomas 'PointedEars' Lahn

I was wondering if the following could be better written:

var myObject = {};
/*
in this case explicit declaration seems to be mandatory
otherwise 'myObject.ala has no properties' error occurs
*/

Of course, `undefined' has no properties.
if (typeof myObject["ala"] == "undefined") {
myObject["ala"] = [];
}

This condition is only necessary if the "ala" property is running the risk
of not being defined or explicitly assigned `undefined' before.
myObject["ala"].push("ela");

Backwards compatible:

var myObject = new Object();
myObject.ala = new Array("ela");

or (ECMAScript 3 compliant):

var myObject = {ala: ["ela"]};


PointedEars
 
J

jim

var myObject = {ala: []};
myObject.ala.push("ela");

could also do:

window.myObject={
ala:[],
alb:{a:1,b:"two",c:[3]},
alc: (false)? true:false,
ald: "hello"
};

cheers, Jim
 
T

Thomas 'PointedEars' Lahn

Thomas said:
if (typeof myObject["ala"] == "undefined") {
myObject["ala"] = [];
}

This condition is only necessary if the "ala" property is running the risk
of not being defined or explicitly assigned `undefined' before.

Clarification: It is not necessary at all, unless a specific program
behavior is attached to its having the value `undefined'.

myObject["ala"] = [];

creates the property and/or assigns a (new) value to it.


PointedEars
 
T

Thomas 'PointedEars' Lahn

jim said:
var myObject = {ala: []}; ^^^^^^^^^^^^^^
myObject.ala.push("ela");

could also do:

window.myObject={ ^^^^^^^^^^^^^^^^
ala:[],
alb:{a:1,b:"two",c:[3]},
alc: (false)? true:false,
ald: "hello"
};

Those two assignments are in no way equivalent.


PointedEars
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top