Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am coming across the following error in js

Cannot read property 'charlie' of undefined 

I am setting a value like this

alpha.beta.charlie.delta.echo = [];

but only alpha and beta are initialized as objects. So how do I auto initialize objects charlie and echo as objects without writing

alpha.beta.charlie = {};
alpha.beta.charlie.delta = {}
alpha.beta.charlie.delta.echo = [];
share|improve this question
    
Duplicate? stackoverflow.com/questions/5484673/… –  Holf Sep 4 '13 at 16:34
    
beta does not seem to initialized already when the error message states that you're accessing charlie on undefined –  Bergi Sep 4 '13 at 16:40
    
Agree with @Bergi The error Cannot read property 'charlie' of undefined indicates that beta is not defined, so only alpha is defined at this point –  Robert Sep 4 '13 at 16:55

4 Answers 4

up vote 1 down vote accepted

You don't - about the best you can do is something like this:

alpha.beta = { charlie: { delta: { echo: [] } } };

Of you don't know whether the objects are initialized yet or not, it would be safer to keep the first form and do something like this:

alpha.beta                    = alpha.beta || {};
alpha.beta.charlie            = alpha.beta.charlie || {};
alpha.beta.charlie.delta      = alpha.beta.charlie.delta || {}
alpha.beta.charlie.delta.echo = alpha.beta.charlie.delta.echo  || [];
share|improve this answer

Have to init all..

alpha={beta:{charlie:{delta:[]}};

then alpha.beta.charlie.delta would be your [] Empty array;

share|improve this answer
    
Please don't use == like that in code (your expression would yield false). Make it a comment at least, or use a symbol like ≙ –  Bergi Sep 4 '13 at 16:58

At some point you have to declare alpha properties, one shorter version of doing so is

alpha.beta.charlie = {
  delta: {
    echo: []
  }
}
share|improve this answer

There is no auto-initialisation possible in javascript (unless from ugly hacks with proxies or with knowing the property names in before).

Instead, just nest the object literals to create the properties directly on them, instead of creating empty objects and putting properties on them afterwards:

alpha.beta = {
    charlie = {
        delta: {
            echo: []
        }
    }
};

or short

alpha.beta = {charlie: {delta: {echo: []}}};
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.