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.
This approach checks only entries that are directly inside the object.
xxxxxxxxxx
1
var student = {
2
name: 'John',
3
age: 25,
4
print: function() { /* nothing here... */ }
5
};
6
7
console.log(student.hasOwnProperty('age')); // true
8
console.log(student.hasOwnProperty('todos')); // false
9
console.log(student.hasOwnProperty('print')); // true
This approach checks elements that are inside the prototype chain.
xxxxxxxxxx
1
var student = {
2
name: 'John',
3
age: 25,
4
print: function() { /* nothing here... */ }
5
};
6
7
console.log('age' in student); // true
8
console.log('todos' in student); // false
9
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.
xxxxxxxxxx
1
// some code...
2
3
Object.prototype.role = 'admin';
4
5
// some code...
6
7
var student = {
8
name: 'John',
9
age: 25
10
};
11
12
console.log('role' in student); // true
xxxxxxxxxx
1
// some code...
2
3
Object.prototype.role = null;
4
5
// some code...
6
7
var student = {
8
name: 'John',
9
age: 25,
10
experience: '',
11
family: null // undefined
12
};
13
14
// for existing null valued inherted property:
15
console.log( student.role ? true : false); // false
16
console.log( student['role'] ? true : false); // false
17
console.log(!! student.role ); // false
18
console.log(!!student['role'] ); // false
19
20
// for existing property:
21
console.log( student.name ? true : false); // true
22
console.log( student['name'] ? true : false); // true
23
console.log(!! student.name ); // true
24
console.log(!!student['name'] ); // true
25
26
// for existing property:
27
console.log( student.experience ? true : false); // false
28
console.log( student['experience'] ? true : false); // false
29
console.log(!! student.experience ); // false
30
console.log(!!student['experience'] ); // false
31
32
// for existing null valued property:
33
console.log( student.family ? true : false); // false
34
console.log( student['family'] ? true : false); // false
35
console.log(!! student.family ); // false
36
console.log(!!student['family'] ); // false
37
38
// for not existing property:
39
console.log( student.todos ? true : false); // false
40
console.log( student['todos'] ? true : false); // false
41
console.log(!! student.todos ); // false
42
console.log(!!student['todos'] ); // false