DEV Community

loading...

Should JavaScript do this?

Adam Crockett
I work at ForgeRock as Staff UI Engineer, I play with all sorts really. Lately WASM is my toy of interest.
・1 min read

Let's let the code do the talking:

function flavour(name) {
    switch(name) {
        case 'berry':
            return 1
        case 'choc'
            return 2
    }
}

const sprinkles = true;

const iceCream = {
    // Regular ol' property
    milk: 2,
    // Insert key and Value at the same time
    sprinkles,
    // 🤔 Why not do the same as above with return values
    flavour('choc'), // ⬅️
    // Define a value
    scoop(cone) {
        return cone.add(this);
    }
}
Enter fullscreen mode Exit fullscreen mode

Discussion (3)

Collapse
mse99 profile image
Mohamed Edrah

Implementing that is going to be difficult since you can invoke any expression in javascript.

Collapse
adam_cyclones profile image
Adam Crockett Author

That's interesting can you give an example of this problem. Thank you for commenting

Collapse
mse99 profile image
Mohamed Edrah

In javascript unlike concise property names (which results in just a regular identifier scope lookup), calling a function often involves doing a lot more.

function red () {
  return [255, 0, 0]
}

const colors = {
  red()
}
Enter fullscreen mode Exit fullscreen mode

here the javascript VM needs to first resolve the reference to red, it will then need to check if the value is a function or not, it will then need to check if the function object supports regular calls (JavaScript "classes" which are just fancy constructor functions must be called using only new operator), you can see that unlike concise property names there's a lot more nuance involved.

It is doable, but they're going to have to cut a lot of corners.