A better way to doing if statements in javascript

Поделиться
HTML-код
  • Опубликовано: 27 авг 2024
  • Instead of using a large if statement block to set a variable, try using a lookup map instead in javascript.
    #shorts
    ------------
    🤑 Patreon / webdevjunkie
    🔔 Newsletter eepurl.com/hnderP
    💬 Discord / discord
    📁. GitHub github.com/cod...

Комментарии • 452

  • @yx4292
    @yx4292 2 года назад +289

    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

    • @reprC
      @reprC 2 года назад +50

      An “easy” solution is to use a null-prototype object:
      const lookupTable = Object.assign(Object.create(null), { monday: 1, tuesday: 2, … });
      Or guard the lookup with:
      Object.hasOwn(lookupMap, day)
      That being said, this kinda reminds me of the pythonic alternative to switch statements. In this example, I think switch is less edge-case prone and IMO easier to read.
      switch (day) {
      case “monday”: return 1;
      case “tuesday”: return 2;

      default: return -1;
      }

    • @tooru
      @tooru 2 года назад +20

      @@reprC an even better solution is not to use such bad language as javascript.

    • @fuzzboi
      @fuzzboi 2 года назад +66

      @@tooru chill, why the hate

    • @lucyegan82
      @lucyegan82 2 года назад +85

      @@tooru I agree, we should use the other language that's available on the web... Oh wait 😱

    • @penguindrummaster
      @penguindrummaster 2 года назад +9

      @@reprC a better solution than Object.create(null) would be
      new Map().set('monday', 0) // ...
      Then use the method Map.prototype.get() with the coalesce operator to achieve the same result.
      The easiest way to do it would probably be the object literal as demonstrated, using a destructuring assignment, and then checking the value retrieved is the correct type.
      const dow = { monday: 0, tuesday: 1... };
      const {[day]: value = -1} = dow;
      return typeof value === 'number' ? value : -1;

  • @goranjosic
    @goranjosic Год назад +8

    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.

  • @elatedbento
    @elatedbento 2 года назад +15

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

    • @Yutaro-Yoshii
      @Yutaro-Yoshii 2 года назад +1

      map yn = {{"yes",'y'},{"absolutely!",'a'}};
      my favorite usecase of map is for command line parsing in cpp!

  • @eugenb9017
    @eugenb9017 Год назад +357

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

    • @WebDevCody
      @WebDevCody  Год назад +59

      You can name it after me 😂

    • @ironcloud6222
      @ironcloud6222 Год назад +19

      @@WebDevCody GOATED response💀

    • @asfaerfadfasdfsadf5211
      @asfaerfadfasdfsadf5211 Год назад

      they do things i did in delphi 10 years ago...

    • @enum01
      @enum01 Год назад +6

      He’s literally telling people how to do things????????? Like he didn’t say “I invented this” 😂

  • @AnyVideo999
    @AnyVideo999 2 года назад +73

    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

    • @hawkmne
      @hawkmne 2 года назад +2

      If the data is numerically keyed why would you need indexOf / findIndex?

    • @AnyVideo999
      @AnyVideo999 2 года назад

      @@hawkmne In the case where your array is
      ["Sunday", "Monday", "Tuesday]
      and you need to convert your day of the week to a number.

    • @hawkmne
      @hawkmne 2 года назад +6

      @@AnyVideo999 in that case, using findIndex/indexOf is much slower because lookup time complexity is O(n) compared to using a map/object with constant O(1) lookup time complexity, so no, array is a much worse fit here.

    • @AnyVideo999
      @AnyVideo999 2 года назад +2

      @@hawkmne For surprisingly large values of n, linear search is faster than a hash map. The purpose I opted for an array is that it removes any error prone behaviour when numbering, especially useful in small toy examples like this I'd say. By all means, you can take the entries of the array and make a hash map if you'd prefer.

    • @hawkmne
      @hawkmne 2 года назад +1

      ​@@AnyVideo999 it is true for very small values of n, not really for 'surprisingly large' values (though it's not clear what order of magnitude you imply here). In this particular case, linear search might be negligibly faster or equally fast, but generally hashmap lookup is much quicker, even for 'n' values as low as ~50-100, according to my benchmark (using Map, not plain object)

  • @lucasgrd4258
    @lucasgrd4258 Год назад +60

    Arrays' indexes left the chat

    • @prestonhall5171
      @prestonhall5171 Год назад +1

      That's what I always try to do if want to pair objects with consecutive numbers. Just store them in an array and use their indices. This works even if the numbers don't start at zero, as you can simply subtract the lookup number from the smallest number to get the index.

    • @alimanski7941
      @alimanski7941 Год назад

      Not sure about JS, but in python dictionaries have O(1) lookup time due to their keys being hashed, compared to O(n) to index an item in a list. So, it will be significantly faster to use a dictionary for this kind of operation (though of course negligible if you just have a handful of key-value pairs)

    • @lucasgrd4258
      @lucasgrd4258 Год назад

      @@alimanski7941 i can understand that, but honestly if you need speed, just don’t use python 😅

    • @alimanski7941
      @alimanski7941 Год назад +3

      @@lucasgrd4258 just because python (or js, or any other language) isn't the fastest, doesn't mean you get to neglect optimizations. Some optimizing principles are relevant for any language. If you design an entire system in python, you're not going to switch to another language just because you found out you need to index a value in a list of size 10 million.

    • @prestonhall5171
      @prestonhall5171 Год назад

      @@lucasgrd4258 Python will be coming out with an update in the near future that the developers say will increase the speed up to 3x, making it comparable to C and Java. So when that happens this will be outdated.
      That said, computers are so fast nowadays that Python's difference in speed is negligible for user programs.

  • @changalex469
    @changalex469 Год назад +16

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

  • @charliesta.abc123
    @charliesta.abc123 2 года назад +4

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

  • @matheuslopesmarques9363
    @matheuslopesmarques9363 Год назад +13

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

    • @kabomekgwe
      @kabomekgwe Год назад

      This was my train of thought

  • @jaydeepkarena
    @jaydeepkarena Год назад +1

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

  • @BboyHotshot
    @BboyHotshot Год назад +5

    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.

  • @user-jo2fe5tg9c
    @user-jo2fe5tg9c Год назад

    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.

  • @Rudxain
    @Rudxain 2 года назад +3

    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

    • @dc22199x
      @dc22199x 2 года назад

      But dont forget to treeshake your js, using Map is good but not so good if you're not utilizing every methods of that class, that comes in tree shaking procedure in node. Esbuild/Vite is built with this.

    • @Rudxain
      @Rudxain 2 года назад

      @@dc22199x WDYM? Map isn't a 3rd party library, it's included in ECMAscript. Do you mean the polyfill? Because yes, adding the entire polyfill is inefficient

  • @froxx93
    @froxx93 Год назад

    When you do it in typescript and define its type like Record 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'..."

  • @silvanb
    @silvanb 2 года назад +86

    My approach would be using switch

    • @melonenlord2723
      @melonenlord2723 2 года назад

      Switch is nice to read but very slow for some reason.

    • @samwise3117
      @samwise3117 2 года назад

      @@melonenlord2723 for real?
      Cos I like switch for these kinda stuff

    • @Schnorzel1337
      @Schnorzel1337 2 года назад +16

      @@melonenlord2723 You shouldnt be concerning yourself for those miniscule performance boosts. You are writing code for people not machines.
      Im not native to JS, but I think we can assume that the compiler/interpreter is smart enough, to handle both nearly at the same efficiency.
      In Java a big switch statment gets converted to an Hashmap for those values. This brings me back to my first point write code for people not machines.

    • @melonenlord2723
      @melonenlord2723 2 года назад +8

      @@Schnorzel1337 Ok, i tested it again, it doesn't seem to have any difference now. I rememver around some time ago switch was slow for some reason.

    • @davitkolxi2632
      @davitkolxi2632 Год назад

      switch is terrible

  • @truthseeker2236
    @truthseeker2236 Год назад +1

    nice, looks like I'm not the only one who prefers this strategy myself over ifs and switches.

  • @StuartAylward
    @StuartAylward 2 года назад +39

    Or you could literary use Map followed by nullish coalescing ...
    days = new Map([...])
    days.get(day) ?? -1

    • @Krilllind
      @Krilllind 2 года назад +4

      Yea this is way better. The solution shown in video was how we did it before 2015...

    • @jakob7116
      @jakob7116 2 года назад +3

      I prefer the way he did it in the video for this kind of stuff cuz it’s a lot cleaner:
      { x: 1, y: 2, z: 3 }
      new Map([[‘x’, 1], [‘y’, 2], [‘z’, 3]])

  • @SirDamatoIII
    @SirDamatoIII 2 года назад +71

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

    • @SiOnCaa
      @SiOnCaa 2 года назад +5

      Tank you! I scrolled way too far for this.

    • @catlord69
      @catlord69 2 года назад +5

      nobody said that the numeric values will corespond to the index

    • @alfredwindslow1894
      @alfredwindslow1894 2 года назад +2

      Who said Monday-> Sunday corresponded to 0->6? This way with a object is more generalised. Yours is very specific and wasn’t what was implied here

    • @akzual50
      @akzual50 2 года назад +3

      Isn't this an allocation each time?

    • @ltroya
      @ltroya 2 года назад

      That's not the same. It will return 0 for Monday

  • @Aeyzaz
    @Aeyzaz 2 года назад +55

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

    • @emmanuelu
      @emmanuelu 2 года назад +5

      this would only work if each day mapped to different numbers no?

    • @bakwertgeek2544
      @bakwertgeek2544 2 года назад +2

      Sorry i am new to programming so tell me if I am wrong but isn’t he not just describing a dictionary with the key value pairs?

    • @emmanuelu
      @emmanuelu 2 года назад

      @@bakwertgeek2544 pretty much like that yeah

    • @emmanuelu
      @emmanuelu 2 года назад

      @@bakwertgeek2544 you learning python right now?

    • @bakwertgeek2544
      @bakwertgeek2544 2 года назад

      @@emmanuelu yeah learning python right now but why u asking :) ?

  • @andyvu92
    @andyvu92 2 года назад +2

    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’.

    • @everyhandletaken
      @everyhandletaken 2 года назад

      I like this approach, had forgotten about this method

  • @rickvian
    @rickvian Год назад

    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

  • @dominikmatis6934
    @dominikmatis6934 Год назад +12

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

    • @ESArnau
      @ESArnau Год назад

      Yep. Way better

    • @farhanaditya2647
      @farhanaditya2647 Год назад

      @@ESArnau but it's slower

    • @YamiSuzume
      @YamiSuzume Год назад

      @@farhanaditya2647 But in general more useful, and that could makeup in speed, instead of making both, you know?

  • @keshavakumar9828
    @keshavakumar9828 Год назад

    This is great. Newbie here got to know something new today thanks

  • @trustytrojan
    @trustytrojan Год назад +7

    or just use switch case statements which is just as readable as if else statements. using dictionary/array for this purpose can be less readable

    • @lazlohollyfeld3770
      @lazlohollyfeld3770 Год назад

      A daynumver function containing a case whiich responds i agree would be good here

  • @AnEnemyAnemone1
    @AnEnemyAnemone1 Год назад

    I naturally started using maps/dicts very frequently as I started learning JavaScript for my job. They just make sense to use in so many contexts.

  • @ttrss
    @ttrss Год назад +24

    I swear you can always predict exactly what they're going to say.

  • @thetrends5670
    @thetrends5670 Год назад +1

    He had us in the first half.

  • @jacqueskloster4085
    @jacqueskloster4085 Год назад +1

    This indexing principle should be used especially when you want to have lookups in loops. I see junior developers excessively make use of array functions like Filter, map, some etc creating ridiculous amounts of nested loops instead of creating indexes, allowing for Direct property access to a desired entry

  • @abdelbasset8280
    @abdelbasset8280 2 года назад +1

    I am really enjoying your js shorts.

  • @TCErnesto
    @TCErnesto Год назад +2

    it'd be better to use an array of strings since the numerical days are within a range 0-6. And also an actual Map would be better than a plain object

  • @yovivideos
    @yovivideos 2 года назад

    I've used this a couple of times, it's very clean and readable, it's a lot faster than if's and just barely slower than switch

    • @iben1195
      @iben1195 2 года назад

      How do people know how fast one conditional is relative to another?

  • @stianscholtz5227
    @stianscholtz5227 Год назад +7

    Just make an array and use indexOf. Even simpler.

    • @harirushi4018
      @harirushi4018 Год назад

      On a practical scenario where any future keys are added, a dictionary is much more easy to add and get rather than using an array.

  • @pixelstriko1642
    @pixelstriko1642 2 года назад +13

    this is called a jump table and its nice but not for everything

    • @ltroya
      @ltroya 2 года назад

      Isn't a hash table?

    • @Yutaro-Yoshii
      @Yutaro-Yoshii 2 года назад

      what would you consider is a bad use case of this?

  • @BeatleGeuse_
    @BeatleGeuse_ Год назад

    In this case, you can use an array instead and use `indexOf`, but I really like to avoid if statements using objects, nice tip!

  • @Adamski94
    @Adamski94 Год назад +1

    Enums are pretty good for this. That way you can check for a value like so:
    Enum.Monday -> 1 or Enum[1] -> 'Monday'

  • @erenuludag9498
    @erenuludag9498 Год назад

    const day = 'tuesday'
    const values = {
    monday: 0,
    tuesday: 1,
    wednesday: 2
    }[day]
    console.log(day);
    little bit simpler :)

  • @pqsk
    @pqsk Год назад +5

    I would just use a switch statement. Very clear and does the same thing without creating an object.

  • @CallousCoder
    @CallousCoder 2 года назад

    Indeed these sorts of related constant strings need to be in const struct and/or in an array.
    But when you need to match strings use a regex match.
    var day = “Monday”
    var pattern = /Monday|Tuesday|Wednesday/;
    If ( pattern.test(day) ) {
    return “also non-working days!”;
    }

  • @acetributon
    @acetributon Год назад

    Better placed. I use optional chain between object and property and use logical OR as a false statement. Or value in object works too

  • @caareystore4858
    @caareystore4858 2 года назад +5

    I will use arrays for my approach, make an array for days and index them from 0, if the days value not in days array will return -1

  • @bugs389
    @bugs389 Год назад

    Another one that I like is immediately invoked anonymous functions. Rather than setting a variable within an if statement, you can return that value from the function. Naturally this lends itself to allow more complex logic within the function as well.

  • @captpierce83
    @captpierce83 Год назад

    For this specific use case, you put day strings into an array and use .indexOf

  • @kcbrown74
    @kcbrown74 Год назад +1

    Put days in an array and use the index for the number.

  • @RemoteAccessGG
    @RemoteAccessGG Год назад +1

    Lists left the chat

  • @orionpro79
    @orionpro79 Год назад +2

    the easiest option )) = ['понедельник', 'вторник', 'среда', 'четверг', 'пятница', 'суббота', 'воскресенье'].indexOf(day)

  • @adambright5416
    @adambright5416 Год назад

    1) Use Map if you need a map, stop using objects everywhere
    2) On small scale array lookup might be faster due to how slow hash function can be (microbenchmark it to your hearts content)
    3) do not recreate lookup maps or arrays inside function if you can prepare them globally. memory allocation is not cheap
    4) there's nothing wrong with if or switch statements, do not replace every if/switch statement with map/array lookup.

  • @joaoqueiroga3404
    @joaoqueiroga3404 2 года назад +1

    Why not use switch case?

  • @andrewhamel1
    @andrewhamel1 Год назад

    Would definitely be best to use the Map object now, deep that you can actually get a list of all your keys and many other important prototype features.

  • @janguardian
    @janguardian Год назад +2

    Or you could put days in array and use the indexOf method. Would be even more concise

    • @YeetYeetYe
      @YeetYeetYe Год назад

      That's O(n) time complexity whereas a map is O(1)

    • @janguardian
      @janguardian Год назад

      @@YeetYeetYe we’re talking about an array with seven items, c’mon man 😜

  • @piusmotai1874
    @piusmotai1874 2 года назад +2

    That JavaScript functionality reminds me of the Python dictionary

    • @cheditx22
      @cheditx22 2 года назад

      Fr

    • @Black.x
      @Black.x 2 года назад

      I did the same in Python

  • @godbleak
    @godbleak Год назад

    Or
    const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
    let day = days.indexOf('Wed');
    And `indexOf` will give you back -1 if it's not in the array.

  • @GranticusWaticus
    @GranticusWaticus 2 года назад

    Thank you for providing this helpful tip

  • @agapologia
    @agapologia 2 года назад

    I am so glad this wasn't just another ternary operator clip. I use this kind of thing all the time. Makes future extensibility much more natural as well. Also fits nicely with other good programming practices such as using constants, enums, and configs.

  • @bhavishshetty5332
    @bhavishshetty5332 Год назад

    U can place all the strings in array and findIndex() will do the job

  • @hellowill
    @hellowill 2 года назад +5

    Just use a switch-cacse, it uses hashmap under the hood.

    • @DeusGladiorum
      @DeusGladiorum Год назад +4

      switch statements absolutely do _not_ use hashmaps under the hood.

    • @hellowill
      @hellowill Год назад +1

      @@DeusGladiorum it absolutely uses hashing/lookups. Do you have evidence to prove otherwise?

    • @oculusquest6703
      @oculusquest6703 Год назад

      @@hellowill Hash maps and hashing are different things

    • @hellowill
      @hellowill Год назад +1

      @@oculusquest6703 it's essentially the same thing.
      If you want to correct my comment why not just do that instead of saying its completely wrong? Cause it sounded like you think it behaves like an IF statement.

    • @DeusGladiorum
      @DeusGladiorum Год назад

      @@hellowill Just to note, you’re talking to a couple different guys. But actually you’re right, I did think it acted like if-statements. Looked it up years ago and I guess the fall-through behavior without break made me believe such. So just never used it in my code lol. But I get mixed results as to whether or not it acts like a true lookup table/hash map though. Like anything else under the hood in JS, it really depends, but it can definitely operate as one.

  • @mohamedel-damarawy6595
    @mohamedel-damarawy6595 2 года назад +15

    Or just use typescript and make use of enumerators 😃

    • @WebDevCody
      @WebDevCody  2 года назад +1

      Absolutely

    • @Yutaro-Yoshii
      @Yutaro-Yoshii 2 года назад

      Yes enumerators are godly and efficient. This doesn't work for user input string though, does it?

  • @TheRealTw1nky
    @TheRealTw1nky 2 года назад +8

    I am a C# student, so i would use enums :)

  • @akshay777able
    @akshay777able 2 года назад +1

    These shorts are so helpful. Keep them coming.

  • @merazmi1971
    @merazmi1971 Год назад

    Have been using this for over a year, if not mistaken, its called as Object Lookup

    • @WebDevCody
      @WebDevCody  Год назад

      Yeah lookup table, a map, dictionary, key value store, enum if js had enums. All basically the same name for what this is

  • @vanvanni_nl
    @vanvanni_nl Год назад +4

    You are amazing never knew about dictionaries. That is great. And not to forget '??' does not indicate a fallback function. It a nullish coalescing operator.

  • @re.liable
    @re.liable 2 года назад

    If this is inside a function, where is it best to define the object mapping?
    - Simply inside the function? Wouldn't that get "redefined" everytime the function is called?
    - As a parameter? That would help with the "redefining" thing I feel that's a bit clunky?
    - Outside the function? That'd probably be best but then the details kinda go out of scope?
    Don't get me wrong, I absolutely do this as well. But there are times I don't know where to put the object definition that I just fallback to if-else statements lol

    • @Superroc0614
      @Superroc0614 2 года назад +1

      If I'm remembering things correctly, for literals like that (where the data is defined ahead of time), the compiler/interpreter will preload it into a memory location, and reference it that way, so it is not redefined on each function call

  • @minhtritruong3892
    @minhtritruong3892 2 года назад

    Supporting comments here always broaden my knowledge just as in my expectation

  • @creaky2436
    @creaky2436 Год назад

    I thought you were going to say the switch statement. Pretty cool

    • @WebDevCody
      @WebDevCody  Год назад

      I almost never use switch statements, I don't find them useful.

  • @Genaaa916
    @Genaaa916 Год назад

    Whoa, a real eye opener, thanks! Do you know if it's possible to store multiple strings or values in a single variable??

  • @floskater99
    @floskater99 Год назад +1

    In this case I would just make a list and use indexOf(), even shorter.

  • @spicynoodle7419
    @spicynoodle7419 Год назад

    Since Date.getMonth() returns an index you can also avoid if-else by making a simple array:
    let months = ['January', 'February', ...]

  • @blessedpigeon6304
    @blessedpigeon6304 Год назад +1

    Gotta say switch statement would be more readable in this particular case

  • @jacoblockwood4034
    @jacoblockwood4034 Год назад

    Since this example only uses numbers, you could do an array with indexOf. But this is faster and probably more readable

  • @ravisorathiya1756
    @ravisorathiya1756 Год назад

    Enums laughing in the corners

  • @mounis
    @mounis 2 года назад +3

    Using objects increases the space complexity. So just use an array and return array[i+1]

  • @teeboh99
    @teeboh99 Год назад +3

    Ok so when I started coding professionally I used to do this for situations where there were many conditions I had to handle.
    Upon getting my code reviewed, a senior mentioned to me that while it might look “cleaner”, it might not always be the best option.
    When writing production code that’s going to be around for years and handled by dozens of devs, you always want to be as explicit as possible lest your intentions be misinterpreted, you also want to reduce the time between your code being initially seen and your code being fully understood.
    Using objects or maps can potentially run foul of these 2 things, depending on where the map is defined and if the value is pulled via a function or inline.
    It’s always going to be much clearer and explicit to use a switch statement, yes it might not look “cleaner” but these are the situations it was designed for
    Just my 2 ce…pennies?

    • @WebDevCody
      @WebDevCody  Год назад

      Yeah I think it depends on the use cases, but if it’s a legit value lookup like in this video, I do not see any need for if or switch. The moment you need to run multiple statements when the day is Sunday, get rid of the map approach and go to if else if else

    • @hadawardgz
      @hadawardgz Год назад

      But readability doesn't have much to do with it though, you can always give it a specific name and use keys that match the name, of course I'm talking about small objects.

  • @patite3103
    @patite3103 Год назад

    Would it be possible to elaborate this example with a video? I get an error message for ?? -1. How does it work? What is the purpose of this code?

  • @tauzN
    @tauzN Год назад

    This is not "a better way to doing if statements"... this is just a better way to solve this specific problem...

  • @colinwiseman
    @colinwiseman Год назад

    I know you've tried to be generic, but for a M-S
    const day = 'Tuesday';
    let value = ['Monday', 'Tuesday',...].indexOf(day);
    and value will be the correct value or -1.

  • @dcknature
    @dcknature Год назад +2

    Yeah, using a long if else statement isn't a good idea. Having a data structure is much better than that.
    Thank you and thumbs up 😉👍!

  • @stendaneel4879
    @stendaneel4879 Год назад

    you can also create a list with all the days and then run the .indexOf(day) function on it

  • @barondls8134
    @barondls8134 2 года назад +1

    That trip is amazing 🤩

  • @DEVDerr
    @DEVDerr 2 года назад +1

    Well... I wouldnt use object for that. Javascript Maps were created and intended for this type of case. Especially that they have very easy and straight-forward methods for getting and setting the values :)

    • @WebDevCody
      @WebDevCody  2 года назад +1

      Map vs object, literally the same data structure imo

    • @hedgehog125
      @hedgehog125 2 года назад

      I thought maps were for when the structure of an object changes more than a slight amount?

  • @maxence3648
    @maxence3648 Год назад

    You could just use an array with your days in and use findindex on it it’s one line

  • @Joshk326
    @Joshk326 Год назад

    Hashmap, hashmap, hashmap!!! Hashmaps are always the answer

  • @kapildeshmukh7878
    @kapildeshmukh7878 Год назад

    Nice. Cleaned up an ugly switch case with a objectMap

  • @daveisradicle
    @daveisradicle Год назад

    protip: *almost* never do this, instead -- use arrays. The only time you should have objects like this is if you're using them with `.reduce`.

  • @THEJR_DEV
    @THEJR_DEV 2 года назад

    The object returns 0 if the day is Monday in which case days[key] ?? -1 will return -1 as "zero" will be interpreted as" false ".

    • @WebDevCody
      @WebDevCody  2 года назад

      I think the ?? Only falls back on null and undefined

    • @THEJR_DEV
      @THEJR_DEV 2 года назад

      @@WebDevCody thanks a lot for clarifying that to me ! I just tested it by myself it's working as you said ! And thank you again for clarifying that !

  • @kimberlyjacobsen4148
    @kimberlyjacobsen4148 Год назад

    You could freeze the object to prevent future changes

  • @wakwawunited1588
    @wakwawunited1588 Год назад

    it's people like this that confuse me on stack overflow.
    when you see the program code on the forum like 'what is this, how does it function?, why does it work?, what is the logic?"😂

  • @angell2341
    @angell2341 2 года назад

    Create an array like ["Monday "] and do Object.keys gets keys should do it as well or getting specific indexOf array location can provide integer.

  • @davydorynbaev
    @davydorynbaev 2 года назад +1

    Why not represent your days as numbers in the first place, with an enumerator or something? Does that exist in JS? That would (very likely) save processing time and memory.

    • @WebDevCody
      @WebDevCody  2 года назад +1

      I’m just teaching a concept, I didn’t think everyone would question the example so critically 😅

    • @everyhandletaken
      @everyhandletaken 2 года назад +1

      @@WebDevCody .. it’s the internet, expect the worst 😂

  • @_gunnnu_
    @_gunnnu_ Год назад

    OR
    You could save Monday to Sunday in an array and just return its index or index +1 based on requirement and do a nullish cohelscing check and return -1 if the value is not in array….

  • @nicholasryan7612
    @nicholasryan7612 Год назад

    you could also write an array and use a for loop.

  • @TheCameltotem
    @TheCameltotem 2 года назад

    Its like Javascript people never heard of objects before. I mean this is how you would do it in java/C#. Nice that you brought it up here too!

    • @WebDevCody
      @WebDevCody  2 года назад +1

      Sometimes it’s just hard for a beginner to know when to use what pattern when solving a problem

  • @gorandejanovic4796
    @gorandejanovic4796 Год назад

    try arrays they will blow your mind

  • @mvnkycheez
    @mvnkycheez 2 года назад +1

    Are you and Web Dev Simplified lab clones?

  • @sathyanarayanandhanuskodi1734
    @sathyanarayanandhanuskodi1734 Год назад +1

    Good idea.

  • @shivam-hs7fz
    @shivam-hs7fz 2 года назад +1

    Instead use an array

    • @WebDevCody
      @WebDevCody  2 года назад

      Sure for this example because we happen to return numbers that happen to increment from 0, but what if we didn’t return numbers we’d need to do something like this

    • @shivam-hs7fz
      @shivam-hs7fz 2 года назад

      okay it make sense now
      Keep doing it brother i love this type of videos it really help me

  • @yeboahnanaosei
    @yeboahnanaosei Год назад

    Great job. Which font are you using by the way?

    • @WebDevCody
      @WebDevCody  Год назад

      Should be in description I think

    • @yeboahnanaosei
      @yeboahnanaosei Год назад

      @@WebDevCody I just checked. I did not see any mention of a font

    • @WebDevCody
      @WebDevCody  Год назад

      @@yeboahnanaosei check out one of my latest videos

    • @yeboahnanaosei
      @yeboahnanaosei Год назад

      @@WebDevCody I'm confused. I wanted to find out the name of the font in this video.

  • @raianmr2843
    @raianmr2843 2 года назад

    Use ES6 maps instead of plain old objects. Objects weren't designed to be used like this and have some pitfalls as mentioned by others in the comments.

  • @MrRizzyWizzy
    @MrRizzyWizzy Год назад

    One hacky javascript way to do Enums is like this:
    function createEnum(values) {
    const enumObject = {};
    for (const val of values) {
    enumObject[val] = val;
    }
    return Object.freeze(enumObject);
    }
    const Days= createEnum(['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Satursday']);
    var today = Days.Tuesday;

    • @WebDevCody
      @WebDevCody  Год назад

      Yeah, seems a bit hacky, but it would work!

  • @boredguy1663
    @boredguy1663 2 года назад

    I was using Switch statement but this approach seems better in certain cases.

  • @twocsies
    @twocsies Год назад

    If the array does not have that elements it will throw an arror. Null coalesce is not sufficient.

  • @justinian.erdmier
    @justinian.erdmier 2 года назад +2

    Wtf doesn't js have a switch expression?

    • @Migler1
      @Migler1 Год назад

      Yes it does.