DOM commands are ignored when processing a function as values?

I am new to JS and programming in general. I teach myself casually and just for fun! Take a look at this:

var a=0;
var b=0;

function test(){
  a++;
  b++;
  document.body.innerHTML+=a+" "+b;
  return 42;
}

$("document").ready(function(){
  test();
});

This (as expected) outputs

1 1

And the return value seems pointless when you just run the function. If, on the other hand, I change it so that it reads ...

$("document").ready(function(){
  document.body.innerHTML+=test()+" "+a+" "+b;
});

This produces:

42 1 1

This means that β€œvar a” was incremented, and β€œvar b” was incremented, and 42 was returned as the value of test (), but the DOM part of the test () was ignored. Why is this? Is something else being ignored? Thank.

+4
source share
1 answer

It really comes down to what it means +=?

x += y;
// same as
x = x + y;

So

document.body.innerHTML += test() + " " + a + " " + b;
// same as 
document.body.innerHTML = document.body.innerHTML + test() + " " + a + " " + b;
//               X                         Y

, document.body.innerHTML Y , test(), , test, Y.

+5

Source: https://habr.com/ru/post/1530839/


All Articles