javascript array contains key code example

Example 1: javascript does key exist

var person={"name":"Billy","age":20}
person.hasOwnProperty("name"); // true
person.hasOwnProperty("sex"); // false

Example 2: javascript hashtable contains key

if (obj.hasOwnProperty("key1")) {
  ...
}

Example 3: javascript array contains

var colors = ["red", "blue", "green"];
var hasRed = colors.includes("red"); //true
var hasYellow = colors.includes("yellow"); //false

Example 4: javascript includes

const pets = ['cat', 'dog', 'bat'];

console.log(pets.includes('cat'));
// output: true

Example 5: javascript list include

const array1 = [1, 2, 3];

console.log(array1.includes(2));
// expected output: true

const pets = ['cat', 'dog', 'bat'];

console.log(pets.includes('cat'));
// expected output: true

console.log(pets.includes('at'));
// expected output: false

Example 6: check if a key exists in an object javascript

"key" in obj // true, regardless of the actual value

Tags: