javascript optional add object key

javascript optional add object key

In JavaScript, you can add optional object keys to a given object literal. This is useful when you want to provide an object with optional parameters. For example, you may want to provide an optional value to a given object, and check if that value exists before attempting to access it.


const user = {
    name: "Raju",
    age: 25
};

// Set the optional key
user.isAdmin = true;

// Check if the optional key exists
if (user.isAdmin) {
    console.log("Raju is an admin");
}

In the above example, we have created an object with two required keys, and then added an optional key. We can then check if the optional key exists before attempting to access it. This is a useful pattern when dealing with optional parameters.

You can also use the Object.assign() method to add optional keys to an existing object. For example:


const user = {
    name: "Raju",
    age: 25
};

// Add optional keys to the user object
Object.assign(user, {
    isAdmin: true,
    email: "[email protected]"
});

// Check if the optional keys exist
if (user.isAdmin) {
    console.log("Raju is an admin");
}

if (user.email) {
    console.log("Raju's email is " + user.email);
}

In the above example, we have used the Object.assign() method to add two optional keys to our user object. We can then check if the keys exist before attempting to access them.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe