Javascript Declaring Number In Different Ways?
Solution 1:
A value like 1
is a primitive, not an object. JavaScript will generally promote numbers to Number
objects when necessary. There's rarely a reason to explicitly construct one, and there's certainly no particular "advantage". There's also no reason for something like Number(1)
, though the Number
constructor is one of several ways of coercing a value to be a number.
Solution 2:
In short, non: the new String()
and new Number()
constructors are to be ignored if you want to save yourself a world of trouble. The first two methods you present here assign a numeric constant to the variable, the third way -as you say- creates an object. The value of that object will be 1
, but you can change that value without loosing any specific methods you set to the object.
There aren't very many advantages to storing numbers or strings in objects. AFAIK, the only thing you "gain" is a very, very, very slight performance difference over the constants when invoking certain methods, like toExponential
etc... In my view, that isn't worth the trouble of creating objects for all numbers you're bound to use. I think of it as one of the bad parts of JS, meant to make the language look familiar to Java Applet developers.
The second, without the new keyword, allows you to sort-of-type-cast: Number(document.getElementById('formElem').value) === 123;
and has its uses (mainly with Date objects, in my experience). But then again, converting to a number can be achieved using the +
operator, too: +document.getElementById('formElem').value) === 123
On the whole, just stay well clear of these primitive constructors. The only reason they're still there is because they're objects, and therefore have prototypes. Now THAT is an advantage:
Number.prototype.addOneToString = function()
{
return (1+this).toString();
};
String.prototype.UpperFirst = function()
{
returnthis.charAt(0).toUpperCase() + this.slice(1);
}
var foo = newNumber(3);
foo.addOneToString();//returns "4"
foo = newString('foo');
foo.UpperFirst();//Foo
Since JS wraps constant operands in an instance of its object counterpart, when the statement requires it, you can apply prototype methods (either native or self-made ones) to any constant. (Thanks to Pointy for this, and +1)
(3).addOneToString();//"4"'foo'.UpperFirst();//Foo
So just regard them as legacy quirks, that are still there because of their prototypes.
Solution 3:
In ES12 and after you can use the below ways to declare large numbers.
const oneMillion = 1_000_000;
var oneMillion1 = 1_000_000;
you can use separators _
, for bitter readability
Post a Comment for "Javascript Declaring Number In Different Ways?"