Animations

API

Arrays

Async

Basics

Challenges

Classes

Console

Dates

Debugging

DOM Elements

DOM Methods

DOM Navigation

DOM Properties

Event Listeners

Flow Control

Forms

Functions

Global Functions

JSON

Keywords

Libraries (3rd party)

Math

Modules

Objects

Snippets

String

Types

Widgets

Window Object

JavaScript - Properties

You can access object properties like so:


$("#demo").html("First name is " + person.firstName);
...or....
$("#demo").html("First name is " + person["firstName"]);

 

The second example deserves some exploration. What if you had a scenario where you wanted to select and use an object's property dynamically? What if you wanted to select First Name, Last Name, or age at will? You can actually pass in the property name as an argument and since it will be seen as a string, the code below will work fine.


let person = { Name: "Ricky Bobby", Occupation: "Race Car Driver", Gender: "Male", Age: 45 };
const ShowProperty = (prop) => { $("#demo").html(person[prop]); };
ShowProperty("Name");

// another example
const GetBackgroundColor = (answerStatus) =>
{
    let mapping =
    {
        "none": "",
        "correct": "green",
        "wrong": "red"
    };

    // returns "", green or red
    return mapping[answerStatus];
};