๐ก JavaScript Objects โ Basics

๐น Data Types in JavaScript
JavaScript has 8 data types, and 7 of them are called primitive.
Primitive means they can contain only a single value. These include:
string
number
bigint
boolean
symbol
null
undefined
The remaining one is object, which can store multiple values using key-value pairs.
๐น Creating Objects in JavaScript
You can create objects in two ways:
1. Using Object Constructor:
jsCopyEditlet user = new Object();
2. Using Object Literal:
jsCopyEditlet user = {
name: "John", // key: "name", value: "John"
age: 30 // key: "age", value: 30
};
๐น Working with Object Properties
๐ Accessing Properties:
jsCopyEdituser.name; // John
๐ Adding Properties:
jsCopyEdituser.isAdmin = true;
๐ Deleting Properties:
jsCopyEditdelete user.age;
๐น Multiword Property Names
If a property name contains spaces or special characters, use quotes:
jsCopyEditlet user = {
name: "John",
age: 30,
"likes birds": true
};
Access using square brackets:
jsCopyEdituser["likes birds"] = true; // set
alert(user["likes birds"]); // get: true
delete user["likes birds"]; // delete
๐น Dot Notation vs Bracket Notation
Dot Notation:
jsCopyEditlet user = {
name: "John",
age: 30
};
alert(user.name); // John
Bracket Notation (can use variables as keys):
jsCopyEditlet key = prompt("What do you want to know about the user?", "name");
alert(user[key]); // John (if user enters "name")
Important: Dot notation doesnโt work with variables.
jsCopyEditlet key = "name";
alert(user.key); // undefined
๐น Property Keys are Always Strings
Even if you use a number as a key, JavaScript converts it to a string:
jsCopyEditlet obj = {};
obj[0] = "zero";
alert(obj["0"]); // "zero"
๐น Checking Property Existence: "in"
Operator
jsCopyEditlet user = {};
alert(user.noSuchProp === undefined); // true
let user2 = { age: 30 };
alert("age" in user2); // true
When "in"
is Better:
jsCopyEditlet obj = {
test: undefined
};
alert(obj.test); // undefined
alert("test" in obj); // true
๐น Looping Through Properties: for...in
jsCopyEditlet user = {
name: "John",
age: 30,
isAdmin: true
};
for (let key in user) {
alert(key); // name, age, isAdmin
alert(user[key]); // John, 30, true
}
๐น Object Property Order
For string keys, JavaScript preserves the insertion order.
For number-like keys, JavaScript sorts them numerically:
jsCopyEditlet codes = {
"49": "Germany",
"41": "Switzerland",
"44": "UK",
"1": "USA"
};
for (let code in codes) {
alert(code); // 1, 41, 44, 49
}
Fixing Numeric Order Issue:
jsCopyEditlet codes = {
"+49": "Germany",
"+41": "Switzerland",
"+44": "UK",
"+1": "USA"
};
for (let code in codes) {
alert(+code); // 49, 41, 44, 1
}
๐งฉ Task: Check for Emptiness
Write a function isEmpty(obj)
that returns true
if the object has no properties, otherwise false
.
jsCopyEditfunction isEmpty(obj) {
for (let key in obj) {
return false; // if at least one property exists
}
return true;
}
// Test
let schedule = {};
alert(isEmpty(schedule)); // true
schedule["8:30"] = "get up";
alert(isEmpty(schedule)); // false
๐งฉ Task: Sum Object Properties
jsCopyEditlet salaries = {
John: 100,
Ann: 160,
Pete: 130
};
let sum = 0;
for (let key in salaries) {
sum += salaries[key];
}
alert(sum); // 390
๐ง Understanding JavaScript Objects: Copying, Referencing & Cloning
When you're starting out with JavaScript, one concept that can be a bit confusing is how objects behave when copied or assigned to new variables. Let's dive into it!
๐ Primitive vs. Object Copying
In JavaScript, primitive values like strings, numbers, and booleans are copied by value. That means a new, separate copy is created in memory.
let message = "Hello!";
let phrase = message;
console.log(message); // "Hello!"
console.log(phrase); // "Hello!"
Here, message
and phrase
are two different variables with the same string value.
But objects work differently...
๐ Objects Are Copied by Reference
When you assign an object to another variable, you're not copying the object itself โ you're copying a reference to it.
let user = { name: "John" };
let admin = user;
admin.name = "Pete";
console.log(user.name); // "Pete"
Even though we updated admin.name
, the change is reflected in user
as well, because both variables reference the same object in memory.
๐ Object Comparison: Reference Only
Objects are only equal if they reference the same object.
let a = {};
let b = a;
console.log(a == b); // true
console.log(a === b); // true
let x = {};
let y = {};
console.log(x == y); // false
Even if two objects have identical content, theyโre not equal unless they reference the same object.
๐ Const Objects Can Still Be Modified
Declaring an object with const
doesnโt make it immutable โ it only prevents reassignment of the reference.
const user = { name: "John" };
user.name = "Pete"; // โ
allowed
// user = {} โ Not allowed
To make object properties truly immutable, youโd need techniques like Object.freeze()
or property descriptors.
๐ฆ Shallow Copy with Object.assign()
If you want to create a new object with the same top-level properties, you can use:
let user = { name: "John", age: 30 };
let clone = Object.assign({}, user);
console.log(clone); // { name: "John", age: 30 }
You can also merge multiple objects:
let permissions1 = { canView: true };
let permissions2 = { canEdit: true };
Object.assign(user, permissions1, permissions2);
But be careful โ Object.assign()
performs a shallow copy. It copies only the first level of properties.
๐ช The Problem with Nested Objects
let user = {
name: "John",
sizes: {
height: 182,
width: 50
}
};
let clone = Object.assign({}, user);
console.log(user.sizes === clone.sizes); // true
Both user
and clone
share the same sizes
object โ changing one affects the other. To fix this, we need a deep copy.
๐งฌ Deep Copy with structuredClone()
To clone an object with all nested properties:
let clone = structuredClone(user);
This creates a completely independent copy of the original object, even for nested values and circular references.
let user = {};
user.self = user;
let clone = structuredClone(user);
console.log(clone.self === clone); // true
โ ๏ธ
structuredClone()
doesnโt support functions, symbols, or non-cloneable values.
๐ Advanced Cloning: Use Libraries
For advanced or complex scenarios (functions inside objects, symbols, etc.), use libraries like Lodash:
import _ from 'lodash';
let deepClone = _.cloneDeep(originalObject);
๐งฉ Task: implement Object.assign()
create polyfill for shallow and deep cloning
๐ Summary
Primitives are copied by value.
Objects are copied by reference.
Use
Object.assign()
or{...obj}
for shallow copies.Use
structuredClone()
or_.cloneDeep()
for deep copies.const
objects can still have their properties modified.
Understanding object references is key to mastering JavaScript behavior in real-world apps. Happy coding! ๐ฉโ๐ป๐จโ๐ป
Subscribe to my newsletter
Read articles from priyanka kumari directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
