PDA

View Full Version : new Number()


enuenu
10-14-2007, 06:14 AM
Why when initiatializing a variable with a numeric value in JavaScript is a new Number object created? For example it seems that in JavaScript I am supposed to use;

var num= new Number(array[i]);

rather than what I would have initially thought, which is;

var num= array[i];


Both of the above seem to work, but I have been informed that my way is not correct.

Has it got something to do with the fact that you don't specify a type when creating variables in JavaScript?

BillyGalbreath
10-14-2007, 01:18 PM
I've never heard of this new Number() thing before. I've never used it and all my scripts work fine. Might be one of these personal preference type of things... All I know is that my scripts work just fine without it.

;)

coothead
10-14-2007, 02:14 PM
Hi there Billy,

I've never heard of this new Number() thing before


Here's the lowdown...
http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide:Predefined_Core_Objects:Number_Object
My reference book has this to say, which very much echoes what you said...

By and large, you don't have to worry about the Number object because a numerical value automatically
becomes a Number object instance whenever you use such a value or assign it to a variable.
On the other hand, you might want access to the static properties that only a Math major would love.

enuenu
10-15-2007, 05:58 AM
Thanks a lot. It was as I suspectedBy and large, you don't have to worry about the Number object because a numerical value automatically
becomes a Number object instance whenever you use such a value or assign it to a variable.I will try and convince those who tell me otherwise.

Jon Hanlon
10-18-2007, 07:04 PM
It's the same with strings:
var hi = "hi"
var hi = new String("hi")

From memory, the JS interpreter converts the first one to the second one internally.
This is so methods can be attached to primitive data types.
But!


var zero = 0;
var zilch = new Number(0);

if (zero) alert("zero"); //won't fire
if (zilch) alert("zilch"); //will fire


As zilch is technically a number object, we will see an alert.
Similarly

var isFalse = new Boolean(false);
if (isFalse) alert("isFalse"); // will fire

As will an empty String.

So it's best to stay away from primitive constructors!

BillyGalbreath
10-18-2007, 07:54 PM
var zero = 0;
if (!isNaN(zero)) alert("zero"); //will fire

;)


Question: Why would if (zilch) return true? I mean... Zilch is 0. 0 is false... so... shouldn't it read as if (false)? Which means it shouldn't fire... That's confusing as hell...