Hello World Master

Tutorials, articles and quizzes on Software Development

Javascript > Articles

Objects in Javascript

This article is associated with the following course
Introduction to Javascript

We can create Objects to represent a collection of data in Javascript. Note that this is different from Arrays, which store a list of data in a specific order.

Data in objects have their own names and values. Let’s do an example where we want to create a duck and define different information about that duck.

var duck = {
  name: "Sylvester",
  feather_color: "white",
}

Here we’re saying that our duck’s name is Sylvester and that the duck’s feathers are white.

We can print our different attributes to the screen like this

console.log(duck.name);

Which will print out “Sylvester” and

console.log(duck.feather_color);

Which will print out “white”

We can also include functions as values to our object. Let’s say we want to call a function that makes the sound a duck normally makes. We can add the a key named call_sound with its value be printing to the console the sound a duck makes

var duck = {
  name: "Sylvester",
  feather_color: "white",
  call_sound: function() {
    console.log("Quack");
  }
}

Now we can have our duck object call the call_sound function whenever we want

var duck = {
  name: "Sylvester",
  feather_color: "white",
  call_sound: function() {
    console.log("Quack");
  }
}

Now we can call our function

duck.call_sound();

Which will print “Quack” to the screen.

What if you want one of the attributes in our object? Lets change our Ducks name to Mittens

duck.name = "Mittens"

We could also use bracket notation to update our attribute

duck["name"] = "Mittens";