Mukhammad Sobirov
Mukhammad Sobirov

Reputation: 27

What's the difference between "number" and Number in javascript when iterating over an object?

here's an object.

let menu = {
  width: 200,
  height: 300,
  title: "My menu"
};

that's the right code

function multiplyNumeric(obj) {
  for (let key in obj) {
    if (typeof obj[key] == 'number') {
      obj[key] *= 2;
    }
  }
}

and here's my code

function multiplyNumeric(obj) {
      for (let key in obj) {
        if (typeof(obj[key]) === Number) {
          obj[key] *= 2;
        }
      }
    }

Please tell me what makes the difference?

Upvotes: 0

Views: 327

Answers (4)

dinesh sonawane
dinesh sonawane

Reputation: 26

The Number() is Javascript function converts the object argument to a number that represents the object's value. If the value cannot be converted to a legal number, NaN is returned.

typeof(obj[key]) function returns, what kind of type the value is, like 'number' and string etc

Upvotes: 0

Tim567
Tim567

Reputation: 815

As Jonas Høgh pointed out Nummer is a JavaScript function

A quick examlple of understanding the Number function:

console.log(Number(true));
console.log(Number(false));
console.log(Number(new Date()));
console.log(Number("999"));

Upvotes: 0

Ilijanovic
Ilijanovic

Reputation: 14904

The difference is that 'number' is an string and Number is an build-in function.

console.log(typeof "number") //string
console.log(typeof Number) //function

Upvotes: 1

Jonas Høgh
Jonas Høgh

Reputation: 10874

The typeof operator returns a string containing the name of the type of the operand. Number is a function that converts its input to a number.

Upvotes: 3

Related Questions