0

So, I tried to initialize a variable using this snippet of code,

    var foo = {bar: {baz: 3}, qux: {fooAgain: foo.bar.baz + 5}}

But I get the error TypeError: Cannot read property 'bar' of undefined

How would I access property baz from qux?

  • You cannot in an object literal declaration. There is nothing to access yet when `fooAgain` is created. – Bergi Apr 11 '15 at 19:00

1 Answers1

0

Edited answer in response to your comment:

var bar = {baz: 3};
var foo = {bar: bar, qux: {fooAgain: bar.baz + 5}};

This way you first create bar variable and then create your foo variable using it.

Explaination: Your original code did not work because you were trying to access property bar of foo object before the foo object was actually initialized.

Andrew B
  • 860
  • 1
  • 14
  • 23
  • That is not what I intended. I want a single variable with the following fields, `bar` and `qux`. `bar` is an object itself with a single field, `baz`, intialized to 3. And `qux` is an object too with a single field, `fooAgain`, that I want to initialize to 5 plus `baz`. What I would like to know is how to access `baz` from within `fooAgain`. –  Apr 11 '15 at 07:48
  • I guess this would be the only possible way to do it. –  Apr 11 '15 at 19:04