Languages
[Edit]
EN

JavaScript - how to check if object has property or function?

14 points
Created by:
JustMike
29790

In JavaScript it is possible to check if object has property or method (function) in following ways.

1. hasOwnProperty method example

This approach checks only entries that are directly inside 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 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

 

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join