Last edited 2 years ago
by Horst Schreiber

Object-oriented Programming with JavaScript

The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

Object basics

As with many things in JavaScript, creating an object often begins with defining and initializing a variable. Try entering the following line below the JavaScript code that's already in your file, then saving and refreshing:

const person = {};

Now open your browser's JavaScript console, enter person into it, and press Enter/Return. You should get a result similar to one of the below lines:

[object Object]

Congratulations, you've just created your first object. Job done! But this is an empty object, so we can't really do much with it. Let's update the JavaScript object in our file to look like this:

var person = {
  name: ['Bob', 'Smith'],
  age: 32,
  gender: 'male',
  interests: ['music', 'skiing'],
  bio: function() {
    alert(this.name[0] + ' ' + this.name[1] +
    ' is ' + this.age + ' years old. He likes ' +
    this.interests[0] + ' and ' + this.interests[1] + '.');
  },
  greeting: function() {
    alert('Hi! I\'m ' + this.name[0] + '.');
  }
};

After saving and refreshing, try entering some of the following into the JavaScript console on your browser devtools:

person.name
person.name[0]
person.age
person.interests[1]
person.bio()
person.greeting()

You have now got some data and functionality inside your object, and are now able to access them with some nice simple syntax!


Source of this example: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Basics

No categories assignedEdit

Discussions