Javascript does not throw an exception when reading or writing a property that does not exist. When reading, it just returns undefined . When writing it, it simply creates a property.
You can create your own function that checks if the property exists and throws an exception if it is not (but you will have to call this function every time), but JS does not make an exception to this, it belongs as you ask.
If you want to check if a key exists for an object in javascript, you can use this construction with the in operator:
var obj = {}; var key = "test"; if (key in obj) {
If you try to read a key that does not exist, you will get undefined as the value.
var obj = {}; var value = obj.test; alert(value === undefined);
The in operator knows better if a test key exists for undefined , since undefined is the legal value for a key that exists.
In many cases, when you control values ββthat have keys and the present key will never be falsey, you can also just check if the key has a true value:
var obj = {}; var obj.test = "hello"; if (obj.test) {
If you want to make sure that the object itself has a property, and not some prototype from which it is inherited, you can do this:
var obj = {}; var obj.test = "hello"; if (obj.hasOwnProperty(test)) {
jfriend00
source share