Beginner Question Please Help

Beginner Question Please Help
0

#1

Why use “+=” here and not just “=” ?

function fun2() {
var output = “”;
if (typeof myGlobal != “undefined”) {
output += "myGlobal: " + myGlobal;
}
if (typeof oopsGlobal != “undefined”) {
output += " oopsGlobal: " + oopsGlobal;
}
console.log(output);
}


#2

+= is used when you are concatenating existing string. In this case it was declared before if statements.

If output variable holds another string already, it will add onto it. However if you use =

Instead of adding onto it, it will just completely replace it.


#3

“=” is the assignment operator. As the name suggests, “=” assigns the value on the right side of it to the variable on the left side of it. When “=” is preceded by an arithmetic operator (+, -, %, /, etc), it changes the implementation of assignment slightly. For example:

x = y; //This assigns the value of variable y to the variable x
x += y; //This expands as x = x + y
/* The above code computes the sum of x and y using the 'current' values of
the variables x and y, then it assigns it to the variable x, thus replacing its
previous value that was used to compute the sum with the sum itself */

When ‘+’ is used in the context of strings, i.e. both or atleast one of the variables is a string, then the operator performs string concatenation. Similarly, ‘+=’ in the context of strings performs a string concatenation and assignment operation.
In the code you posted, the variable ‘output’ is initially an empty string. After the execution of the first if statement, the value on the right side (‘myGlobal: valueOfmyGlobal’) is concatenated with the value of output which is currently an empty string, making the new value of output ‘myGlobal: valueOfmyGlobal’. Till this point there is no difference in the value of output whether you use string concatenation (+=) or plain assignment (=). But after the execution of the second if statement, the value of output changes depending on whether you used ‘=’ or ‘+=’.

If you used plain assignment (=), then the ‘current’ value of the variable output (‘myGlobal: valueOfmyGlobal’) will be replaced by (‘oopsGlobal: valueOfoopsGlobal’), thus making the final value of output that is printed ‘oopsGlobal: valueOfoopsGlobal’.

On the other hand if you use ‘+=’, the value ‘oopsGlobal: valueOfoopsGlobal’ will be concatenated with the ‘current’ value of output and then assigned to the variable output, thus replacing the ‘previous’ value of output (myGlobal: valueOfmyGlobal). In this case the final value of output that is printed will be ‘myGlobal: valueOfmyGlobal oopsGlobal: valueOfoopsGlobal’.

If you still have trouble understanding the concepts involved, you can use the references below as guides:
Assignment operators (MDN)
Javascript operators (W3S)

Hope this helps you.


#4

Oh I see now. Thank you so much!!