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
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?
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");
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
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.
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.
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.
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!
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.
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”.
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.
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().
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.
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
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.
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.
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
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.
Quick and to the point, great vid. Thanks mate
Learnt something today which I did not know yesterday.... many thanks!
waiting for more on topics in JS to understand concepts
Thanks for this James 👍👍
Glad you enjoyed it!
Great explaination for the Javascript Enums, Thanks.
one word, brilliant :)
So simply explained, Thanks..
great explanation james
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
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?
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);
How would I set my variable to a GAME_STATES if I have its values (maybe from querystring): let gameState = GAME_STATES.Find("Playing");
Loving this video, that Object.freeze() approach is super clever!
Didn't know this was built into TS, awesome, thanks :)
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
Like Java i suppose
@@tiendatnguyen6758 never used it I used the same approach in php
its called a data transfer object or a DTO
Lovely! Thanks
Thank you! Thank you!!
great explanation
Awesome explanation, Thank you so much. ☺☺
cool, thanks. Perfect video for a short break :)
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.
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.
Could i Ask u about a question about Javascript?
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.
@@dardanillyr3989 Don’t ask to ask, just ask…
Great Video!@
@James Which theme of vs code are you using here??
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!
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.
What theme are you using on VScode? it looks awesome
So an enum is essentially an object literal with a specific use case?
Would be nice if you also demonstrated how to use enums as bit masks...
great video! what plugin are you using to make that animation for cursor line?
This is built in VS Code. Simply go to the settings, search for "cursor blinking" and select "expand".
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”.
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.
Use Typescript
Great video
>Q Quick
Nice, immediate subscribe!
You wouldn’t happen to be the same JamesQ from U413 would you? Either way, excellent channel!
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 ?
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().
@@jonlothar6126 well said.
@@عبدالقادرعبدالرحمنعبدالله Thank you!
Thanks for sharing
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.
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
@@hiagooliveira6510 it will depends strictly on which architecture your project is based on. clean code does not mean more code whatsoever
Could i Ask u about a question about Javascript?
at 5:00 - how can you modifí if its a const.
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.
Welcome to the JavaScript world...
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
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.
Astoundingly clear and succinct explanation of creating ENUMs in JavaScript!
Thanks, James
{2022-03-28}
Does JavaScript guarantee property order in case you had to iterate the keys?
No, object does not. Use map instead.
Nice tutorial.
Ty so much
I was thinking "const" has the same effect as "Object.freeze()" but maybe I'm mistaken?
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
Awesome!
Quokka looks great, but it seems to stop working, and I can't get it loaded into new JS files. :(
What I get from this comment sections is that there are no enums in JavaScript, just ways to make things act like enums
Object.freeze😍😍
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.
Could i Ask u about a question about Javascript?
that's not an enum, it's just an object defined as const xD
or simply, install this module, *npm i enum*
First🤗
or u use typescript =O
... If someone needs an explanation on setting up enums they should probably find another career choice lol
Object.freeze for the WIN 🙂