How to Guarantee That My Enums Definition Doesn't Change in JavaScript

How can I guarantee that my enums definition doesn't change in JavaScript?

Since 1.8.5 it's possible to seal and freeze the object, so define the above as:

const DaysEnum = Object.freeze({"monday":1, "tuesday":2, "wednesday":3, ...})

or

const DaysEnum = {"monday":1, "tuesday":2, "wednesday":3, ...}
Object.freeze(DaysEnum)

and voila! JS enums.

However, this doesn't prevent you from assigning an undesired value to a variable, which is often the main goal of enums:

let day = DaysEnum.tuesday
day = 298832342 // goes through without any errors

One way to ensure a stronger degree of type safety (with enums or otherwise) is to use a tool like TypeScript or Flow.

Quotes aren't needed but I kept them for consistency.

JavaScript - Why doesn't my code run when Document.querySelector().value is outside function + how do I get function to run on input number change?

const number needs to be in the function, otherwise the const will be null always

function myFunction() {

const number = document.querySelector("input").value
if (parseInt(number) === 2) {
message.textContent = "Correct"
} else message.textContent = "Wrong!"
}

Live update on keyup inputfield

const inputfield = document.querySelector("input");
inputfield.addEventListener("keyup", myFunction);

Why doesn't the value of a field change after form submit (JavaScript/Chrome extension)

Ok I just realized I had this stateless, so when I turned it stateful with React did the job

class TextChanger extends React.Component {
constructor() {
super();
this.state = {};
}
render() {
const task = 'task' in this.state ? this.state.task :
this.props.task;

and then

onTextChange(event) {
this.setState({
task: event.target.value,
});
}


Related Topics



Leave a reply



Submit