Объекты
Как мы знаем из главы Типы данных, в JavaScript существует 8 типов данных. Семь из них называются «примитивными», так как содержат только одно значение (будь то строка, число или что-то другое).
Объекты же используются для хранения коллекций различных значений и более сложных сущностей. В JavaScript объекты используются очень часто, это одна из основ языка. Поэтому мы должны понять их, прежде чем углубляться куда-либо ещё.
Объект может быть создан с помощью фигурных скобок <…>с необязательным списком свойств. Свойство – это пара «ключ: значение», где ключ – это строка (также называемая «именем свойства»), а значение может быть чем угодно.
Мы можем представить объект в виде ящика с подписанными папками. Каждый элемент данных хранится в своей папке, на которой написан ключ. По ключу папку легко найти, удалить или добавить в неё что-либо.
Пустой объект («пустой ящик») можно создать, используя один из двух вариантов синтаксиса:
Обычно используют вариант с фигурными скобками <. >. Такое объявление называют литералом объекта или литеральной нотацией.
Литералы и свойства
При использовании литерального синтаксиса <. >мы сразу можем поместить в объект несколько свойств в виде пар «ключ: значение»:
У каждого свойства есть ключ (также называемый «имя» или «идентификатор»). После имени свойства следует двоеточие ":" , и затем указывается значение свойства. Если в объекте несколько свойств, то они перечисляются через запятую.
В объекте user сейчас находятся два свойства:
- Первое свойство с именем "name" и значением "John" .
- Второе свойство с именем "age" и значением 30 .
Можно сказать, что наш объект user – это ящик с двумя папками, подписанными «name» и «age».
Мы можем в любой момент добавить в него новые папки, удалить папки или прочитать содержимое любой папки.
Для обращения к свойствам используется запись «через точку»:
Значение может быть любого типа. Давайте добавим свойство с логическим значением:
Для удаления свойства мы можем использовать оператор delete :
Имя свойства может состоять из нескольких слов, но тогда оно должно быть заключено в кавычки:
Последнее свойство объекта может заканчиваться запятой:
Это называется «висячая запятая». Такой подход упрощает добавление, удаление и перемещение свойств, так как все строки объекта становятся одинаковыми.
Объект, объявленный через const , может быть изменён.
Может показаться, что строка (*) должна вызвать ошибку, но нет, здесь всё в порядке. Дело в том, что объявление const защищает от изменений только саму переменную user , а не её содержимое.
Определение const выдаст ошибку только если мы присвоим переменной другое значение: user=. .
Есть ещё один способ сделать константами свойства объекта, который мы рассмотрим в главе Флаги и дескрипторы свойств.
Квадратные скобки
Для свойств, имена которых состоят из нескольких слов, доступ к значению «через точку» не работает:
JavaScript видит, что мы обращаемся к свойству user.likes , а затем идёт непонятное слово birds . В итоге синтаксическая ошибка.
Точка требует, чтобы ключ был именован по правилам именования переменных. То есть не имел пробелов, не начинался с цифры и не содержал специальные символы, кроме $ и _ .
Для таких случаев существует альтернативный способ доступа к свойствам через квадратные скобки. Такой способ сработает с любым именем свойства:
Сейчас всё в порядке. Обратите внимание, что строка в квадратных скобках заключена в кавычки (подойдёт любой тип кавычек).
Квадратные скобки также позволяют обратиться к свойству, имя которого может быть результатом выражения. Например, имя свойства может храниться в переменной:
Здесь переменная key может быть вычислена во время выполнения кода или зависеть от пользовательского ввода. После этого мы используем её для доступа к свойству. Это даёт нам большую гибкость.
Определить, существует ли ключ в объекте JavaScript
В этом посте мы обсудим, как определить, существует ли ключ в объекте JavaScript.
Первое решение, которое приходит на ум, — использовать оператор строгого равенства для сравнения значения данного ключа с undefined .
Это сработало бы во всех случаях, кроме случаев, когда ключ существует, но его значение на самом деле undefined . Это поведение продемонстрировано ниже:
В этом посте представлен обзор некоторых доступных альтернатив для определения того, правильно ли существует ключ в объекте.
1. Использование hasOwnProperty() метод
The hasOwnProperty() метод возвращает true, если объект содержит указанное свойство, которое является прямым свойством этого объекта, а не унаследованным. В следующем примере проверяется, является ли объект obj имеет свойство с именем two :
JavaScript Key in Object – How to Check if an Object has a Key in JS
Joel Olawanle

Objects in JavaScript are non-primitive data types that hold an unordered collection of key-value pairs.

