#javascript anomaly (what a surprise)

1 messages · Page 1 of 1 (latest)

wet crest
#

so i have here (simplified):

rank = 0, file = 5
for (i = 0; i < 8; i++) {
    console.log("" + (rank-i) + (file-i));
    console.log("" + (rank+i) + (file+i));
};

which returns

05 (expected)
0050 (what)

what is happening here?

wet crest
#

i did not hmmm

tacit tusk
#

Can you share some more code?

wet crest
#

not really sure what i could share that would add more context

tacit tusk
#

well, what you shared is working correctly, so there's something else causing the error.

#

Just share whatever you have

wet crest
#

seems to be happening only with the addition

#

wait would this result if 'rank' and 'file' are strings?

#

oooooh

#

lmao what a goofy language

#

thanks tho

warm anchor
#

The issue with the code is that the console.log statements are concatenating the values of rank-i and file-i, and rank+i and file+i, respectively, without any separator. This results in the values being concatenated together, instead of being printed as separate values.

To fix the code, you can add a separator between the values in the console.log statements. Here's an updated version of the code:

let rank = 0, file = 5;
for (let i = 0; i < 8; i++) {
    console.log("" + (rank-i) + "," + (file-i));
    console.log("" + (rank+i) + "," + (file+i));
};

In this version, a comma is added between the values in the console.log statements to separate them. This should produce the expected output:

0,5
0,5
-1,4
1,6
-2,3
2,7
-3,2
3,8
-4,1
4,9
-5,0
5,10
-6,-1
6,11
-7,-2
7,12
tacit tusk
heavy plume
wet crest
tacit tusk
wet crest
#

the code i posted was simplified and i didn't realise my mistake
addition on a string treats it as concatenation, while subtraction treats it as numerical subtraction