๐ŸŸก JavaScript Objects โ€“ Basics

priyanka kumaripriyanka kumari
6 min read

๐Ÿ”น 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! ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป


10
Subscribe to my newsletter

Read articles from priyanka kumari directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

priyanka kumari
priyanka kumari