๐Ÿงฑ JavaScript Objects = Key-Value Pairs

Youโ€™ve probably used this:

myObject.name = "Ken";

Thatโ€™s dot notation โ€” the simplest way to access object properties. But hereโ€™s the thing:

โŒ It only works for valid identifiers (letters, numbers, _, $). โŒ It canโ€™t handle spaces, emojis, or special characters.


๐Ÿคฏ What Happens with Weird Property Names?

Say you try this:

myObject.special property โ˜บ = 'Oops!';

Youโ€™ll get a syntax error. Why? That property name has a space and an emoji.


โœ… Use Bracket Notation Instead

Hereโ€™s the fix:

myObject['special property โ˜บ'] = 'It works!';
console.log(myObject['special property โ˜บ']); // Output: 'It works!'

Bracket notation accepts any string, making it perfect for:

  • User-generated property names
  • Property names with emojis, spaces, punctuation, etc.

๐Ÿ”ข What About Numbers as Keys?

You can do:

myObject[123] = 'hi!';

JavaScript converts the number 123 to the string '123', so this works:

console.log(myObject['123']); // hi!
console.log(myObject[123]);   // hi!

You can even use expressions:

myObject['12' + '3'];   // hi!
myObject[120 + 3];      // hi!
myObject[123.0];        // hi!

โš ๏ธ Avoid leading zeros in number keys:

myObject[0123]; // Might behave strangely (octal!)

๐Ÿง  Key Takeaways

  1. Dot Notation โ†’ For normal names like name, age, user_1.
  2. Bracket Notation โ†’ For:

    • Special characters (['hello world!'])
    • Emojis (['๐Ÿ’ป'])
    • All-digit names ([123])
    • Dynamic expressions (['key' + 1])

โœจ Final Tip

Use dot notation for clean, predictable keys. Use bracket notation when things get fancy, weird, or dynamic.


Here are 3 review questions you can add at the end of your post:


๐Ÿ“ Review Questions

  1. Why canโ€™t you use dot notation to access a property like myObject["user name"]? (Hint: Think about valid identifiers.)

  2. What will the following code output?

    const obj = {};
    obj[456] = 'Hello!';
    console.log(obj['456']);
    

    (Explain why.)

  3. When should you choose bracket notation over dot notation in JavaScript? (List at least two cases.)


<
Previous Post
๐Ÿง  Debugging Made Simple with console.table
>
Next Post
JavaScript Objects Simplified: A Summary of MDN Web Docs