To set an object key by variable in JavaScript, you can use either “dot notation” or “square bracket” notation.
Here’s an example using both notations:
const mainObj = {};
const key = 'mainKey';
const value = 'mainValue';
// Using dot notation
mainObj[key] = value;
// Using square bracket notation
mainObj.key2 = 'mainValue2';
console.log(mainObj);
Output
{ mainKey: 'mainValue', key2: 'mainValue2' }
In this code example, we created a new empty object mainObj.
A variable key is assigned the string value ‘mainKey‘, and a variable value is assigned the string value ‘mainValue’.
The key variable is used to set the value of a property on ‘mainObj’ using square bracket notation (mainObj[key] = value), which dynamically sets the object key based on the value of the key.
Another key2 is set using dot notation (mainObj.key2 = ‘mainValue2’), which sets the object key to the literal string ‘key2’.
Finally, the mainObj object is logged into the console.
The dot notation only works if the key name is a valid identifier, which means it must start with a letter, underscore, or dollar sign and may contain letters, digits, underscores, or dollar signs.
You must use square bracket notation if the key name is not a valid identifier. Square bracket notation is also required to use a variable to set the key name dynamically.

Niva Shah is a Software Engineer with over eight years of experience. She has developed a strong foundation in computer science principles and a passion for problem-solving.