while iam using the += operator the multiplication results in NaN
convertToDecimal(){
let current=this.head;
let size=this.size;
size-=1;
var result;
while(current!=null){
let num=current.value;
var power=Math.pow(2,size)
result=(power*num);
size-=1;
current=current.next;
}
// console.log(result);
}
**console without putting += for result
value of result in each iteration
8
4
2
1
but afer i puts +=
result+=(power*num);
output is
NaN
NaN
NaN
NaN
Anyone can explain this please, I am new to javaScript so may be its a dumb question
This happens because your result
variable has no initial value and so it starts as undefined
. The first time you then execute +=
, it tries to add a number to undefined
which results in NaN
.
Your problem can be reproduced with this simplified code:
var result;
for (let i = 0; i < 4; i++) {
result += 1;
console.log(result);
}
So initialise as var result = 0
.
var result = 0;
for (let i = 0; i < 4; i++) {
result += 1;
console.log(result);
}