1

Can additional object properties in coffeescript/javascript be added dynamically to an existing object?

For example:

var fred = { name: "Fred", species: "Sub-Human" };

Now later, for example, I want to add college major to get this:

{ name: "Fred", species: "Sub-Human", major: "Computer Science" }

And... how does this affect, or does it affect performance?

2 Answers 2

4

Sure, JavaScript objects are completely dynamic.

You can use dot notation with a property name literal:

fred.major = "Computer Science";

or brackets notation with a property name string:

fred["major"] = "Computer Science";

Literals can be optimized more by the JavaScript engine, strings can be the result of any expression (so, fred["m" + "ajo" + "r"] = ... would work) and can include characters (like spaces — yes, really —) that you can't use in a property name literal.

I suggest working through some basic JavaScript tutorials (if you want to learn JavaScript) or CoffeeScript tutorials (if you want to learn CoffeeScript).

Sign up to request clarification or add additional context in comments.

6 Comments

Really,... It's exact the answer I gave.
@Mouser: It wasn't as of when I started writing my answer. The answer that was there when I started was misleading, suggesting that you had to use a string. I thought something more complete was appropriate.
True give you that ;-) Cuddos for giving the correct answer. ;-)
Thanks, I knew you can do <code>delete fred.major</code> Thought there might be something like <code>add fred.gender = "Male"</code> or something similar, but now I really am understanding what "weakly-typed" means. I come from a Java background, so none of this would fly due to scope, etc... New to JS,so thanks. :) Hopefully people won't kill me over asking a simple question.
@JoshuaMichael: Ah, yes, I see that logic. BTW, side note about delete: On modern engines, if you use delete to remove a property, subsequent property lookups on that object may be slower (although with modern engines it rarely matters). This is because using delete frequently causes the JavaScript engine to stop using an optimized object and fall back on a simple map or dictionary object. Adding properties doesn't do that, but delete can.
|
2

Yes;

fred["major"] = "Computer Science";

All properties on an object can be accessed by using square brackets and the property name. This method also allows you to set new properties.

fred.major = "Computer Science";

This will also work fine.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.