A better way to doing if statements in javascript

แชร์
ฝัง
  • เผยแพร่เมื่อ 15 ก.ค. 2022
  • 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/codyseibert/youtube

ความคิดเห็น • 451

  • @yx4292
    @yx4292 2 ปีที่แล้ว +288

    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 ปีที่แล้ว +21

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

    • @fuzzboi
      @fuzzboi 2 ปีที่แล้ว +67

      @@tooru chill, why the hate

    • @lucyegan82
      @lucyegan82 2 ปีที่แล้ว +86

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

  • @changalex469
    @changalex469 ปีที่แล้ว +16

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

  • @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.

  • @elatedbento
    @elatedbento ปีที่แล้ว +15

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

    • @Yutaro-Yoshii
      @Yutaro-Yoshii ปีที่แล้ว +1

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

  • @AnyVideo999
    @AnyVideo999 ปีที่แล้ว +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

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

    • @AnyVideo999
      @AnyVideo999 ปีที่แล้ว

      @@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 ปีที่แล้ว +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

      @@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 ปีที่แล้ว +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)

  • @silvanb
    @silvanb 2 ปีที่แล้ว +85

    My approach would be using switch

    • @melonenlord2723
      @melonenlord2723 ปีที่แล้ว

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

    • @samwise3117
      @samwise3117 ปีที่แล้ว

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

    • @Schnorzel1337
      @Schnorzel1337 ปีที่แล้ว +15

      @@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 ปีที่แล้ว +7

      @@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

  • @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 :) ?

  • @jaydeepkarena
    @jaydeepkarena ปีที่แล้ว +1

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

  • @charliesta.abc123
    @charliesta.abc123 2 ปีที่แล้ว +4

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

  • @eugenb9017
    @eugenb9017 ปีที่แล้ว +358

    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” 😂

  • @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

  • @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.

  • @StuartAylward
    @StuartAylward 2 ปีที่แล้ว +39

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

    • @Krilllind
      @Krilllind ปีที่แล้ว +4

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

    • @jakob7116
      @jakob7116 ปีที่แล้ว +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]])

  • @abdelbasset8280
    @abdelbasset8280 2 ปีที่แล้ว +1

    I am really enjoying your js shorts.

  • @truthseeker2236
    @truthseeker2236 ปีที่แล้ว +1

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

  • @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

  • @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 ปีที่แล้ว

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

  • @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

  • @thetrends5670
    @thetrends5670 ปีที่แล้ว +1

    He had us in the first half.

  • @ttrss
    @ttrss ปีที่แล้ว +24

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

  • @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.

  • @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

  • @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?

  • @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.

  • @keshavakumar9828
    @keshavakumar9828 ปีที่แล้ว

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

  • @captpierce83
    @captpierce83 ปีที่แล้ว

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

  • @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'..."

  • @pixelstriko1642
    @pixelstriko1642 2 ปีที่แล้ว +13

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

    • @ltroya
      @ltroya ปีที่แล้ว

      Isn't a hash table?

    • @Yutaro-Yoshii
      @Yutaro-Yoshii ปีที่แล้ว

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

  • @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?

  • @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.

  • @GranticusWaticus
    @GranticusWaticus ปีที่แล้ว

    Thank you for providing this helpful tip

  • @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

  • @kcbrown74
    @kcbrown74 ปีที่แล้ว +1

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

  • @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

  • @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!

  • @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.

  • @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

  • @stendaneel4879
    @stendaneel4879 ปีที่แล้ว

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

  • @adambright5416
    @adambright5416 11 หลายเดือนก่อน

    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.

  • @barondls8134
    @barondls8134 2 ปีที่แล้ว +1

    That trip is amazing 🤩

  • @floskater99
    @floskater99 ปีที่แล้ว +1

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

  • @akshay777able
    @akshay777able 2 ปีที่แล้ว +1

    These shorts are so helpful. Keep them coming.

  • @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

  • @jacoblockwood4034
    @jacoblockwood4034 ปีที่แล้ว

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

  • @RemoteAccessGG
    @RemoteAccessGG ปีที่แล้ว +1

    Lists left the chat

  • @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

  • @pqsk
    @pqsk ปีที่แล้ว +5

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

  • @joaoqueiroga3404
    @joaoqueiroga3404 ปีที่แล้ว +1

    Why not use switch case?

  • @erenuludag9498
    @erenuludag9498 ปีที่แล้ว

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

  • @blessedpigeon6304
    @blessedpigeon6304 ปีที่แล้ว +1

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

  • @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'

    • @MrRizzyWizzy
      @MrRizzyWizzy ปีที่แล้ว

      No enums in javascript though.

  • @boredguy1663
    @boredguy1663 ปีที่แล้ว

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

  • @orionpro79
    @orionpro79 ปีที่แล้ว +2

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

  • @nicholasryan7612
    @nicholasryan7612 ปีที่แล้ว

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

  • @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.

  • @minhtritruong3892
    @minhtritruong3892 ปีที่แล้ว

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

  • @piusmotai1874
    @piusmotai1874 2 ปีที่แล้ว +2

    That JavaScript functionality reminds me of the Python dictionary

    • @cheditx22
      @cheditx22 2 ปีที่แล้ว

      Fr

    • @Black.x
      @Black.x ปีที่แล้ว

      I did the same in Python

  • @hellowill
    @hellowill ปีที่แล้ว +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.

  • @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.

  • @kimberlyjacobsen4148
    @kimberlyjacobsen4148 ปีที่แล้ว

    You could freeze the object to prevent future changes

  • @CallousCoder
    @CallousCoder ปีที่แล้ว

    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!”;
    }

  • @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.

  • @caareystore4858
    @caareystore4858 ปีที่แล้ว +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

  • @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.

  • @sathyanarayanandhanuskodi1734
    @sathyanarayanandhanuskodi1734 ปีที่แล้ว +1

    Good idea.

  • @insignianator6452
    @insignianator6452 ปีที่แล้ว

    Check out c# enum. I have done this very thing to sync my enums in the back end to js logic on the front.

  • @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??

  • @mos90
    @mos90 ปีที่แล้ว

    that was beautiful. ❤️🙏

  • @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.

  • @abiodundacosta6250
    @abiodundacosta6250 2 ปีที่แล้ว +1

    This is pretty neat!... 💯

  • @TheRealTw1nky
    @TheRealTw1nky ปีที่แล้ว +8

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

  • @bhavishshetty5332
    @bhavishshetty5332 ปีที่แล้ว

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

  • @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 😜

  • @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?

  • @mohamedel-damarawy6595
    @mohamedel-damarawy6595 2 ปีที่แล้ว +15

    Or just use typescript and make use of enumerators 😃

    • @WebDevCody
      @WebDevCody  2 ปีที่แล้ว +1

      Absolutely

    • @Yutaro-Yoshii
      @Yutaro-Yoshii ปีที่แล้ว

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

  • @starterdev
    @starterdev 2 ปีที่แล้ว

    super great tip :D

  • @chinmayh2745
    @chinmayh2745 ปีที่แล้ว +1

    Just have array of string values as week names.

  • @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?"😂

  • @raianmr2843
    @raianmr2843 ปีที่แล้ว

    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.

    • @WebDevCody
      @WebDevCody  ปีที่แล้ว

      I think it’s fine.

  • @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

  • @kapildeshmukh7878
    @kapildeshmukh7878 ปีที่แล้ว

    Nice. Cleaned up an ugly switch case with a objectMap

  • @maxence3648
    @maxence3648 ปีที่แล้ว

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

  • @Yamas258
    @Yamas258 ปีที่แล้ว

    I understood some words you say😂

  • @ravisorathiya1756
    @ravisorathiya1756 ปีที่แล้ว

    Enums laughing in the corners

  • @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`.

  • @twocsies
    @twocsies ปีที่แล้ว

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

  • @SeibertSwirl
    @SeibertSwirl 2 ปีที่แล้ว

    Good job babe!

  • @_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….

  • @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

  • @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.

  • @mounis
    @mounis 2 ปีที่แล้ว +3

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

  • @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!

  • @zakuguriin4521
    @zakuguriin4521 ปีที่แล้ว

    That's pretty nice. I was gonna say using a Switch. Branching is nasty, I will always use a Ternary or Switch whenever I can get away with it.

  • @PowBro
    @PowBro ปีที่แล้ว

    I do this all the time... much better then writing if/else

  • @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.

  • @rauchu5861
    @rauchu5861 ปีที่แล้ว

    thats frigging sick :DDDDDDDDDDDDDDDDD

  • @gorandejanovic4796
    @gorandejanovic4796 ปีที่แล้ว

    try arrays they will blow your mind

  • @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 😉👍!

  • @bluerose2542
    @bluerose2542 ปีที่แล้ว

    I always put day in array