JavaScript Enums in 5 Minutes - What they are and how to create them

Поделиться
HTML-код
  • Опубликовано: 4 янв 2025

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

  • @Paul-wy6tn
    @Paul-wy6tn Год назад +3

    Quick and to the point, great vid. Thanks mate

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

    Learnt something today which I did not know yesterday.... many thanks!

  • @js-swift
    @js-swift 2 года назад +5

    waiting for more on topics in JS to understand concepts
    Thanks for this James 👍👍

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

    Great explaination for the Javascript Enums, Thanks.

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

    one word, brilliant :)

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

    So simply explained, Thanks..

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

    great explanation james

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

    There is a JS project we are putting feature flags in. Didn't like the array reference to the flags, wished we had enum like TS. Thanks for showing this, spot on

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

    What I know from TypeScript is that enums are reverse mappable. Reverse mappable means that we can get the value (right side) using the key, and can we get the key (right side) using the value. But the enum you made in Javascript is a plain old object literal.
    Am I missing something?

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

      Provided you don't have duplicate values, the enum in JS is also reverse mappable. Ofc it takes a little code to index it by value but it can still be done pretty easily. Something like
      Object.keys(epikEnum).find(key => epikEnum[key] === value);

  •  Год назад +1

    How would I set my variable to a GAME_STATES if I have its values (maybe from querystring): let gameState = GAME_STATES.Find("Playing");

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

    Loving this video, that Object.freeze() approach is super clever!

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

    Didn't know this was built into TS, awesome, thanks :)

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

    I like to create my enums as a class so each has an instance and can have a to string and to json option. Then the enum class can provide helper methods for like generating drop downs etc

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

    Lovely! Thanks

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

    Thank you! Thank you!!

  • @Rajkumar-mi3uv
    @Rajkumar-mi3uv 2 года назад

    great explanation

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

    Awesome explanation, Thank you so much. ☺☺

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

    cool, thanks. Perfect video for a short break :)

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

    You can declare your enum values slightly different without having to group them into an object for which than youre ought to freeze.
    That other way is, you create a constants file where namely expory each state/key as a constant of its own and then import as all anywhere else plus you can rename that grouped module to w/e you feel is right.
    E.g.
    // gameStates.js
    export const IS_PLAYING = 'isPlaying';
    export const IS_PAUSED = 'isPaused';
    export const IS_FINISHED = 'isFinished';
    //myView.js
    import * as GAME_STATES from './gameConstants';
    // Or selectively picking one or few
    import { IS_PLAYING, IS_PAUSED } from './gameStates';
    As you can see you are safe from someone overriding these values cause they are constants and they wont be able to overriden. Also advantage is that you can selectively import, helps alot when tree shaking and code splitting is in place.

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

      That’s a good point. I’ve used that approach before but more for one off constants. The benefit that the object representation gives you is that they are all kinda grouped together.

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

      Could i Ask u about a question about Javascript?

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

      This does make a lot more sense. Also I personally dislike something like "constants" global variable. Constants should be put close to its domain model.

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

      @@dardanillyr3989 Don’t ask to ask, just ask…

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

    Great Video!@

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

    @James Which theme of vs code are you using here??

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

    What is the theme that you're using for VSCode? Love it. Also, how do you get the animated text cursor and inline console.log() output within the syntax? Thanks in advance!

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

      Don't know about the theme but the cursor effect is under settings>cursor blinking>expand and the inline console log is an extension called quokka which he mentioned at the start of the video.
      Hope this helps!
      Ps. Pretty sure you can easily find the theme if you scroll through extensions>themes for a little while.

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

    What theme are you using on VScode? it looks awesome

  • @AD-wg8ik
    @AD-wg8ik 2 года назад

    So an enum is essentially an object literal with a specific use case?

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

    Would be nice if you also demonstrated how to use enums as bit masks...

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

    great video! what plugin are you using to make that animation for cursor line?

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

      This is built in VS Code. Simply go to the settings, search for "cursor blinking" and select "expand".

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

    Nice video. Just one question on top of it. How to enforce that the variable gameState doesn’t take any value outside of enum?
    Because even though we have an enum defined, we are not guaranteed that the gameState can only be assigned a value from inside it only. We can still write gameState = “any_value”.

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

      Two ways afaik - use typescript, so you can enforce the type of the variable (const gameState: GameState = GameState.playing) - or set the value using a function (setGameState) which does some validation to ensure the value you provided is part of that enum. Other than those, javascript just isn't typesafe.

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

      Use Typescript

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

    Great video

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

    >Q Quick
    Nice, immediate subscribe!

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

    You wouldn’t happen to be the same JamesQ from U413 would you? Either way, excellent channel!

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

    I would have thought you could not change the GAME_STATES because it was defined as const. So do we still require the object.freeze ?

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

      You would think right? In reality, it does require Object.freeze() because objects are pass by reference and not by value. This means that having a constant object makes it so you can't switch the value of the variable to a completely new Object. However, this doesn't mean that you can't continue to manipulate the object's fields-the only way to stop that is Object.freeze().

    • @عبدالقادرعبدالرحمنعبدالله
      @عبدالقادرعبدالرحمنعبدالله 2 года назад +1

      @@jonlothar6126 well said.

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

      @@عبدالقادرعبدالرحمنعبدالله Thank you!

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

    Thanks for sharing

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

    just a hint, I would go for object destructuring rather directly object property assignment. it's not so legible, but you can save a few lines of code.

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

      which goes against clean code principles... it's better if it has a couple more lines but is very legible and straightforward than having 3 ternary operators chained to save a few lines for example

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

      @@hiagooliveira6510 it will depends strictly on which architecture your project is based on. clean code does not mean more code whatsoever

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

      Could i Ask u about a question about Javascript?

  •  2 года назад

    at 5:00 - how can you modifí if its a const.

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

      a const in JS can't be replaced, i.e., the whole GAME_STATES can't be assigned with a new value, but the properties in that object GAME_STATES can be updated. A const isn't a true const, i.e., the subparts can still be modified.

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

      Welcome to the JavaScript world...

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

    u do not need to use object.freez with constant
    if u try to assign another value for constant the compiler will throw an erorr

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

      GAME_STATES = {} // error
      GAME_STATES.NOT_STARTED = "xxx" // no error
      Object.freeze doesn't change that, but the value of NOT_STARTED is unchanged, even if you set it.
      So you need Object.freeze(). A const GAME_STATES is not enough.

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

    Astoundingly clear and succinct explanation of creating ENUMs in JavaScript!
    Thanks, James
    {2022-03-28}

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

    Does JavaScript guarantee property order in case you had to iterate the keys?

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

      No, object does not. Use map instead.

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

    Nice tutorial.

  • @6flak
    @6flak 3 месяца назад

    Ty so much

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

    I was thinking "const" has the same effect as "Object.freeze()" but maybe I'm mistaken?

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

      Const doesn't allows you to reasign a value to a variable. But if the variable has assigned an object, you can add, remove properties from that object. Object.freeze prevents you from modifying that object

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

    Awesome!

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

    Quokka looks great, but it seems to stop working, and I can't get it loaded into new JS files. :(

  • @gumbilicious1
    @gumbilicious1 7 месяцев назад

    What I get from this comment sections is that there are no enums in JavaScript, just ways to make things act like enums

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

    Object.freeze😍😍

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

    hum, you should ((never)) use strings for this kind of flags for your game loops.
    Compare pure number is hell faster vs compare strings.
    Ts allow easly handle enums numbers, but in js, if you lazy , you want you cant just add comment upper your number to give definition and help debug.

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

      Could i Ask u about a question about Javascript?

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

    that's not an enum, it's just an object defined as const xD

  • @عبدالقادرعبدالرحمنعبدالله

    or simply, install this module, *npm i enum*

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

    First🤗

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

    or u use typescript =O

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

    ... If someone needs an explanation on setting up enums they should probably find another career choice lol

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

    Object.freeze for the WIN 🙂