Last Updated: September 09, 2019
·
529
· gerardsans

JavaScript - object properties and prototype chain

Sons of JavaScript Collection | this article

As we saw in another protip properties can be created in two different ways. This is by using a literal object notation or by using a function constructor.

var person = {};
person.name = "John";
person.surname = "Smith";

function Person(name, surname) {
  this.name = name;
  this.surname = surname;
}
var person = new Person("John", "Smith");

Checking object property existence

console.log("name" in person); // true
console.log(person.hasOwnProperty("name")); //true

Using dictionary notation

console.log(person["name"]); // John

Using for..in loop

for (var key in person) {
  console.log(person[key]);
}
// John Smith

If you are using prototypes in order to avoid displaying the properties higher on the prototype chain you can filter those properties by using object.hasOwnProperty(property_name). Note also that if you declare anonymous functions as variables you will have to filter those too with (typeof(person[key]) != "function"). Definition would look like var myFn = function(){};

for (var key in person) {
  if (person.hasOwnProperty(key)) //filter prototype properties
    console.log(person[key]);
}
// John Smith

Sons of JavaScript Collection | this article