How7oHow7o
  • Home
  • Tools
    • All Tools
    • Image Tools
    • Text & String Tools
    • Video Tools
    • Developer Tools
    • PDF Tools
    • Calculators & More
  • Prank Screens
  • Learn
  • Blog
  • Contact
Reading: How to Use a Variable as an Object Key in JavaScript
Share
Notification Show More
Font ResizerAa
How7oHow7o
Font ResizerAa
  • OS
Search
  • Home
  • Tools
    • All Tools
    • Image Tools
    • Text & String Tools
    • Video Tools
    • Developer Tools
    • PDF Tools
    • Calculators & More
  • Prank Screens
  • Learn
  • Blog
  • Contact
Follow US
© 2024–2026 How7o. All rights reserved.
How7o > Free Laravel, PHP, WordPress & Server Tutorials > Web Development > How to Use a Variable as an Object Key in JavaScript
Web Development

How to Use a Variable as an Object Key in JavaScript

how7o
By how7o
Last updated: May 23, 2026
5 Min Read
Use a JavaScript variable as an object key
SHARE

To use a variable as an object key in JavaScript, wrap the variable in square brackets inside the object literal: { [variable]: value }. This is ES6’s computed property names syntax — the expression in brackets is evaluated and the result becomes the key.

Contents
  • The problem
  • The fix — computed property names
  • Pre-ES6 alternative — build and assign
  • Computed keys with expressions
  • Multiple computed keys at once
  • Combine with spread / rest
  • Frequently asked questions
  • Related guides
  • References

Last verified: 2026-05-17 on modern browsers and Node 20+. Originally published 2022-09-15, rewritten and updated 2026-05-17.

The problem

function setStorageValue(objectKey, objectValue) {
    // BUG: the literal string "objectKey" becomes the key,
    // not the value of the variable
    chrome.storage.local.set({ objectKey: JSON.stringify(objectValue || {}) });
}

In an object literal, a bare identifier is treated as a string. { objectKey: x } always produces { "objectKey": x }, regardless of what’s stored in the objectKey variable.

The fix — computed property names

function setStorageValue(objectKey, objectValue) {
    chrome.storage.local.set({
        [objectKey]: JSON.stringify(objectValue || {})
    });
}

The [objectKey] wrapper says “evaluate this and use the result as the key.” Calling setStorageValue('userDetails', { ... }) now produces { userDetails: '...' } as expected.

JS dynamic object keys — computed property names, bracket assignment, expressions in keys

Pre-ES6 alternative — build and assign

function setStorageValue(objectKey, objectValue) {
    const data = {};
    data[objectKey] = JSON.stringify(objectValue || {});
    chrome.storage.local.set(data);
}

Build an empty object, assign the property with bracket notation, then pass the object. Functionally identical to the computed-property form, just two lines longer.

Computed keys with expressions

const id     = 42;
const prefix = 'user';

const obj = {
    [`${prefix}_${id}`]: { name: 'Alice' },
    ['count_' + id]:     1,
    [getKey()]:          'computed at call time',
};

// obj is { user_42: {...}, count_42: 1, ...whatever getKey() returned }

Any expression that returns a string (or Symbol) can go in the brackets — template literals, concatenations, function calls. Useful for building objects whose shape depends on runtime state.

Multiple computed keys at once

function makeUser(id, name, role) {
    return {
        [`user_${id}_name`]: name,
        [`user_${id}_role`]: role,
    };
}

makeUser(42, 'Alice', 'admin');
// { user_42_name: 'Alice', user_42_role: 'admin' }

Combine with spread / rest

function updateField(obj, fieldName, newValue) {
    // Non-mutating: return a new object with one field changed
    return { ...obj, [fieldName]: newValue };
}

const user        = { name: 'Alice', role: 'user' };
const promoted    = updateField(user, 'role', 'admin');
// promoted: { name: 'Alice', role: 'admin' }
// user:     unchanged

Common React/state-management pattern: spread the existing object, then override one or more keys with computed names. The original object stays untouched (handy for immutable updates).

Frequently asked questions

Why does { key: value } use key as a literal string instead of the variable’s value?

JavaScript treats bare identifiers in object literals as string keys by convention — { key: 1 } is shorthand for { 'key': 1 }. To say “use the variable’s value as the key,” wrap the variable in square brackets: { [key]: 1 }. That’s the ES6 computed-property syntax.

Can I compute keys from expressions, not just variables?

Yes — the brackets can contain any expression: { ['user_' + id]: data }, { [`${prefix}-${id}`]: data }, { [getKey()]: data }. The expression is evaluated and its result (coerced to string or symbol) becomes the key.

How is this different from obj[key] = value?

obj[key] = value mutates an existing object — adds or overwrites a property. The computed-property syntax { [key]: value } is used inside an object literal to construct a new object with that key. Both produce the same shape; pick by whether you’re building or modifying.

Are object keys always strings?

Almost — keys are strings or Symbols. Numbers, booleans, and other primitives are coerced to strings when used as keys (obj[1] and obj['1'] reach the same property). Symbols are the exception: they remain Symbols and aren’t enumerable in for...in loops or Object.keys(). Use Symbols when you want “private” properties that won’t show up in standard iteration.

Related guides

  • How to Get N Elements from an Array in JavaScript
  • How to Get the First Character of a String in JavaScript
  • How to Check if a JavaScript String Is a Valid URL

References

MDN computed property names: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#computed_property_names.

TAGGED:JavaScriptobjects

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
[mc4wp_form]
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Share This Article
Facebook Copy Link Print
Previous Article Select the last child element with jQuery How to Select the Last Child Element in jQuery
Next Article Enforce a minimum phone-number length in WooCommerce checkout How to Set a Minimum Length for Phone Numbers in WooCommerce
Leave a Comment

Leave a Reply Cancel reply

You must be logged in to post a comment.

You Might Also Like

WordPress admin notice — four notice types shown at the top of the admin area
Web Development

How to Show Custom Notifications in the WordPress Dashboard

6 Min Read
Laravel database transactions explained
Web Development

Laravel Database Transactions Explained (DB::transaction vs beginTransaction)

6 Min Read
Laravel unknown column CONCAT fix — DB::raw and selectRaw bypass identifier escaping
Web Development

How to Fix “Unknown column ‘CONCAT'” in Laravel

8 Min Read
WordPress check if user is logged in with is_user_logged_in()
Web Development

How to Check If a User Is Logged In in WordPress

7 Min Read
How7oHow7o

Free browser-based tools, prank screens, and step-by-step tech tutorials. No signup, nothing uploaded.

  • Private by design — your files never leave your device
  • Instant — no signup, no install, no waiting
  • Always free — no trials, no watermarks, no paywalls

Tools

  • PDF Editor
  • Image Upscaler
  • JPEG Compressor
  • Password Generator
  • QR Code Generator
  • Video Trimmer
  • See all tools →

Pranks

  • Cracked Screen Prank
  • Fake Blue Screen (BSOD)
  • Fake Disk Format
  • Fake Low Battery
  • Fake Virus Scan
  • Fake Windows 10 Update
  • See all prank screens →

Company

  • About Us
  • Blog
  • Contact
  • Privacy Policy
  • Terms of Service
  • Sitemap
© 2024–2026 How7o. All rights reserved.
Welcome Back!

Sign in to your account

Username or Email Address
Password

Lost your password?