What Is The Method To Add A Key/value Pair To A JavaScript Object?

To add a key/value pair to a JavaScript object, you can use either the dot notation or square bracket notation. Here are a few examples:

  1. Using dot notation:
const obj = {};
obj.key = "value";
  1. Using square bracket notation:
const obj = {};
obj["key"] = "value";

You can also use variables as keys:

const key = "name";
const obj = {};
obj[key] = "John";

Or, if you want to add multiple key/value pairs at once, you can use the object literal syntax:

const obj = {
  key1: "value1",
  key2: "value2",

Note: If the key already exists in the object, the value will be overwritten with the new value.

About the Author Rex

I'm a passionate tech blogger with an insatiable love for programming! From my early days tinkering with code, I've delved into web dev, mobile apps, and AI. Sharing insights and tutorials with the world is my joy, connecting me to a global community of like-minded tech enthusiasts. Python holds a special place in my heart, but I embrace all challenges. Constantly learning, I attend tech conferences, contribute to open-source projects, and engage in code review sessions. My ultimate goal is to inspire the next generation of developers and contribute positively to the ever-evolving tech landscape. Let's code together!