JavaScript "plain" Object

romeopeter

Romeo Agbor Peter

Posted on June 10, 2021

JavaScript "plain" Object

NOTE:

The term "object" denotes two kinds of objects: the key-value data structure in JavaScript, and the popular but opinionated programming methodology: OOP . This article is about the latter type of object.

Object data type

In JavaScript, [almost] everything is an object. To understand the language in-depth, you first have to know what objects are and how they work.

An object is used to store key-value data. It allows for various data and complex entities to be stored. Entities within an object are known as properties. A property is a "key-value" pair, where the key is the property name and value can be anything

To create an object, the curly braces {...} is used with a list of optional properties. It's possible to initialize an empty object.

// Empty object using "object literal" syntax
let user = {};

// Empty object using "object constructor" syntax
let user = new Object();
Enter fullscreen mode Exit fullscreen mode

When declaring an object, the curly braces {...} are preferred over the "object constructor". This is known as Object literal.

Object Literal

Inside the curly braces, we can put in properties separated by commas. All properties have a property name which is the key followed by a colon, and then the property value which can be anything.

let user = { // The object
    name: "Romeo", // key "name" store value of "Romeo"
    age: 22, // key "age" store value of 22
    work: "Went to work" // key "work" store value of "Went to work"
}
Enter fullscreen mode Exit fullscreen mode

Reading a property that doesn't exist will return an undefined value. This means the property hasn't been declared or defined yet. Property values are accessed using the dot . notation.

alert(user.name) // Romeo
alert(user.height) // undefined
Enter fullscreen mode Exit fullscreen mode

It is possible to add, remove and assign a value to a property. Values are removed or deleted using the delete keyword. Values are assigned using the = operator. If a property value already exists, it will replace it.

// Add a bolean value
user.isChristian = true;

// Delete property
delete user.work; // "work" property is deleted
alert(user.work); // undefined.
Enter fullscreen mode Exit fullscreen mode

Lastly, property names that do not follow valid binding name have to be quoted, in other words, a property name can be multi worded. To access multi worded property names, the square bracket is used [].

Square Brackets

Square brackets are used to access multi worded property names in an object. The dot . does not work for multi-word names.

// Set property using square brackets
user["likes dogs"] = true;

// Access property using dot notation
user.likes dogs; // Syntax Error
Enter fullscreen mode Exit fullscreen mode

user.likes dogs will throw an error because JavaScript reads user.likes first, which is valid, but throws an error when it gets to dogs. This is because when using dot notation, the property name can not contain spaces, numbers and special characters (_ and $ are allowed).

The square brackets should be used for property names containing spaces (multi-word names).

// Get property name
alert(user["likes dogs"]); // true

// Delete property name
delete user["likes dogs"];
Enter fullscreen mode Exit fullscreen mode

Square brackets allow accessing property names using expression. for instance, a variable.

const key = "likes dogs";
alert(user[key]); // true
Enter fullscreen mode Exit fullscreen mode

With the square bracket notation, the properties of an object can be accessed by user input. Such flexibility can not be achieved with the dot notation

const pet = {
    type: "Dog"
    name: "Zeus",
    breed: "Pitbull",
    age: 3
}

let key = prompt("What do you want to know about my pet? ");

// access properties
alert(pet[key]); // "Pitbull" if user enter 'breed'
Enter fullscreen mode Exit fullscreen mode

The square bracket gives more flexibility when accessing object properties, but more often than not you should be using the dot notation because of its simplicity and readability. Only use a square bracket when the need arises.

Object property short-hand

When working on or reading an actual codebase, property names and values are often the same. This is due to accepting values from variables. For example:

function myPet(type, name, breed, age) {
    return {
        type : type,
        name : name,
        breed : breed,
        age : age
    }
}

const pet = myPet("Dog", "Zeus", "Pitbull", 3);

alert(pet.name); // Zeus
Enter fullscreen mode Exit fullscreen mode

In the example above, the object properties have the same values as the variables (function parameters). This is a common use-case but there is shorthand for it.

Instead of having a type:type property of an object, you can just have a type and JavaScript will understand that the single value represents both the property name and property value.

For example:

function myPet(type, name, breed, age) {

    // Property value shorthand
    return { type, name, breed, age };
}

// Normal object and shorthand togethter is valid
const pet = {
    breed, // same breed:breed
    age: 3
};
Enter fullscreen mode Exit fullscreen mode

Property test.

Accessing an object property that is not available or does not exist return an undefined value. unlike other programming languages, JavaScript does not halt the program and throw an error.

You can test if a property exist or not:

const pet = {};

consolg.log(pet.propertDoesNotExist === undefined); // returns "true." property does not exist
Enter fullscreen mode Exit fullscreen mode

JavaScript has a special in operator for testing if properties exist.

let pet = {type: "Dog", breed: "Pitbull"};

if ("type" in pet) console.log(pet.type); // logs "Dog" pet.type exists
if ("age" in pet) console.log(pet.age); // logs "undfined" pet.age doesn't exit
Enter fullscreen mode Exit fullscreen mode

Why the in operator is preferred for testing properties instead of comparing against undefined is because property can exist but store undefined as the value.

For example:

const pet  = {
    type: undefined,
    name: "Zeus"
}

if (pet.type) console.log("true") // type is "undefine" ...no such property

if ("type" in pet) console.log("true") // logs "true" Property exists
Enter fullscreen mode Exit fullscreen mode

The pet.type property above technically exist, but the if (pet.type) test for a true or false condition didn't pass because the property name type is set to "undefined" explicitly.

undefined values should not be explicitly set. you should prefer using null for unknown values.

the key in object condition will always work as long the key exists in the object.

Summary

Let's go over what you've learned so far about JavaScript Object.

An object is a data structure for storing key-value data.

Data stored in an object are called properties, where:

  • Property key or name must be string or symbol (_ and $)
  • Property value can be of any type

To access object properties, use:

  • The dot notation object.property
  • The square bracket notation object["property"]. You can take keys from expression using the square bracket

Additional Object operators:

  • delete operator is used for deleting properties: delete object.property

  • The in operator is a special type of operator for testing object properties: "key" in object

  • To iterate over an object: for (let key in obj) loop. (Reserved for future update)

These are the basics that should be known for anybody starting JavaScript programming. The language has other built-in objects, like the Date, Array, Math and Error object. Understanding how they work isn't much of a brainer when you how the "plain" object works.

💖 💪 🙅 🚩
romeopeter
Romeo Agbor Peter

Posted on June 10, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

JavaScript "plain" Object
javascript JavaScript "plain" Object

June 10, 2021