I understand why CODE A returns a sequence of numbers (that's the loop process), but why is CODE B returning a summation?
// CODE A:
let counter = '';
let i = 1;
do {
counter = counter i;
i ;
} while (i < 15);
console.log(counter);
//1234567891011121314
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
// CODE B:
let counter = 4;
let i = 1;
do {
counter = counter i;
i ;
} while (i < 15);
console.log(counter);
//109
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
In Code A you initialized your counter variable with a string and when you use operator with strings in javascript it concats them. https://www.w3schools.com/jsref/jsref_obj_string.asp
In Code B you initialized your counter variable with the number and in the case of numbers, the operator will add instead of concatenating.
You need to study the basics of data types in javascript.
CodePudding user response:
in code A you are using counter as a string and the variable i is been added at the end of the string that means you will get a output of 12345.. in string whereas, in code B you are using counter as a integer so you are adding a integer in a integer so the correct code will be.
// CODE A:
let counter = "";
let i = 1;
do {
counter = counter i;
i ;
} while (i < 15);
console.log(counter);
// 1234567891011121314
// CODE B:
let counter = "4";
let i = 1;
do {
counter = counter i;
i ;
} while (i < 15);
console.log(counter);
// 41234567891011121314
CodePudding user response:
In code A you initialized one of your variable(counter) as a character variable. If you add a character with an integer, in that case the result will act as a character variable. You can see an example from w3schools.
On code B you declared both variables as integer. So, they are behaving like integer variables does. In this case they are summing their values.
These are root javascript knowledge but very useful in many way.