*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));
New Ways
const prices = {
food1 : 100,
food2 : 200,
food3 : 400,
food4 : 500
}
const getPrice = (item) => {
return prices[item]
}
console.log(getPrice(foodName))
Hope you like my new tricks :D
Top comments (3)
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
Using large lists this approach outperforms and array version by far and is a lot cleaner IMO.
An example for map could be
developer.mozilla.org/en-US/docs/W...
developer.mozilla.org/en-US/docs/W...
Oh, I did not mean to criticize but to educate! 😊 keep writing and keep learning 🙏
You might want to improve the 'old ways' example. Currently you could replace the function with this:
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.