As you can see in the image above, the key is the property, and each object value must have a key.
When interacting with objects, situations might arise that require you to check if a particular key exists. It is important to note that if you know a key exists that automatically means that a value exists. This value could be anything – even empty, null, or undefined.
In this article, we will learn the various methods to check if an object’s key exists in JavaScript.
Here’s an Interactive Scrim about How to Check if an Object Has a Key in JavaScript
In case you are in a rush, here are the two standard methods we can use to check:
How to Check if an Object Has a key in JavaScript with the in Operator
You can use the JavaScript in operator to check if a specified property/key exists in an object. It has a straightforward syntax and returns true if the specified property/key exists in the specified object or its prototype chain.
The syntax when using the in operator is:
Suppose we have an object which contains a user’s details:
We can check if a key exists with the in operator as seen below:
Note: The value before the in keyword should be of type string or symbol .
How to Check if an Object Has a key in JavaScript with the hasOwnProperty() Method
You can use the JavaScript hasOwnProperty() method to check if a specified object has the given property as its property. T
his method is pretty similar to the in operator. It takes in a string and will return true if the key exists in the object and false otherwise.
The syntax when using the hasOwnProperty() method is:
Suppose we have an object which contains a user’s details:
We can check if a key exists with the in operator as seen below:
Note: The value you pass into the hasOwnProperty() method should be of type string or symbol .
Since we now know that these methods exist, we can now use a condition to check and perform whatever operation we wish to perform:
Wrapping Up
In this article, we have learned how to check if an object has a key using the two standard methods. The difference between the two methods is that Object.hasOwnProperty() looks for a key in an object alone while the in operator looks for the key in the object and its prototype chain.
There are other methods you can use, but at some point they might get too elaborate and aren’t that easy to understand. They also might fail when tested against certain conditions.
For example, we could use the optional chaining, so if a specified key does not exist, it will return undefined :
So we could create a condition that, when it’s not equal to undefined , it means the key exists:
As we said earlier, these methods fail when tested against some uncommon conditions. For example, in a situation when a particular key is set to «undefined», as seen below, the condition fails:
Another example when it works but gets elaborate is when we use the Object.keys() method alongside the some() method. This works but isn’t really easy to understand:
In the code above, we retired all the keys as an array and then applied the some() method to test whether at least one element in the array passed the test. If it passes, it returns true , else false .
How to Check if Key Exists in JavaScript Object/Array

An object in JavaScript is an unordered collection of key-value pairs ( key: value ). Each key is known as a property, and is a string representing a property name. If a non-string is given as the key, it's stringified representation will be used. A property's value can be of any data type that fits the property conceptually — a string, a number, an array, or even a function.
An array, on the other hand, is a sorted set of values. Each value is referred to as an element, which is identified by a numerical index. An array can include values of almost any type. For example, it can store items like integers, strings, booleans, functions, etc. JavaScript arrays are also not restricted to a single type, meaning a given array can contain multiple different types within it.
When working in JavaScript, you might at a particular point in time need to determine if a key exists in a given object or array.
In this article, we will see the various methods which we could use to check if a particular key exists in a JavaScript object/array.
Using the in Operator
The in operator in JavaScript is used to determine if a certain property exists in an object or its inherited properties (also known as its prototype chain). If the provided property exists, the in operator returns true.
Checking an Object
Checking an Array
Since we demonstrated that the JavaScript in operator can be used with objects, you may be asking if it can also be used with arrays. In JavaScript, everything is an instance of the Object type (except for primitives), so arrays also support the in operator.
Let's confirm if it's an instance of the Object type using the instanceof operator:
Now, back to using the in operator:
This will also return true for method properties on an array type, of which the number array is an instance.
Using the hasOwnProperty() Method
In JavaScript, the hasOwnProperty() function is used to determine whether the object has the supplied property as its own property. This is important for determining if the attribute was inherited by the object rather than being its own.
Checking an Object
Checking an Array
You might begin to wonder if this would work for arrays. As we established earlier, an array is actually a prototype (instance) of the Object type, therefore it also has this method available to it.
Using the Object.key() Method
The static method Object.key generates and returns an array whose components are strings of the names (keys) of an object's properties. This may be used to loop through the object's keys, which we can then use to verify if any match a certain key in the object.
Using the some() Method
some() is a JavaScript method that tests a callback function on all the elements of the calling array and returns true if the callback function returns true for any of them.
Using some() for Objects
We could also customize this into a reusable function:
Using some() for an Array
Again, just like with the object, we could also make use of a similar customized reusable function to check a value's existence in an array:
Using the indexOf() Method
JavaScript's indexOf() method will return the index of the first instance of an element in the array. If the element does not exist then, -1 is returned.
Using indexOf() for an Object
The Object type in JavaScript does not actually support the indexOf method, since its properties/keys do not inherently have indexed positions in the object. Instead, we can get the object's keys as an array and then check the existence of a key using the indexOf method:
Free eBook: Git Essentials
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
Keep in mind that JavaScript objects do not always preserve key order, so the index returned may not be as meaningful as in arrays. In this case, the index should primarily be used to determine just the existence of a key.
Here is an example of using this in a utility function:
Using indexOf() for an Array
As we saw in the previous example, arrays do support the indexOf method, unlike objects. To use it, pass the value of the item you're looking for to indexOf , which will then return the position of that value if it exists in the array:
Conclusion
In this article, we have seen all of the possible ways in which we could check if a key or item exists in a JavaScript object/array. We show how to make use of the in operator, hasOwnProperty() method, and some method. We also saw how JS objects and arrays in similar in that arrays inherit from objects, and thus contain many of the same methods.