0

I have this function (going trough the Eloquent Javascript Tutorial chapter 3):

function absolute(number) {

  if (number < 0)
  return -number;
  else
  return number;
}

show(absolute(prompt("Pick a number", "")));

If I run it and enter -3 the output will be 3 as expectet but if I enter just 3 the output will be "3" (with double quotes). I can get around by changing

return number;

to return Number(number);

but why is that necessary? What am I missing?

2
  • @mgraph: Try parseInt("042") Commented Feb 27, 2012 at 19:44
  • @NickBeranek: It's octal. You need to force it to parse as decimal by adding , 10 Commented Feb 27, 2012 at 19:49

4 Answers 4

2

prompt() always returns a string, but when you enter a negative number, it is handed to the -number call and implicitly converted to a Number. That doesn't happen if you pass it a positive, and the value received by prompt() is returned directly.

You can, as you discovered, cast it with Number(), or you can use parseInt(number, 10), or you could do -(-number) to flip it negative, then positive again, or more obviously as pointed out in comments, +number. (Don't do --number, which will cast it to a Number then decrement it)

Sign up to request clarification or add additional context in comments.

1 Comment

@SLaks Indeed, Overcomplication is my middle name.
1

Javascript is not strongly typed.

number comes from the prompt() function, which returns a string.
Since you aren't doing anything to change its type, it remains a string.

-number implicitly converts and returns an actual number.

Comments

1

If you have a string that needs to be converted to a number, please do the following:

var numString = '3';
var num = parseInt(numString);
console.log(num); // 3

Comments

0

JavaScript performs automatic conversion between types. Your incoming "number" is most likely string (you can verify by showing result of typeof(number)).

- does not take "string" as argument, so it will be converted to number first and than negated. You can get the same behavior using unary +: typeof(+ "3") is number when typeof("3") is string.

Same happens for binary - - will convert operands to number. + is more fun as it work with both strings "1"+"2" is "12", but 1+2 is 3.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.