DEV Community

loading...

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

Collapse
lukeshiru profile image
▲ LUKE知る • Edited

You can actually get around all of these:

#1 Named arguments

const aFunction = ({ foo, bar }) => ...

aFunction({ bar: 1, foo: 2 });
Enter fullscreen mode Exit fullscreen mode

#2 Match expression

const fontWeight =
    {
        100: "Super Thin",
        300: "Thin",
        400: "Normal",
        600: "Bold",
        900: "Heavy"
    }[weight] ?? "";
Enter fullscreen mode Exit fullscreen mode

#3 Optional chaining

This one is not missing in JS:

const country = session?.user?.getAddress()?.country ?? null;
Enter fullscreen mode Exit fullscreen mode
Collapse
devmount profile image
Andreas Author

Awesome! Didn't know #3 was already possible in JS 👏🏻

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