ThomasThomas H171 ThomasThomas H171 - 4 months ago 15
Javascript Question

Strange Javascript code displays wrong number

I've found this Javascript code on the internet, but I cannot figure out why it displays an unexpected number:

var foo = 5;
var bar = 7;
fоo = bar;
bar += +!(foo - 5);
console.log(foo = bar); // It displays 8 instead of 7


As I understand, we defined two variables
foo
and
bar
which have values
5
and
7
respectively. After that, we copy value from
bar
to
foo
. On the fourth line,
bar
is not incremented, because
+!(7 - 5) == +!2 == +false == 0
. On the last line, value from
bar
is again copied to
foo
and then displayed, which means that
foo
must be
7
. But, why console logs
8
instead?

Answer

The line fоo = bar; actually assigns the value of bar to a newly created global variable fоo — that’s Latin lower-case F, Cyrillic lower-case letter O and Latin lower-case O.

If you replace fоo = bar; by foo = bar; (actually copy paste it), it’ll work as expected.

You can debug this yourself by experimenting with the code in the console and ultimately by typing this in the console:

"fоo = bar;".split("").map(function(a){
  return a.charCodeAt(0);
});
/*
** Returns:
** [
**   102,  // "f"
**   1086, // "o"? This seems suspicious!
**   111,  // "o"
**   32,   // " "
**   61,   // "="
**   32,   // " "
**   98,   // "b"
**   97,   // "a"
**   114,  // "r"
**   59    // ";"
** ]
*/