Contact Mentor

Projects + Tutorials on React JS & JavaScript

5 ways to Add a Property to object in JavaScript

To demonstrate adding new properties to JavaScript object, we will consider the following example of an employee object:

There are multiple instances to consider, which are as follows:

Please enable JavaScript

  • Static property names : Addition of “id” property to an employee object.
  • Dynamic property names : Include property based on the value of “customProp” variable.
  • Adding properties from another object : Add location property from a person object to an employee object.

1. “object.property_name” syntax

The dot notation is the simplest way to access/modify the properties of a JavaScript object. A new property can be initialized by the following syntax:

In the below example, we are creating an “id” property with the value 130 for the employee object.

Further, adding properties for nested objects follows a similar syntax:

Below, the “country” property is added to a nested object which is the value of the “location” parent property in the employee object.

This approach is most ideal for the following instances:

  • The property name is a static value and needs to be initialized manually.
  • Property names don’t include special characters like extra space, etc.

2. Access property though “object[‘property_name’]”

The syntax based on the square brackets is an alternative approach with similar capabilities and avoids most of the disadvantages of the dot operator. The syntax for adding new property using square brackets is as follows:

Square bracket syntax offers the following advantages over traditional dot operator:

  • When the property name is based on a dynamic variable . For example, the property name is retrieved from API calls, user inputs, etc.
  • The property name string value contains special characters like extra space, etc.

In the below example, the “Last name” property cannot be directly added using dot operator syntax due to the presence of space characters . Hence, we are able to accomplish the creation of “Last name” property using square bracket syntax.

The nested objects are accessed using a series of multiple square bracket syntax or alternatively, a combination of dot operator and square brackets can also be used.

3. Create new property using Object.defineProperty()

JavaScript Object class also provides native “ defineProperty() ” method to define new properties for an object. In addition to specifying the value of the new property, “ defineProperty() ” also allow configuring the behavior for the property .

The generic syntax for “defineProperty()” is as follows:

In the below example, we define “id” property for the employee object with a value of 130 and writable as false . Hence, subsequent changes in the value of the id property are discarded. Read more about Object.defineProperty from developer.mozilla.org/Object/defineProperty .

4. Spread operator syntax “{ …object, property_name: property_value } “

The spread operator allows the creation of a soft copy of an object with existing properties. The Spread operator followed by an inline property definition allows the addition of new properties. Further, the properties of another object can be added by using the spread operator multiple times.

In the below example, we create a copy of the employee object combined with location and id properties. Next line, “id” object is added to employee object using the spread operator .

5. Assign properties using Object.assign()

The “Object.assign()” method allows properties of the source object to be added to the target object . By defining all the new properties which need to be added to the source object, we achieve the addition of properties to a target object.

In the below example, we add the “id” property with value 670 to the employee object using Object.assign.

Finally, to conclude the summary of the methods to add properties to objects is as follows:

  • Dot method syntax is ideal for static property values.
  • Square bracket syntax works best for dynamic values from external API, user input, etc.
  • Object.defineProperty() is used when the property’s writability, getter, setters, etc needs to be configured.
  • In object/array formatter functions and when properties from another object are included, the spread operator and Object.assign() are more ideal.

Related Articles

How to Remove Property from a JavaScript object

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • English (US)

Working with objects

JavaScript is designed on a simple object-based paradigm. An object is a collection of properties , and a property is an association between a name (or key ) and a value. A property's value can be a function, in which case the property is known as a method .

Objects in JavaScript, just as in many other programming languages, can be compared to objects in real life. In JavaScript, an object is a standalone entity, with properties and type. Compare it with a cup, for example. A cup is an object, with properties. A cup has a color, a design, weight, a material it is made of, etc. The same way, JavaScript objects can have properties, which define their characteristics.

In addition to objects that are predefined in the browser, you can define your own objects. This chapter describes how to use objects, properties, and methods, and how to create your own objects.

Creating new objects

You can create an object using an object initializer . Alternatively, you can first create a constructor function and then instantiate an object by invoking that function with the new operator.

Using object initializers

Object initializers are also called object literals . "Object initializer" is consistent with the terminology used by C++.

The syntax for an object using an object initializer is:

Each property name before colons is an identifier (either a name, a number, or a string literal), and each valueN is an expression whose value is assigned to the property name. The property name can also be an expression; computed keys need to be wrapped in square brackets. The object initializer reference contains a more detailed explanation of the syntax.

