React Notes 2

React Notes 2

React Notes 2

Dynamic Access with Objects

const activityMultipliers = {
        sedentary : 1.2,
        light : 1.375,
        moderately : 1.55,
        very : 1.725,
        super_active : 1.9
    }

    const activityLevel = activity;

    if (activityMultipliers[activityLevel]){
        BMR = BMR * activityMultipliers[activityLevel];
    } else return;

Dynamic Access with objects using Bracket Notation allows you to use variables, expressions, or even computed property names to reference the objects properties.

Object Destructuring

const data = {
    age: 25,
    sex: "male",
    height: 175,
    weight: 70,
    activity: "moderate"
};

const { age, sex, height, weight, activity } = data;
// Renaming during destructuring
const { age: userAge, sex: userSex, height: userHeight } = data;

Allows you to extract multiple properties from an object and assign them variables in a concise manner.

The Problem with 0 as an object property value

When the goal is “maintenance”, calGoals[specGoals] is 0, which is falsy.

As a result, the if (calGoals[specGoals]) condition fails because 0 is evaluated as falsy.

const calGoals = {
    fat_loss: -500,
    aggressive_fat_loss: -750,
    maintenance: 0,
    muscle_gain: 250,
};

if (calGoals[specGoals]) {
    BMR = BMR + calGoals[specGoals];
}

Instead of relying on JavaScript’s truthy/falsy behavior, you can explicitly check for the presence of the key in the object or check if the value is not undefined (or even null) to avoid incorrect behavior when the value is 0.

if (calGoals.hasOwnProperty(specGoals)) {
    BMR = BMR + calGoals[specGoals];
    console.log(BMR);
} 

This method checks if the key exists in the object, regardless of its value (even if the value is 0 or another falsy value).

View All Posts