JavaScript | Sololearn: Learn to code for FREE!
¡Nuevo curso! ¡Todo programador debería aprender IA Generativa!
Prueba una lección gratuita
+ 2

JavaScript

what is the output of this code? alert(-"1"+1+"2"); // answer is 02 Does anyone know how it came to be 2?

8th Sep 2020, 7:01 AM
S.P. Karthee
S.P. Karthee - avatar
2 Respuestas
+ 4
Hello!! [-"1"]+1+"2" : the interpreter converted "1" to 1 because it was preceeded by -, so it was -1. Now it is [-1+1]+"2": you know -1+1 is 0; [0+"2"]: this is sum between an integer and a string , 0 was converted to "0"(because i think alert() need strings ) ,so we have now "0"+"2" which is a simple concatenation , the result was "02". The end!!
8th Sep 2020, 7:12 AM
CHERIEF Houcine Abdelkader
CHERIEF Houcine Abdelkader - avatar
+ 2
This is the problem with languages wchich does not have fixed type of a variable. Then you cannot remember it how it works respectively should work.
8th Sep 2020, 7:14 AM
JaScript
JaScript - avatar