In this example, the newly created object is assigned to a variable obj — this is optional. If you do not need to refer to this object elsewhere, you do not need to assign it to a variable. (Note that you may need to wrap the object literal in parentheses if the object appears where a statement is expected, so as not to have the literal be confused with a block statement.)

Object initializers are expressions, and each object initializer results in a new object being created whenever the statement in which it appears is executed. Identical object initializers create distinct objects that do not compare to each other as equal.

The following statement creates an object and assigns it to the variable x if and only if the expression cond is true:

The following example creates myHonda with three properties. Note that the engine property is also an object with its own properties.

Objects created with initializers are called plain objects , because they are instances of Object , but not any other object type. Some object types have special initializer syntaxes — for example, array initializers and regex literals .

Using a constructor function

Alternatively, you can create an object with these two steps:

  • Define the object type by writing a constructor function. There is a strong convention, with good reason, to use a capital initial letter.
  • Create an instance of the object with new .

To define an object type, create a function for the object type that specifies its name, properties, and methods. For example, suppose you want to create an object type for cars. You want this type of object to be called Car , and you want it to have properties for make, model, and year. To do this, you would write the following function:

Notice the use of this to assign values to the object's properties based on the values passed to the function.

Now you can create an object called myCar as follows:

This statement creates myCar and assigns it the specified values for its properties. Then the value of myCar.make is the string "Eagle" , myCar.model is the string "Talon TSi" , myCar.year is the integer 1993 , and so on. The order of arguments and parameters should be the same.

You can create any number of Car objects by calls to new . For example,

An object can have a property that is itself another object. For example, suppose you define an object called Person as follows:

and then instantiate two new Person objects as follows:

Then, you can rewrite the definition of Car to include an owner property that takes a Person object, as follows:

To instantiate the new objects, you then use the following:

Notice that instead of passing a literal string or integer value when creating the new objects, the above statements pass the objects rand and ken as the arguments for the owners. Then if you want to find out the name of the owner of car2 , you can access the following property:

You can always add a property to a previously defined object. For example, the statement

adds a property color to car1 , and assigns it a value of "black" . However, this does not affect any other objects. To add the new property to all objects of the same type, you have to add the property to the definition of the Car object type.

You can also use the class syntax instead of the function syntax to define a constructor function. For more information, see the class guide .

Using the Object.create() method

Objects can also be created using the Object.create() method. This method can be very useful, because it allows you to choose the prototype object for the object you want to create, without having to define a constructor function.

Objects and properties

A JavaScript object has properties associated with it. Object properties are basically the same as variables, except that they are associated with objects, not scopes . The properties of an object define the characteristics of the object.

For example, this example creates an object named myCar , with properties named make , model , and year , with their values set to "Ford" , "Mustang" , and 1969 :

Like JavaScript variables, property names are case sensitive. Property names can only be strings or Symbols — all keys are converted to strings unless they are Symbols. Array indices are, in fact, properties with string keys that contain integers.

Accessing properties

You can access a property of an object by its property name. Property accessors come in two syntaxes: dot notation and bracket notation . For example, you could access the properties of the myCar object as follows:

An object property name can be any JavaScript string or symbol , including an empty string. However, you cannot use dot notation to access a property whose name is not a valid JavaScript identifier. For example, a property name that has a space or a hyphen, that starts with a number, or that is held inside a variable can only be accessed using the bracket notation. This notation is also very useful when property names are to be dynamically determined, i.e. not determinable until runtime. Examples are as follows:

In the above code, the key anotherObj is an object, which is neither a string nor a symbol. When it is added to the myObj , JavaScript calls the toString() method of anotherObj , and use the resulting string as the new key.

You can also access properties with a string value stored in a variable. The variable must be passed in bracket notation. In the example above, the variable str held "myString" and it is "myString" that is the property name. Therefore, myObj.str will return as undefined.

This allows accessing any property as determined at runtime:

However, beware of using square brackets to access properties whose names are given by external input. This may make your code susceptible to object injection attacks .

Nonexistent properties of an object have value undefined (and not null ).

Enumerating properties

There are three native ways to list/traverse object properties:

  • for...in loops. This method traverses all of the enumerable string properties of an object as well as its prototype chain.
  • Object.keys() . This method returns an array with only the enumerable own string property names ("keys") in the object myObj , but not those in the prototype chain.
  • Object.getOwnPropertyNames() . This method returns an array containing all the own string property names in the object myObj , regardless of if they are enumerable or not.

You can use the bracket notation with for...in to iterate over all the enumerable properties of an object. To illustrate how this works, the following function displays the properties of the object when you pass the object and the object's name as arguments to the function:

