0

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

ABIN
  • 29
  • 5
  • Could you edit your question and introduce a runnable snippet (using the toolbar button), so that the instance of your linked list is initialised and running the code reproduces the NaN outputs? – trincot Jan 27 '23 at 17:26

1 Answers1

2

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);
}
trincot
  • 317,000
  • 35
  • 244
  • 286