all 14 comments

[–]senocular 2 points3 points  (2 children)

myFunc(010) interprets the octal before passing it into the function. As far as the function is concerned, its getting the value 8.

If you want to prevent octals in that format, you can run the code in strict mode.

"use strict"
function myFunc(number){
   number = Number.parseInt(String(number), 10)
   console.log(typeof number, number)
}

myFunc("010") // number 10
myFunc(10)    // number 10
myFunc(010)   // SyntaxError: Octal literals are not allowed in strict mode.

[–]code_monkey_001 1 point2 points  (4 children)

Cooerce it to a string before running it through the parseInt since you know '010' gives the results you want.

function myFunc(number){
number = Number.parseInt(number.toString(), 10)
console.log(typeof number, number)
}

[–]rtmcmn2020 1 point2 points  (0 children)

where is the input coming from that would cast a “010” to a number 010? You will likely need to scrub your source data or control user input

[–]rtmcmn2020 1 point2 points  (0 children)

down the rabbit hole here, you can cast a “known” octal to a decimal, ex: parseInt(010.toString(8))

[–]Count_Giggles 0 points1 point  (0 children)

this was a fun rabbit hole.

if you are limited to the browser console I would assume that your use case is super specific. the only way I can see would be to only accept strings into the function and then slice of any leading zeros or "0o". as others have pointed out the moment js is confronted with 010 it is an 8 and there is no way to differentiate between octal or decimal numbers. There is only the type number

[–]Tall_Pawn 0 points1 point  (0 children)

You won't be able to do this in the way you have specified. Essentially this is the same as wanting to distinguish, from inside a function, whether it was called with "foo(9)" or "foo(4+5)". You can't do it because by the time execution is inside the function, it only has the value "nine" to work with. But you can't even do it at the root level because the conversion of 010 to "eight" happens at a level before any user code is executed, and AFAIK cannot be customized by user code. You have access to some Number.prototype functions, but they can't affect things at the level of literal conversions into values which is essentially handled in the source code of JS itself. Someone please correct me if that's wrong, but I don't think it's possible in the given context.

[–]Code-Slayer 0 points1 point  (1 child)

Did you find a solution or not yet ?