Does this code make my Number "save"?
Hey, it's difficult to write in the title what I want. So sorry, if the title doesn't make much sense ;) I wanted to create a variable or container that contains a number as a value. The value has to be a number and I want to get notified if it got changed. I came up with the following idea: const saveNumber = (function () { var numberValue = null; return { set value(value){ console.warn('Number was changed!'); if(typeof value !== 'number') { throw 'Value has to be a number!'; return; } numberValue = value; }, get value(){ return numberValue; } } })(); This leads to the following behaviour: saveNumber.value = 5; // "Number was changed!" saveNumber.value = "Strings don't work"; // throws 'Value has to be a number!' console.log(saveNumber.value); // 5 So in my opinion I created some kind of a "save" number or value. I call it saved since the value can't be manipulated directly or in other words without using the setter function. In addition it's save because I get notified as soon as the value gets changed. My question is: Does this code make sense and does it really lead to the above described behaviour? Or is the still a way to change the numberValue without using the getter function? Thank you!