+ 2

In JavaScript? Why Str and Int confusion?

When I try document.write(‚Äú2‚ÄĚ + ‚Äú2‚ÄĚ); It outputs 4 Why?? Same... var int = 3; var str = ‚Äúhiya‚ÄĚ; document.write(int * str); Why doesn‚Äôt it output hiyahiyahiya But instead gives me NaN?

21st Mar 2019, 7:01 PM
Brave Tea
Brave Tea - avatar
4 Respostas
+ 2
i don't really now this, but it seems that js converts the strings to int, if you multiply them, and returns them as int. When the result can't be an int, it will become NaN tests: document.write(2*3); //6 document.write("\n"); document.write(2*"3"); //6 document.write("\n"); document.write("2"*3); //6 document.write("\n"); document.write("2"*"3"); //6 document.write("\n"); document.write("hi"*3); //NaN document.write("\n"); document.write("hi"*"3"); //NaN document.write("\n"); document.write(3*"hi"); //NaN document.write("\n"); document.write("3"*"hi"); //NaN document.write("\n");
21st Mar 2019, 9:16 PM
Anton Böhler
Anton Böhler - avatar
+ 1
sorry I made a mistake in my first bit. document.write(‚Äú2‚ÄĚ * ‚Äú3‚ÄĚ); outputs 6 and I dont understand why
21st Mar 2019, 8:04 PM
Brave Tea
Brave Tea - avatar
+ 1
why is int an invalid variable? is int forbidden? see this code as a similar example: var test1 = 3; var test2 = "hiya"; document.write(test1 * test2); //output NaN
21st Mar 2019, 8:06 PM
Brave Tea
Brave Tea - avatar
0
://First of all document.write("2"+"2") output is not "4", it is 22 because they are between quotes, which makes them string ://Second var int is invalid variable, you don't need describe in int, str for numbers and strings
21st Mar 2019, 7:12 PM
Sudarshan Rai
Sudarshan Rai - avatar