EN
JavaScript - check if object has property or function
14
points
In JavaScript, it is possible to check if the object has a property or method (function) in the following ways.
1. hasOwnProperty
method example
This approach checks only entries that are directly inside the object.
// ONLINE-RUNNER:browser;
var student = {
name: 'John',
age: 25,
print: function() { /* nothing here... */ }
};
console.log(student.hasOwnProperty('age')); // true
console.log(student.hasOwnProperty('todos')); // false
console.log(student.hasOwnProperty('print')); // true
2. in
keyword example
This approach checks elements that are inside the prototype chain.
// ONLINE-RUNNER:browser;
var student = {
name: 'John',
age: 25,
print: function() { /* nothing here... */ }
};
console.log('age' in student); // true
console.log('todos' in student); // false
console.log('print' in student); // true
Note: be careful during using this approach because of inherited properties and methods e.g. true value for 'toString' in student expression.
3. Most common mistakes
3.1. in
keyword for entry in prototype chain example
// ONLINE-RUNNER:browser;
// some code...
Object.prototype.role = 'admin';
// some code...
var student = {
name: 'John',
age: 25
};
console.log('role' in student); // true
3.2. if
instruction for undefined
or null
valued entries example
// ONLINE-RUNNER:browser;
// some code...
Object.prototype.role = null;
// some code...
var student = {
name: 'John',
age: 25,
experience: '',
family: null // undefined
};
// for existing null valued inherted property:
console.log( student.role ? true : false); // false
console.log( student['role'] ? true : false); // false
console.log(!! student.role ); // false
console.log(!!student['role'] ); // false
// for existing property:
console.log( student.name ? true : false); // true
console.log( student['name'] ? true : false); // true
console.log(!! student.name ); // true
console.log(!!student['name'] ); // true
// for existing property:
console.log( student.experience ? true : false); // false
console.log( student['experience'] ? true : false); // false
console.log(!! student.experience ); // false
console.log(!!student['experience'] ); // false
// for existing null valued property:
console.log( student.family ? true : false); // false
console.log( student['family'] ? true : false); // false
console.log(!! student.family ); // false
console.log(!!student['family'] ); // false
// for not existing property:
console.log( student.todos ? true : false); // false
console.log( student['todos'] ? true : false); // false
console.log(!! student.todos ); // false
console.log(!!student['todos'] ); // false