JavaScript Objects - Creating, Accessing, and Manipulating Objects
Author
Pedro GeoGIS
Published
Monday, January 13, 2025
Modified
Monday, October 13, 2025
1 Overview
📘 Objects
Objects are used to store keyed collections of various data and more complex entities. Unlike primitive types that contain only a single value, objects can store multiple values as properties. An object is a collection of key-value pairs where keys are strings (or Symbols) and values can be of any type. Objects are fundamental to JavaScript and penetrate almost every aspect of the language.
2 Creating Objects
An object can be created with curly brackets {...} with an optional list of properties.
2.1 Object Literal Syntax
let user = {};// empty object
2.2 Object Constructor Syntax
let user =newObject();// empty object
Recommendation: Use object literal syntax {} as it’s more concise and commonly used.
3 Literals and Properties
We can immediately put some properties into {...} as “key: value” pairs:
let user = {name:"John",// by key "name" store value "John"age:30// by key "age" store value 30};
A property has a key (also known as “name” or “identifier”) before the colon : and a value to the right of it.
4 Accessing Properties
4.1 Dot Notation
Property values are accessible using the dot notation:
let user = {name:"John",age:30};alert(user.name);// Johnalert(user.age);// 30
4.2 Adding Properties
user.isAdmin=true;
4.3 Removing Properties
To remove a property, use the delete operator:
delete user.age;
4.4 Multiword Property Names
We can use multiword property names, but they must be quoted:
let user = {name:"John",age:30,"likes birds":true// multiword property name must be quoted};
4.5 Trailing Comma
The last property in the list may end with a comma:
let user = {name:"John",age:30,// trailing comma};
This makes it easier to add/remove/move around properties.
5 Square Bracket Notation
For multiword properties, the dot access doesn’t work:
// This would give a syntax erroruser.likes birds =true
Use square bracket notation instead:
let user = {};// setuser["likes birds"] =true;// getalert(user["likes birds"]);// true// deletedelete user["likes birds"];
5.1 Dynamic Property Access
Square brackets provide a way to obtain the property name from a variable:
let user = {name:"John",age:30};let key =prompt("What do you want to know about the user?","name");// access by variablealert(user[key]);// John (if enter "name")
The dot notation cannot be used this way:
let key ="name";alert(user.key);// undefined (looks for property named "key")
6 Computed Properties
We can use square brackets in an object literal when creating an object. That’s called computed properties.
let fruit =prompt("Which fruit to buy?","apple");let bag = { [fruit]:5,// the name of the property is taken from the variable fruit};alert(bag.apple);// 5 if fruit="apple"
This is the same as:
let fruit =prompt("Which fruit to buy?","apple");let bag = {};bag[fruit] =5;
6.1 Complex Expressions
let fruit ='apple';let bag = { [fruit +'Computers']:5// bag.appleComputers = 5};
7 Property Value Shorthand
In real code, we often use existing variables as values for property names:
functionmakeUser(name, age) {return {name: name,age: age, };}let user =makeUser("John",30);alert(user.name);// John
7.1 Shorthand
When property name and variable name are the same, we can use property value shorthand:
functionmakeUser(name, age) {return { name,// same as name: name age,// same as age: age };}
We can use both normal properties and shorthands in the same object:
let user = { name,// same as name:nameage:30};
8 Property Names Limitations
A variable cannot have a name equal to one of the language-reserved words like “for”, “let”, “return”, etc.
But for an object property, there’s no such restriction:
let obj = {for:1,let:2,return:3};alert(obj.for+ obj.let+ obj.return);// 6
8.1 Special Property: proto
There’s a minor gotcha with a special property named __proto__. We can’t set it to a non-object value:
let obj = {};obj.__proto__=5;// assign a numberalert(obj.__proto__);// [object Object] - didn't work as intended
9 Property Existence Test
A notable feature of objects in JavaScript is that it’s possible to access any property. There will be no error if the property doesn’t exist!
Reading a non-existing property just returns undefined:
let user = {};alert(user.noSuchProperty===undefined);// true means "no such property"
9.1 The “in” Operator
There’s a special operator "in" for checking property existence:
let user = { name:"John",age:30 };alert("age"in user);// true, user.age existsalert("blabla"in user);// false, user.blabla doesn't exist
Note that on the left side of in there must be a property name (usually a quoted string).
9.2 Why Use “in”?
Usually, the comparison with undefined works fine. But there’s a special case when it fails:
let obj = {test:undefined};alert(obj.test);// undefined, so property doesn't exist?alert("test"in obj);// true, the property does exist!
10 The “for…in” Loop
To walk over all keys of an object, use the for...in loop:
for (key in object) {// executes the body for each key among object properties}
10.1 Example
let user = {name:"John",age:30,isAdmin:true};for (let key in user) {// keysalert(key);// name, age, isAdmin// values for the keysalert(user[key]);// John, 30, true}
11 Object References and Copying
One of the fundamental differences between objects and primitives is that objects are stored and copied “by reference”, whereas primitive values are copied “as a whole value”.
let message ="Hello!";let phrase = message;// copied by value
With objects:
let user = { name:"John" };let admin = user;// copy the referenceadmin.name='Pete';// changed by the "admin" referencealert(user.name);// 'Pete', changes are seen from the "user" reference
11.1 Comparison by Reference
Two objects are equal only if they are the same object:
let a = {};let b = a;// copy the referencealert(a == b);// true, both variables reference the same objectalert(a === b);// true
But two independent objects are not equal:
let a = {};let b = {};// two independent objectsalert(a == b);// false
12 Cloning Objects
12.1 Manual Cloning
let user = {name:"John",age:30};let clone = {};// the new empty object// let's copy all user properties into itfor (let key in user) { clone[key] = user[key];}// now clone is a fully independent objectclone.name="Pete";alert(user.name);// still John in the original object
12.2 Object.assign
We can use Object.assign for cloning:
Object.assign(dest,...sources)
Example:
let user = { name:"John" };let permissions1 = { canView:true };let permissions2 = { canEdit:true };// copies all properties from permissions1 and permissions2 into userObject.assign(user, permissions1, permissions2);// now user = { name: "John", canView: true, canEdit: true }
12.3 Simple Cloning
let user = {name:"John",age:30};let clone =Object.assign({}, user);
13 Nested Objects
Objects can contain other objects as properties:
let user = {name:"John",sizes: {height:182,width:50 }};alert(user.sizes.height);// 182
13.1 Deep Cloning
For nested objects, simple cloning doesn’t work:
let user = {name:"John",sizes: {height:182,width:50 }};let clone =Object.assign({}, user);alert(user.sizes=== clone.sizes);// true, same object// user and clone share sizesuser.sizes.width=60;alert(clone.sizes.width);// 60, changed from the other object
Use structuredClone for deep cloning:
let clone =structuredClone(user);alert(user.sizes=== clone.sizes);// false, different objectsuser.sizes.width=60;alert(clone.sizes.width);// 50, not affected
14 Examples
14.1 Example 1: User Object
let user = {name:"John",age:30,email:"john@example.com",isAdmin:false};console.log(user.name);// Johnconsole.log(user["age"]);// 30
14.2 Example 2: Modifying Properties
let user = {name:"John",age:30};user.age=31;user.city="New York";delete user.age;console.log(user);// { name: "John", city: "New York" }
14.3 Example 3: Methods in Objects
let user = {name:"John",age:30,sayHi:function() {alert("Hello!"); }};user.sayHi();// Hello!// Method shorthandlet user2 = {name:"John",sayHi() { // same as sayHi: function()alert("Hello!"); }};
14.4 Example 4: this Keyword
let user = {name:"John",age:30,sayHi() {alert(this.name);// "this" refers to the current object }};user.sayHi();// John
14.5 Example 5: Iterating Over Properties
let user = {name:"John",age:30,city:"New York"};for (let key in user) {console.log(`${key}: ${user[key]}`);}// Output:// name: John// age: 30// city: New York
14.6 Example 6: Object as Function Parameter
functionprintUser(user) {console.log(`Name: ${user.name}`);console.log(`Age: ${user.age}`);}let user = {name:"Alice",age:25};printUser(user);
15 Summary
Objects are collections of key-value pairs
Create objects with {} or new Object()
Access properties with dot notation (obj.prop) or square brackets (obj["prop"])
Square brackets allow dynamic property access
Use delete to remove properties
Use in operator to check if property exists
Use for...in loop to iterate over object properties
Objects are stored and copied by reference
Use Object.assign() for shallow cloning
Use structuredClone() for deep cloning
Property names can be any string (including reserved words)
Objects can contain other objects (nested objects)
Objects can have methods (functions as properties)