Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is javascript variable not changed across all the external JS files [closed]

Variable a is decared in the main file. Then a.js and b.js included. JS files have following content.

a.js:

a+=100;

b.js:

a=+200;

And the main file:

<script type="text/javascript">
     a=30;
</script>
<script type="text/javascript" src="js/a.js"></script>
<script type="text/javascript" src="js/b.js"></script>
    a+=90;
    console.log("a = " + a);
</script>

Console shows a=290. Why is a not 420 (i.e. 30+100+200+90 ) ? why doesn't a change across both a.js and b.js?

like image 618
Istiaque Ahmed Avatar asked Dec 25 '22 00:12

Istiaque Ahmed


2 Answers

You wrote the += operator backwards. Written as =+ the + is being interpreted as the unary + operator; in other words, you're explicitly assigning "positive 200" to the variable (in "b.js").

like image 71
Pointy Avatar answered Apr 14 '23 18:04

Pointy


You have a typo with a =+ 200; This assigns the global variable a the value 200.

I believe you meant a += 200;

like image 34
Austin Wang Avatar answered Apr 14 '23 16:04

Austin Wang