WebMasterCampus
WEB DEVELOPER Resources

Javascript Check if a Key Exists in an Object

Learn how to check in Javascript if a Key Exists in an Object


Javascript Check if a Key Exists in an Object

When we are working with objects in Javascript, it’s needed to verify the property we are trying to access in available in objects or not. We just need to verify to avoid any critical error.

The best way to identify an object property exist or not is using in keyword.

The following code is define a car object. Using in keyword we are finding that body and speed properties exist or not. If exist then show the value of these or if not than display the message.

Example


    var car = {color:'white', body:"salon"}

    if ("color" in car){
        console.log(car.color);
    }

    if ("body" in car){
        console.log(car.body);
    }

    if ("speed" in car){
        console.log(car.speed);
    }
    else{
        console.log("Speed is not available")
    }

Learn more about javascript in operator

Created with love and passion.