The term "own property" refers to the properties of the object, but excluding those of the prototype chain. So, the function call showProps(myCar, 'myCar') would print the following:

The above is equivalent to:

There is no native way to list inherited non-enumerable properties. However, this can be achieved with the following function:

For more information, see Enumerability and ownership of properties .

Deleting properties

You can remove a non-inherited property using the delete operator. The following code shows how to remove a property.

Inheritance

All objects in JavaScript inherit from at least one other object. The object being inherited from is known as the prototype, and the inherited properties can be found in the prototype object of the constructor. See Inheritance and the prototype chain for more information.

Defining properties for all objects of one type

You can add a property to all objects created through a certain constructor using the prototype property. This defines a property that is shared by all objects of the specified type, rather than by just one instance of the object. The following code adds a color property to all objects of type Car , and then reads the property's value from an instance car1 .

Defining methods

A method is a function associated with an object, or, put differently, a method is a property of an object that is a function. Methods are defined the way normal functions are defined, except that they have to be assigned as the property of an object. See also method definitions for more details. An example is:

where objectName is an existing object, methodName is the name you are assigning to the method, and functionName is the name of the function.

You can then call the method in the context of the object as follows:

Methods are typically defined on the prototype object of the constructor, so that all objects of the same type share the same method. For example, you can define a function that formats and displays the properties of the previously-defined Car objects.

Notice the use of this to refer to the object to which the method belongs. Then you can call the displayCar method for each of the objects as follows:

Using this for object references

JavaScript has a special keyword, this , that you can use within a method to refer to the current object. For example, suppose you have 2 objects, Manager and Intern . Each object has its own name , age and job . In the function sayHi() , notice the use of this.name . When added to the 2 objects, the same function will print the message with the name of the respective object it's attached to.

this is a "hidden parameter" of a function call that's passed in by specifying the object before the function that was called. For example, in Manager.sayHi() , this is the Manager object, because Manager comes before the function sayHi() . If you access the same function from another object, this will change as well. If you use other methods to call the function, like Function.prototype.call() or Reflect.apply() , you can explicitly pass the value of this as an argument.

Defining getters and setters

A getter is a function associated with a property that gets the value of a specific property. A setter is a function associated with a property that sets the value of a specific property. Together, they can indirectly represent the value of a property.

Getters and setters can be either

  • defined within object initializers , or
  • added later to any existing object.

Within object initializers , getters and setters are defined like regular methods , but prefixed with the keywords get or set . The getter method must not expect a parameter, while the setter method expects exactly one parameter (the new value to set). For instance:

The myObj object's properties are:

  • myObj.a — a number
  • myObj.b — a getter that returns myObj.a plus 1
  • myObj.c — a setter that sets the value of myObj.a to half of the value myObj.c is being set to

Getters and setters can also be added to an object at any time after creation using the Object.defineProperties() method. This method's first parameter is the object on which you want to define the getter or setter. The second parameter is an object whose property names are the getter or setter names, and whose property values are objects for defining the getter or setter functions. Here's an example that defines the same getter and setter used in the previous example:

Which of the two forms to choose depends on your programming style and task at hand. If you can change the definition of the original object, you will probably define getters and setters through the original initializer. This form is more compact and natural. However, if you need to add getters and setters later — maybe because you did not write the particular object — then the second form is the only possible form. The second form better represents the dynamic nature of JavaScript, but it can make the code hard to read and understand.

Comparing objects

In JavaScript, objects are a reference type. Two distinct objects are never equal, even if they have the same properties. Only comparing the same object reference with itself yields true.

For more information about comparison operators, see equality operators .

  • Inheritance and the prototype chain
  • Stack Overflow Public questions & answers
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Talent Build your employer brand
  • Advertising Reach developers & technologists worldwide
  • Labs The future of collective knowledge sharing
  • About the company

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

How to conditionally add properties to a javascript object literal

I am trying to do the following to satisfy the requirements of a code builder (Sencha Cmd to be specific).

This is the essence I what I need to do. The critical factor is that the function body MUST end with a return of an object literal. I cant return a variable due to restrictions in the builder. So, how to add a property 'b' at the point of the pseudo code below if the parameter 'includeB' is true, but NOT add a property AT ALL if it is false. ie b==undefined or b==null is not allowed.

Perhaps it is not possible.

Thanks for reading and considering,

Murrah's user avatar

  • 1 what prevents you from changing the object returned by the function? This seems like an XY Problem –  zzzzBov Feb 5, 2014 at 4:53
  • I don't have access to it. The builder is reading the JS from the file system using a Java app (Sencha Cmd). The function provided is a test case since trying to demonstrate the complete real situation would have been too confusing. The test case was the essence of the problem. –  Murrah Feb 5, 2014 at 5:34
  • Possible duplicate of Conditionally set a JSON object property –  rofrol Mar 21, 2016 at 1:20
  • Possible duplicate of stackoverflow.com/questions/11704267/… –  djskinner Mar 7, 2017 at 16:26

8 Answers 8

If you can use ES6, use the spread properties .

hoshi's user avatar

  • This is elegant syntax in many cases, but requires Object Rest/Spread, which currently is currently (2017-10-29) only a Stage 3 proposal for some future ECMAScript version; work well with Babel's transform, though. –  Thomas Luzat Oct 29, 2017 at 0:54
  • 29 you can even write ...(includeB && { b: 2 } ) –  marco Oct 16, 2018 at 14:01

You've pretty much shown a use case for a constructor function instead of using an object literal:

After re-reading your question it appears that you've got limited access in modifying the function. If I'm understanding your question correctly you can only change a limited portion of the script:

If that's the case, then you could simply skip the later part of the function:

zzzzBov's user avatar

  • OK. Sorry for the delay. I was testing this solution in the real app with the builder. Yes! This syntax is acceptable to the builder. I had previously tried by using an 'else' block but didn't think to try just a plain return. Thank you! –  Murrah Feb 5, 2014 at 5:30
  • To be clear, this is the syntax that kept the builder happy: function create(includeB) { if (includeB) { return { a: 1, b: 2 }; } return { a: 1 }; } –  Murrah Feb 5, 2014 at 5:37

You cannot put boolean logic inside a javascript literal definition. So, if your builder requires the the returned object can ONLY be defined as a javascript literal, then you cannot define properties conditionally that way.

If you can create an object inside your function, modify that object using logic and then return that object, then that's pretty easy.

Your other option would be to wrap the create function and do it outside the create function.

Or, you could even wrap the create function transparently so callers still use create() , but it's behavior has been altered.

jfriend00's user avatar

  • Thanks. Yes, it must be done within the literal. I thought I was probably asking a lot! –  Murrah Feb 5, 2014 at 4:46
  • @Murrah - I added two more option that have you wrap the create function and add your logic outside the existing create() function. –  jfriend00 Feb 5, 2014 at 4:47
  • Thanks. Again, the builder requirement in the specific situation is that whatever function I give it, it must have the literal return. return x; is "illegal" in the specific case. –  Murrah Feb 5, 2014 at 4:51
  • @Murrah - My last two suggestions did not modify the actual create() function. It can be left as is without the .b property. I was suggesting how you could add some plain javascript that would wrap or modify the create() function to make it behave the way you wanted. Can you not add regular javascript to your project? –  jfriend00 Feb 5, 2014 at 4:52

I recently had to do this, and found you could use a self-calling function within an object's definition (if using ES6). This is similar to the accepted answer, but might be useful for others who need to do this without first defining a constructor function.

For example:

makes the object: { a: 1, b: 2 }

It's handy for more complicated objects, keeping the construction continuous:

makes the object:

M P's user avatar

You could define it later:

Alternatively, using your argument in create :

bozdoz's user avatar

  • Yes, normally that is what I would do. As I say, in this case due to external requirements, I cannot do that because the code builder is essentially consuming the result of the create function, so I dont have access to it. If it is possible at all it MUST be done where the pseudo code is. –  Murrah Feb 5, 2014 at 4:44
  • @Murrah You wouldn't be able to do it within an object. Perhaps you could try option #1 in my answer? –  bozdoz Feb 5, 2014 at 4:45
  • 1 @Murrah: An object literal has a very specific syntax. This syntax doesn't provide any means to conditionally set a property. –  Felix Kling Feb 5, 2014 at 4:49
  • You could set b to be a function which returns 2 or undefined @Murrah –  bozdoz Feb 5, 2014 at 4:49
  • Correct @zzzzBov, but it's an option. Honestly, the example given in the question doesn't seem sufficient for whatever real problem OP is trying to solve. –  bozdoz Feb 5, 2014 at 4:51

Below should work. I hope this help.

