The language of the web is Javascript. It is a scripting language, meaning that each line is interpreted rather than compiled. This post will go into great detail on what Javascript keys and objects are as well as how to determine whether an object has a key. We’ll go over many techniques for determining whether a key exists in an item.
What in JavaScript are Objects?
Data is stored in the form of “key-value” pairs using hashmaps in C++, and similarly, data is stored in the same manner using Javascript objects. In summary, objects in Javascript are non-primitive data structures that hold an unordered set of key-value pairs.
Objects are collections of properties because properties represent the associations between key and value.
For illustration, we’ve defined an object called “car” below with a number of characteristics.
let car = {
name: "Audi",
model: 2015,
price: 340000
};
For the object “car,” a number of characteristics are defined, including name, model, and price. Here, the keys are indicated by the name, model, and price; the values that correlate to the linked keys are “Audi,” 2015, and 340000.
What JavaScript Keys Are There?
Keys are usually used as names or identifiers to access an object’s properties, as was covered in the preceding section.
Let’s use an illustration. Let’s say we have an object called “student” with multiple properties, such as age, rollnumber, lastName, and firstName.
let student = {
firstName:"Joshua",
lastName:"Benz",
rollnumber:2000104,
age:16
};
How to Check if the Key Exists in an Object?
We are now aware of keys and things. What would happen if we wanted to see if an item contained a key? Using only the prior example, how can we determine whether the key “age” is present in the object “student” or not? Let’s examine this.
There are various methods for determining whether a key is present in an object.
Syntax:
The “in” operator can be used as follows in syntax:
‘key’ in object_name;
“key” in object_name; let’s use an example to better understand it. An object called “employee” has specific key-value pairs (properties). We’ll see if the employee object has a specific key or not. The following code can be used to check using the “in” operator.
//defining an object employee
let employee={
empId:2301,
name: "Joshua",
email:"josh232@gmail.com",
age:32
};
//both the statements below return true
'name' in employee;
'age' in employee;
//below statement returns false
'salary' in employee
true
true
false
The code above checks to see if the name and age keys are present in the object “employee” and returns true if they are. However, it returns false when the key “salary” is not present in the object.