DEV Community

loading...

Discussion on: PHP 8 features I wish also existed in JavaScript

Collapse
thodwris profile image
Theodoros Kokosioulis

Can you elaborate more on how the #2 works?

Collapse
lukeshiru profile image
△ LUKE知る

Sure! Here it is separated in parts and with comments:

// We create a plain object that has a key = value mapping
const fontWeightMap = {
  // For example, here we say: When the value is 100, we want "Super Thin"
  100: "Super Thin",
  300: "Thin",
  400: "Normal",
  600: "Bold",
  900: "Heavy"
};

// The value of fontWeight here will be "Thin"
const fontWeight300 = fontWeightMap[300];

// But maybe we have a value that is not mapped, like 200
const fontWeight200 = fontWeightMap[200];

// That produces an undefined, so we use the ?? operator
// that only goes to the right value if the left is null or undefined

// Here because 200 is undefined, the value of safeFontWeight is "default"
const safeFontWeight = fontWeightMap[200] ?? "default";
Enter fullscreen mode Exit fullscreen mode

Putting all together:

const fontWeight =
    // Map Object
    {
        100: "Super Thin",
        300: "Thin",
        400: "Normal",
        600: "Bold",
        900: "Heavy"
    // We pass a weight value, and if it doesn't exist then we go to ""
    }[weight] ?? "";
Enter fullscreen mode Exit fullscreen mode