2

I was testing a function out to see what happens when it's parameters are null and decided to put an else statement with it. To my surprise, it did not log the parameters that I have passed, it's logging something else entirely. Maybe someone can shed some light on this, here's the code:

function testing(o) {
    if (!o) {
        return "Sorry, looks like you need to pass an argument.."
    } else {
        return o;
    }
}

console.log(testing(02034));
//logs 1052

What's going on here?

2
  • It has to do with the number you put in. It started with a 0 which is in base 8. Commented Jun 21, 2012 at 0:48
  • This question is similar to: What happens when a number has a leading zero?. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Oct 14 at 15:08

3 Answers 3

8

In Javascript, like other languages, starting a number with 0 would indicate it's base 8 (Octal).

Thus, 02034 in base 8 = 1052 in base 10 (decimal).

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

3 Comments

it's the system of counting we'd use if we arbitrarily had 8 fingers instead of 10 :)
@JeremyWeir That makes sense. Also, this answer helped me, will be accepting once I can.
Run it though parseInt as a string with the second parameter indicating its base (I assume you're talking about user input)? e.g. parseInt("0123", 10) = 123 but parseInt("0123") = 83.
3

The leading "0" is causing JavaScript to read the value as an Octal number. When you print it to the console, it is being converted back to it's decimal representation.

3 Comments

It's not fair, the ellapsed time between the answers is not that much, could be that @Jay just answered firts
@h3nr1x - Answering questions in Stack Overflow is like a race - The faster, the winner. :/
@h3nr1x it was a 5 minute difference on a simple paragraph answer. We can rule that option out
2

That notation is called an octal integer literal

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.