A better way to doing if statements in javascript #shorts

preview_player
Показать описание
Instead of using a large if statement block to set a variable, try using a lookup map instead in javascript.

#shorts

------------

Рекомендации по теме
Комментарии
Автор

beware that objects created with object literals inherit properties from Object.prototype . that means that if day is 'toString', then values[day] will actually return a function and not a numerical value as you expect

yx
Автор

This is an interesting approach not just for JavaScript. Maps are everywhere. Thanks for sharing.

elatedbento
Автор

The beauty of Python is that you learn these things at the very beginning, because in python this approach is taken for granted. That's my experience.

goranjosic
Автор

Nice, I too prefer this method. Howell, in the case of numerical keyed data, the array is a much better fit paired with an indexOf or findIndex

AnyVideo
Автор

Wow, you "invented" the dictionary. Great job!

eugenb
Автор

have used this so many times.... very useful

jaydeepkarena
Автор

In this case I will use an array with string + indexOf

changalex
Автор

const values = ['tuesday', 'monday', 'wednesday']
values.indexOf('tuesday') // return 0
values.indexOf('sunday') // return -1 becausa not exist

matheuslopesmarques
Автор

A different approach would be an Array and just find the index

Aeyzaz
Автор

const arr = ['monday', ….]
const day = arr.indexOf('monday')

dominikmatis
Автор

Everyone commenting saying "I would just indexOf()... array... List...etc" doesn't understand that this is incredibly useful for data that is non continuous and works for reference types as well. The only reason this works is because Mon-Sun is linearly mapped to 0-7.

Im a C# dev and we call them dictionaries instead of maps but essentially they are a collection of key->value pairs, where the values could even be generic in type. The last implementation I used this for was in a 'inventory' system (game dev). I can't recall why I needed a dictionary instead of just a list, but they are incredibly useful structures for representing data in all sorts of ways.

jofetgc
Автор

One line:
return [“monday”, ”…].IndexOf(day);

SirDamatoIII
Автор

Good tip. If you need to do anything more than this with maps, use the Map type.

charliesta.abc
Автор

For a string mapping, I usually do things like

const childTheme = {
white: ‘black’,

}[parentTheme]

By setting parentTheme default to ‘white’, the default for childTheme will always be ‘black’.

andyvu
Автор

When dealing with arbitrary data, it's better to use an actual `Map` than an object, for the same reason the top comment mentioned (prototype collision). Or just use an Object stripped off its prototype

Rudxain
Автор

switch-case works great here as well. Switch only evaluates once, while if-else evaluates for every condition set...and you don't have to store anything. Best performance as well as storage utilization.

BboyHotshot
Автор

Or you could literary use Map followed by nullish coalescing ...

days = new Map([...])
days.get(day) ?? -1

StuartAylward
Автор

Just make an array and use indexOf. Even simpler.

stianscholtz
Автор

When you do it in typescript and define its type like Record<Day, number> you can even save the fallback value since typescript will prevent you to pass in any possible value other than Day (which you would have to define as a literal chain as well like "type Day = 'monday' | 'tuesday'..."

froxx
Автор

as js professional, i can cofirm this is what i do all the time, please do this folks

but keep in mind about accessing property of null it can crash on run time

in this video, he use bracket notation rather than dot notation, it makes difference

rickvian