Is there a name for a language feature that allows assignment/creation?

114 views Asked by At

This is a bit hard for me to articulate, but in PHP you can say something like:

$myArray['someindex'] = "my string";

and if there is no index named that, it will create/assign the value, and if there IS an index, it will overwrite the existing value.

Compare this to Javascript where today I had to do checks like so:

if (!myObject[key]) myObject[key] = "value";

I know this may be a bit of a picky point, but is there a name for the ability of PHP (and many other languages) to do these checks on their own as opposed to the more verbose (read: PITA) method of Javascript?

EDIT

I confused myself in asking this. Let's say you want to add to this structure:

myobject = {
    holidays : {easter : {date : 4/20/2010,
                          religion : Christianity}
                holi : {date : 3/10/2010,
                        religion : hindu} 
}

I had a problem today where I received tabular data and I wanted to put it into a tree sort of like this by building an object.

When I started my loops, I had trouble making NEW indices like myobject['holidays'][thisVariable][date] = 4/20/2010 if the tree hadn't been mostly built to that point.

I'll grab a code sample from my other computer if this isn't clear, sorry for the poor thinking.

3

There are 3 answers

3
AudioBubble On BEST ANSWER

I would guess 'auto-vivification' http://en.wikipedia.org/wiki/Autovivification from Perl might be relevant, but it works different than you described. The wiki page has a good summary. Other languages like Ruby support a "default action" hook for hash keys that have not been assigned, which can be used for auto-vivification as well.

For instance, in Ruby:


>> h = Hash.new {|h,k| h[k] = {}}
=> {}
>> h["hello"]["world"] = 20
=> 20
>> h["hello"]["world"]
=> 20

0
nicholaides On

You are mistaken. To assign a value to an object's key in javascript, you don't need to perform that check. The value will be assigned whether there is already a value for that key or not.

Think about it. How could you ever get values into an object or hash if you had to have a value there first?

0
CWF On

Javascript does exactly the same thing as PHP here: myObject[key] = "value" will overwrite the existing value if one exists. Can you tell us why you think otherwise?