Saturday 22 December 2018

JavaScript: How to check whether object has given property or not?

You can use ‘in’ operator to check whether object has given property or not. ‘in’ operator returns true, if the object has given property, else false.

Syntax
propertyNameOrIndexNumber in objectName

propertyNameOrIndexNumber can be property name or array index.
objectName is the object (or) array name.

HelloWorld.js
var hobbies = ["Football", "cricket", "chess", "Trekking"];

var employee = {
  name : "Krishna",
  age : 29
};

var a = 0 in hobbies; //true
var b = 2 in hobbies; //true
var c = 5 in hobbies; //false

var d = "name" in employee; //true
var e = "age" in employee; //true
var f = "id" in employee //false

console.log("a : " + a);
console.log("b : " + b);
console.log("c : " + c);
console.log("d : " + d);
console.log("e : " + e);
console.log("f : " + f);

Output
a : true
b : true
c : false
d : true
e : true
f : false




Previous                                                 Next                                                 Home

No comments:

Post a Comment