Back to course sections
    Mark As Completed Discussion

    In this lesson, we will learn about a new type of data structure called objects, with a focus on the following key points,

    1. What are objects and how are they used?
    2. Working with objects and key-value pairs in JavaScript.

    For the Python version of this lesson, please click here.

    Previously, we've studied arrays and other data types that can only store a single value of an element. Sometimes, you may encounter situations during your program when you need to refer to your data in pairs. In that case, objects are used. They are a data structure in JavaScript that used a technique called hashing to store the data in key-value pairs.

    Suppose you want to store information of students in a class, along with information identifiers. In this case, using variables or arrays is not recommended as you will have to create too many variables, and separating identifiers and their values from the array will be difficult. You will need something that stores and categorizes your data according to the identifiers. Objects are excellent for this purpose as they allow programmers to categorize data into key-value pairs, that is, you can specify multiple values under a single identifier. This makes the problem of storing student information easier!

    Objects

    Objects allow for the storage of data in the form of key-value pairs. Keys (or names) are unique elements that are assigned a value. You can consider keys as indices or properties of an object. That is, the values stored in an object can be accessed using a key. Moreover, unlike arrays, objects can store a collection of elements (such as using an array) as a value for a single key.

    Let's look at few examples of objects.

    JAVASCRIPT
    1var student = {"ID": "01", "name":"Patrick", "age":18, "major":"Biology"}

    Visualizing this example, we see that the data is stored somewhat like the illustration below.

    Objects

    If we want to store multiple values for a single key, all the values are grouped in an array and assigned to the corresponding key.

    JAVASCRIPT
    1var students = {"ID": ["01", "02", "03", "04"], "name":["Patrick", "William", "Elizabeth", "John"], "age":[18, 19, 19, 20], "major":["Biology", "CS", "Literature", "Mathematics"]}

    Storing multiple values within a single key stores the data in the form of tables within the program.

    Objects

    To access values in an object, keys are used as indices (using bracket notation) or through key name (as a property using dot notation).

    JAVASCRIPT
    1var student = {"ID": "01", "name":"Patrick", "age":18, "major":"Biology"}
    2
    3console.log(student["name"])
    4console.log(student.age)

    Properties of Dictionaries

    • Objects cannot have duplicate keys. That is, two keys of the same name in the same object will generate an error.
    • Values assigned to keys in an object can be of any data type (as shown in the examples in the previous section).
    • JavaScript only allows strings to be the keys in an object. No other data type is allowed.

    Let's test your knowledge. Is this statement true or false?

    An object can have two same keys or two same values.

    Press true if you believe the statement is correct, or false otherwise.

    Try this exercise. Click the correct answer from the options.

    What will be the outcome of the following code block on execution?

    JAVASCRIPT
    1var example_obj = {"a": 1, "b":2, "c":3, "d":4}
    2console.log(example_dict[0])

    Click the option that best answers the question.

    • "1"
    • "undefined"
    • "b"
    • "An error will occur"

    Object Methods and Operations

    Similar to arrays and strings in JavaScript, dictionaries also have built-in functions and properties for insertion, deletion, updating elements, and other operations that need to be performed on objects.

    To get the total length of the dictionary, there is no method available in JavaScript. There are several methods to obtain this, one of which is to use the method Object.keys() which returns an array of keys in an object, and access its length.

    JAVASCRIPT
    1var student = {"ID": "01", "name":"Patrick", "age":18, "major":"Biology"}
    2var length = Object.keys(student).length
    3
    4console.log(length)

    To add new items in an object, there is no built-in method. Rather, they are directly assigned by specifying the key name and its value in bracket or dot notation as shown in the code block below.

    JAVASCRIPT
    1var student = {"ID": "01", "name":"Patrick", "age":18, "major":"Biology"}
    2
    3student["section"] = "A"
    4student.email = "patrick123@xyz.com"
    5
    6console.log(student) //prints the updated dictionary

    Another important operation in objects is the removal of items. This is performed by using the delete keyword by specifying the key name of the key-value pair that needs to be removed using bracket or dot notation.

    JAVASCRIPT
    1student = {"ID": "01", "name":"Patrick", "age":18, "major":"Biology"}
    2
    3delete student["age"]
    4delete student.major
    5
    6console.log(student) //prints the updated dictionary

    Some more commonly used object methods are,

    • To get all the properties or key-value pairs from an object, Object.entries(<object-name>) is used. It returns the key-value pairs in the form of a nested array.
    • To get all the keys in an object, Object.keys(<object-name>) is used. This returns all the keys in the form of an array.
    • To get all the values that exist in an object, Object.values(<object-name>) is used. All the values are returned in the form of an array.

    Try this exercise. Fill in the missing part by typing it in.

    What is the output of following code?

    JAVASCRIPT
    1var obj = {"Peter": 12, "Jane": 11}
    2var pairs = Object.entries(obj)
    3console.log(pairs[1])

    Write the missing line below.

    Summary

    In this lesson, we learned about a new method to store data during the execution of a program. Variables, lists, and objects are all different methods of storing data. Depending on the situation, these different data storage elements (or data structures) are used to store and manipulate data.

    One Pager Cheat Sheet

    • We will learn about the data structure objects and work with key-value pairs in JavaScript to store data easily and efficiently.
    • Objects allow for the storage of key-value pairs to access data using keys (or properties) for indices, and can also store multiple values for a single key in an array.
    • Objects cannot have duplicate keys, and JavaScript only allows strings to be keys in an object.
    • No two keys in the same object can have the same name, even if the assigned values are the same, as JavaScript does not allow an object to have two same keys.
    • Attempting to access the first element in a JavaScript object using an index (like an array or string) will return undefined since objects consist of only key-value pairs.
    • Dictionaries have several built-in functions and properties for insertion, deletion, and other operations, as well as Object methods for obtaining length, keys, and values.
    • The Object.entries() method returns an array of key-value pairs from an object, which can be accessed using an index starting at zero, e.g. pairs[1].
    • We learned about different data storage elements, such as variables, lists, and objects , which are used to store and manipulate data depending on the situation.