function create(includeB){

Tee's user avatar

  • Thanks. Same as above, cant return an object, must be a literal. –  Murrah Feb 5, 2014 at 5:02

How about this:

When includeB is true, the create function will return {a:1, b:2} . If includeB is false, it will return whatever is after the or - in this case, the {a:1} object.

create(true) returns { a:1, b:2 } .

create(false) returns { a:1 }

Blundering Philosopher's user avatar

  • I think you're looking for ternary notation: condition ? true : false; –  bozdoz Feb 5, 2014 at 4:49
  • I'm not sure what this notation is called, but it seems to do what the OP asked for. –  Blundering Philosopher Feb 5, 2014 at 4:51
  • I guess it's another ternary. I expected it to return boolean or an object. –  bozdoz Feb 5, 2014 at 4:53

If you would like to use a declaration to satisfy the same requirement once without too much bloat, you can also simply do the following:

rob2d's user avatar

Your Answer

Sign up or log in, post as a guest.

Required, but never shown

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

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

  • The Overflow Blog
  • Like Python++ for AI developers
  • Being creative with math: The immersive artist who traded a sketchpad for a...
  • Featured on Meta
  • Alpha test for short survey in banner ad slots starting on week of September...
  • What should be next for community events?
  • OverflowAI Search is now available for alpha testing (September 13, 2023)
  • Temporary policy: Generative AI (e.g., ChatGPT) is banned
  • Expanding Discussions: Let's talk about curation
  • Update on Collectives and Discussions

Hot Network Questions

  • Does the increase in German exports to Russia's neighbors make up for losses in Russia proper?
  • Is a passenger who is flying the aircraft liable for regulations that they violate?
  • general principles of piercing the protective cover of unfrozen microwave ready meals
  • How to check if the given row matches one of the rows of a table?
  • What should I do if I am strongly burned out at work, but resigning now would cause problems for my coworkers and burn bridges?
  • How were the signs for logical and arithmetic operators decided?
  • Why would people join a bloc party?
  • Civil liability for criminal punishment
  • What was the purpose of this feature on samurai armor?
  • Are you allowed to paint a sukkah?
  • Daisy chaining APs or connect them into the central router?
  • Is it possible to work on your personal idea as PhD thesis?
  • When are two semidirect products of two cyclic groups isomorphic
  • Why is Trump's alleged fraud in New York not prosecuted as a criminal offense?
  • In countries using Single Transferable Vote, how are voting results presented?
  • What attracted Abimelech to an old woman in her 80s or 90s?
  • When was the end of the floppy-only IBM PC clone?
  • Creating a new language with Rust without Garbage Collection?
  • How can do you learn about residential sprinkler systems in the US?
  • Delete list elements above a certain threshold
  • History of right hand rule
  • How to split a long set
  • What was the big pillar-shaped Beholder in 3.5?
  • My husband (her father) jokes/plays in ways my daughter doesn't always find funny, he says he should be able to do it if he wants

assign property to object

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

IMAGES

  1. JavaScript Object.assign() method

    assign property to object

  2. HOW TO: Assign Properties to Objects

    assign property to object

  3. JavaScript Object.assign() method

    assign property to object

  4. 33 Javascript Assign Property To Object

    assign property to object

  5. reference

    assign property to object

  6. 33 Javascript Assign Property To Object

    assign property to object

VIDEO

  1. Change object property

  2. Object Property 2 Javascript #shorts

  3. Object.create() vs Object.assign() Methods in Javascript

  4. Broken Object Property Level Authorization

  5. Object Property 1 Javascript

  6. Creating a Custom Object and master Detail Relationship on an exiting custom Object

COMMENTS

  1. Object.assign()

    The Object.assign () method only copies enumerable and own properties from a source object to a target object. It uses [ [Get]] on the source and [ [Set]] on the target, so it will invoke getters and setters. Therefore it assigns properties, versus copying or defining new properties.

  2. How do I dynamically assign properties to an object in

    If I wanted to programatically assign a property to an object in Javascript, I would do it like this: var obj = {}; obj.prop = "value"; But in TypeScript, this generates an error: The property 'prop' does not exist on value of type ' {}' How am I supposed to assign any new property to an object in TypeScript? typescript Share Improve this question

  3. Working with objects

    The following statement creates an object and assigns it to the variable x if and only if the expression cond is true: js let x; if (cond) { x = { greeting: "hi there" }; } The following example creates myHonda with three properties. Note that the engine property is also an object with its own properties. js

  4. How to conditionally add properties to a javascript object

    function create (includeB) { // Can have code here but the final thing MUST be a return of the literal. // ... return { a : 1 // pseudo code: // if (includeB==true) then create a property called b // and assign a value of 2 to it.