Skip to main content

Javascript: Objects

Basic Syntax

Objects are similar to arrays in the sense that they store data. However Objects use key value pairs and are better suited for many types of data. Here is a sample of a simple object:

var person = {
name: "Nick Coughlin",
hair: "blond",
city: "Eugene"
};

A key difference between objects and arrays, is that items in objects have no order. The data must be retrieved by using the key.

Retrieving Data

//bracket notation
console.log(person["name"]);

//dot notation
console.log(person.name);

So why would anyone ever use the bracket notation when dot notation is so much simpler. Well there are some notable exceptions where dot notation will not work.

// you cannot use dot notation if the property starts with a number
someObject.1anything //invalid
someObjet["1anything"] //valid

// you cannot use dot notation for property names with spaces
someObject.fav restaurant //invalid
someObject["fav restaurant"] //valid

// you cannot lookup a variable with dot notation
var str = "name";
someObject.str //does not look for "name"
someObject[str] //does evaluate str and look for "name"

Updating Object Data

This is very similar to updating array data. For objects you simply access a property and then reassign it.

var dog = {
name: = "lola",
age: = 5,
weight = 40
}

// to update the age
dog["age"] += 1;
// to update weight
dog.weight = 50; //jesus lola, slow it down

Comments

Recent Work

Free desktop AI Chat client, designed for developers and businesses. Unlocks advanced model settings only available in the API. Includes quality of life features like custom syntax highlighting.

Learn More

BidBear

bidbear.io

Bidbear is a report automation tool. It downloads Amazon Seller and Advertising reports, daily, to a private database. It then merges and formats the data into beautiful, on demand, exportable performance reports.

Learn More