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

Object Definitions

JavaScript gives you four ways to create an object. The literal is the daily choice; the others have niches.

Four creation styles

StyleExampleUse it for
Object literal{ name: "Ada" }One-off records — the everyday default.
new Object()const o = new Object(); o.name = "Ada"Almost never — literals win.
Constructor functionfunction User(name){ this.name = name }Legacy "class" pattern.
classclass User { constructor(name){ this.name = name } }Modern equivalent — many instances.
Object.create(proto)Manually set a prototype.

Object literal features

JS
const name = "Ada", age = 36;
const role = "admin";

const user = {
  name,                       // shorthand: name: name
  age,
  [`${role}_at`]: Date.now(),  // computed key
  greet() {                   // method shorthand
    return `Hi, ${this.name}!`;
  },
  get firstInitial() {        // getter
    return this.name[0];
  },
};

Reading & writing

JS
user.name           // "Ada"  — dot notation
user["age"]         // 36     — bracket notation (works with dynamic keys)
const key = "name";
user[key]           // "Ada"
user.role = "moderator";
delete user.age;
Tip: Default to object literals. For repeated shapes with shared behaviour, jump straight to class — skip the older constructor-function pattern.

Example

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

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

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

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

Exercise

Use shorthand to build { name: name, age: age } from the variables.

const user = { , age };

Test yourself

Q1. The everyday way to make an object is…
Q2. `{ name }` is shorthand for…
Q3. Use a computed key with…

Discussion

Loading…