0

Why extending Number prototype works for 1.2 but not for 1?

Number.prototype.to_s = function () {
  return "" + this
}

console.log(1.2.to_s())
console.log(1.to_s())
Uncaught SyntaxError: Invalid or unexpected token
Alex Craft
  • 13,598
  • 11
  • 69
  • 133
  • 5
    `console.log((1).to_s())`, it's a basic syntax issue, the `.` is taken to be a decimal point and part of a numeric constant. – Pointy Jul 21 '21 at 16:02
  • Extending the prototype works for both `1` and `1.2` and both are of the type `Number`. But whenever you see a `SyntaxError` then the syntax of your code is not correct and this means that your code does not run at all. – t.niese Jul 21 '21 at 16:11

1 Answers1

1

When there is a . in the end it is a part of the number.

You can use double dots to get past your issue for 1.

Number.prototype.to_s = function () {
  return "" + this
}

let y = 1.2; // no issues;
let x = 1.; //no issues
console.log(x,y);

console.log(1..to_s());
console.log(1.2.to_s());

Also, there is a slight color difference in the two dots in the code snippet itself. So code editors also are pointing you towards the right syntax.

Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39