Sethen
Sethen

Reputation: 11348

Javascript returning strange value

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?

Upvotes: 3

Views: 231

Answers (3)

Ben Ripley
Ben Ripley

Reputation: 2145

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.

Upvotes: 3

JeremyWeir
JeremyWeir

Reputation: 24368

That notation is called an octal integer literal

Upvotes: 2

Jay
Jay

Reputation: 3305

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).

Upvotes: 8

Related Questions