Last edited 2 years ago
by Horst Schreiber

Object-oriented Programming with JavaScript

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([0] + ' ' +[1] +
    ' is ' + this.age + ' years old. He likes ' +
    this.interests[0] + ' and ' + this.interests[1] + '.');
  greeting: function() {
    alert('Hi! I\'m ' +[0] + '.');

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

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:

No categories assignedEdit