1

Is an empty JavaScript array considered a string? When I try to do an increment operation on an empty array it returns "1". I am also curious why it doesn't run the catch block.

let x=[]

try {
  x=x+1 
} catch(err){
  console.log(err)
}

console.log( typeof x, x);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
bfmcneill
  • 125
  • 13

1 Answers1

2

The + operator coerces the array and the number to a string first. This calls toString on the array, which calls join without any arguments, resulting in "". The result of concatenating "" and "1" is "1".

Unmitigated
  • 76,500
  • 11
  • 62
  • 80