1

I want to do the following in javascript but there's something about the syntax I'm not understanding here:

var theObj = { foo: val1, bar: val2 } if ( condition ) { theObj[foo] = newVal return theObj // returns { foo: val1, bar: newVal } } return theObj // returns { foo: val1, bar: val2 } 
1
  • I know there was a syntax error there, whoops, got it now! Commented Aug 15, 2012 at 15:46

1 Answer 1

3

What you have is not an object array, but rather an object literal. Normally, its properties would be accessed as theObj.property, but JavaScript provides an alternative syntax of theObj["property"] when you need to do operations like string manipulation on the property name (like theObj["property_" + numberVar]), or for properties not valid in dot notation (like number properties theObj[12] = "twelve")

If you access the property via [], you would need to quote the string ["foo"], otherwise the parser would be looking for a variable named foo to insert there. However, this simple string property is better accessed with dot notation:

if ( condition ) { theObj.foo = newVal return theObj // returns { foo: val1, bar: newVal } } 
Sign up to request clarification or add additional context in comments.

1 Comment

Bracket access is also needed when what would otherwise be invalid dot access syntax: var obj = {1e5: 3}; alert(obj[1e5])

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.