Menu Close


JavaScript: object

JavaScript objects are composite variables that contain many values.  We declare an object using var keyword. We can create JavaScript objects and assign initial value using JSON = Java Script Object Notation.



var person = {
    firstName : "John",
    lastName  : "Doe",
    age       : 50,
    eyeColor  : "blue",
    fullName  : function () {
      return this.firstName + " " + this.lastName}

In this example we declare an object person that has several properties and one method. A method is a property of type function. The method name in this example is fullName(). Observe that method fullName() is encolded inside brackets {…} and belong to person object.


Object Members

You can access object properties in two ways:



You access an object method with the following syntax:


Alert: We can assign to a variable a function. Therefore do not forget to use parentheses () for a function call. Otherwise you can assign to a variable the function itself by mistake !


Alternative Methods

There are two alternative methods to create objects.

  • By using constructor: new Object()
  • By using method: Object.create()


JavaScript has predefined objects. One of these is the funamental Object.

The Fundamental Object constructor can be used to create new objects. This is an alternative method to JSON initializer.


// equivalent to o = new Boolean(true);
var o = new Object(true);

// equivalent to o = new Boolean(false);
var o = new Object(Boolean());

Object prototype

Object.create() method can be used to create new object with the specified prototype object and properties.


function Shape() { = 'Shape 1';

function Rectangle() {;

Rectangle.prototype = Object.create(Shape.prototype);
const rect = new Rectangle();

// expected output: "Shape 1"

Function Object

Every JavaScript function is actually a Function object.

var sum = new Function('a', 'b', 'return a + b');
console.log(sum(2, 6));
// expected output: 8

More details about Objects in JavaScript here: