JavaScript For Kids For Dummies
Book image
Explore Book Buy On Amazon

In addition to the basic data types (string, number, and Boolean), operands in JavaScript can also be of the object type. JavaScript objects can have properties (things that describe them) and methods (things that they can do).

Now, you find out how to create your own objects! To create an object, start with the var keyword, just as you do to create any variable, followed by an equal sign (=):

var myObject =

After the equal sign is where things get a little different. When you create an object, you always start with curly braces ({ and }):

var myObject = {};

Inside the curly braces, you can put multiple properties and methods. Each property or method of an object starts with a name (on the left), followed by a colon (:), followed by a value. If an object contains multiple properties or methods, they're separated by commas.

Practice making some objects and looking at their values in JSFiddle:

  1. Go to JSFiddle in your web browser.

    You should now have a blank fiddle, meaning that all four of the panes on the screen (HTML, CSS, JavaScript, and Result) are blank.

  2. Enter the following into the JavaScript pane to create a dreamCar object:

    var dreamCar = {
        make: "Oldsmobile",
        model: "98",
        color: "brown",
        year: 1983,
        bodyStyle: "Luxury Car",
        price: 4500
    }

    Feel free to customize your dream car in any way that you want!

    Notice that, in an object, it's perfectly fine to mix properties with different data types. For example, in the dreamCar object, the make, model, color, and bodyStyle properties are all strings, and the year and price are numbers.

  3. Type the following into the JavaScript pane after the object definition in order to find out the type of the dreamCar object:

    alert("The type of dreamCar is: " + typeof dreamCar);
  4. Click Run.

    An alert appears, showing you that your dreamCar is an object, as shown here.

    Your dream car is an object.
    Your dream car is an object.

About This Article

This article is from the book:

About the book authors:

Chris Minnick and Eva Holland are experienced web developers, tech trainers, and coauthors of Coding with JavaScript For Dummies. Together they founded WatzThis?, a company focused on training and course development.

This article can be found in the category: