iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

JS Objects

A JavaScript object is an unordered collection of key-value pairs. Almost everything in JS — arrays, functions, dates, even modules — is built on top of objects.

Creating objects

JS
// Object literal — the everyday way
const user = {
  name: "Ada",
  age: 36,
  greet() { return `Hi, ${this.name}!`; }
};

// Reading values
user.name           // "Ada"
user["age"]         // 36
user.greet()        // "Hi, Ada!"

// Adding / changing properties
user.role = "admin";
delete user.age;

Useful built-in helpers

HelperReturns
Object.keys(obj)Array of property names
Object.values(obj)Array of values
Object.entries(obj)Array of [key, value] pairs
Object.assign(target, src)Copies properties from src to target
{ ...obj1, ...obj2 }Shallow merge via spread
Object.freeze(obj)Makes obj read-only

Destructuring

JS
const { name, age = 0, ...rest } = user;
// name === "Ada", age === 36 or 0 if missing, rest has the others

Shorthand syntax

JS
const name = "Ada", age = 36;
const user = { name, age };          // same as { name: name, age: age }

const key = "role";
const obj = { [key]: "admin" };      // computed property name → { role: "admin" }
Tip: Prefer immutable updates with spread — { ...user, age: 37 } — over mutating an object in place. It plays nicely with React, undo stacks, and reasoning about state.

Example

Example
<!DOCTYPE html>
<html>
<body>

<p id="out"></p>

<script>
document.getElementById("out").textContent = "Hello from JS Objects!";
</script>

</body>
</html>
Try it Yourself »

Exercise

Return an array of an object's property names.

const names = Object. (user);

Test yourself

Q1. Which returns an array of an object's keys?
Q2. Shallow-merge two objects with…
Q3. `Object.freeze(obj)` does what?

Discussion

Loading…