Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is the resulting out put of console.log(Object +1) is like this?

why is the out put of

console.log(Object +1)

is

function Object() {
    [native code]
}1

i tried it and expext a numeric value as the + description :

  • If one side is a string, the other operand is also converted to a string and they are concatenated.
  • If they are both BigInts, BigInt addition is performed. If one side is a BigInt but the other is not, a TypeError is thrown.
  • Otherwise, both sides are converted to numbers, and numeric addition is performed.
like image 909
Zyad Avatar asked Jan 01 '26 19:01

Zyad


1 Answers

In this case, JS calls Object's toPrimitive method, which gives the following string:

function Object() {
    [native code]
}

In the next step, JS converts 1(number) into the "1"(string), as the first operand is a string, after that it's just a concatenation of two strings that results in:

function Object() {
    [native code]
}1

Here is the link for a detailed explanation.

like image 188
Artur Minin Avatar answered Jan 03 '26 09:01

Artur Minin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!