lakenney
lakenney

Reputation: 89

JavaScript typeof Operator-Number vs String

In the example typeof (3 + 4); returns number. Then the example typeof (3 + 4) + 1; returns number1.

So instead of adding it to 7, it treats the + 1 as a string but says it's a number?

I find this confusing. Can someone enlighten me?

Upvotes: 0

Views: 138

Answers (3)

NullPointer
NullPointer

Reputation: 7368

The typeof operator returns a string indicating the type of the unevaluated operand.

Syntax

The typeof operator is followed by its operand:

typeof UnaryExpression

Parameters

operand is an expression representing the object or primitive whose type is to be returned.

The parentheses are optional.

In 1st Case[typeof (3 + 4)]: 3+4=7 and this is a number type so it giving output as Number

In 2nd Case[typeof (3 + 4)+1]: 3+4=7 and this is a number type so Number+1(just string concatenation) is giving output as Number1

console.log(typeof (3 + 4));
console.log(typeof (3 + 4)+1);

Upvotes: 1

Luca Kiebel
Luca Kiebel

Reputation: 10096

typeof (3 + 4); returns "number", a String, adding a Number to a String will just append the number to it, meaning

typeof (3 + 4) + 1; is essentially "number" + 1 which is "number1"

And, yeah, typeof 1 + (3 + 4); will add the sum of 3 and 4 to typeof 1 and then return "number7"

Upvotes: 1

brk
brk

Reputation: 50291

In the second case + acting as a string concatenation. So typeof (3 + 4) gives number & + contact number & 1 that is why it is number1

Upvotes: 1

Related Questions