DEV Community

Cover image for New Usefull JavaScript Tips For Everyone
SHaon
SHaon

Posted on

3

New Usefull JavaScript Tips For Everyone

*Old Ways *

 const getPrice = (item) => {
  if(item==200){return 200} 
   else if (item==500){return 500}
   else if (item===400) {return 400}
   else {return 100}
}

console.log(getPrice(foodName));

Enter fullscreen mode Exit fullscreen mode

New Ways

const prices = {
 food1 : 100,
 food2 : 200,
 food3 : 400,
 food4 : 500
}

const getPrice = (item) => {
 return prices[item]
}

console.log(getPrice(foodName))
Enter fullscreen mode Exit fullscreen mode

Hope you like my new tricks :D

follow my github account

Top comments (3)

Collapse
 
pierrewahlberg profile image
Pierre Vahlberg • Edited

For this specific use case and similar "lookups", check out Map and Set in the MDN docs. They build on the dictionary/hash map which is essential JS functionality, now with a nice interface.

Note that the use cases are different, they are both iterable (for ...of.. etc) and that their purpose is value lookup or keeping track of values

Like this

var allowedPrices = new Set([100, 200, 300])
var price = allowedPrices.has(233) || 100; // gives 100
Enter fullscreen mode Exit fullscreen mode

Using large lists this approach outperforms and array version by far and is a lot cleaner IMO.

An example for map could be

var map = new Map([
    [ 100, "cheap" ],
    [ 200, "afforfable"],
    [ 300, "expensive"],
])

var price = 200;
var priceLabel = map.get(price) || "untagged"; // affordable
Enter fullscreen mode Exit fullscreen mode

developer.mozilla.org/en-US/docs/W...

developer.mozilla.org/en-US/docs/W...

Collapse
 
pierrewahlberg profile image
Pierre Vahlberg

Oh, I did not mean to criticize but to educate! 😊 keep writing and keep learning 🙏

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

You might want to improve the 'old ways' example. Currently you could replace the function with this:

const getPrice = item => [200, 400, 500].includes(item) ? item : 100
Enter fullscreen mode Exit fullscreen mode

Ideally, the first example should have identical functionality to the second. There is also an issue with the second example - it will return undefined if it doesn't know the item.

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools can’t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay