Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript (nodejs) while loop bug

running the following code in nodejs cli:

var my_function = function() {                                                                                              
    var next_value = 1
      , value = undefined
      , difference = undefined                                                                                              
      , prev_difference = undefined                                                                                         

    while ((typeof prev_difference === 'undefined') || (prev_difference > 0)) {                               
        value = next_value 
        next_value = 2
        difference = next_value - value 
        if (difference > prev_difference) {                                                                                 
              throw new Error('Diminishing')
        }                                                                                                                   
        prev_difference = 0 
    }                                                                                                                       
    return next_value 
}              

for (var i = 0; i< 300; i++) { console.log(i); console.log(my_function()) }

At iteration 282 of the loop I start getting the value '1' instead of '2'. Can't for the life of me understand why. This chunk of code is a reduction from something else I've been working on, hence the seemingly unnecessary if statement within the loop. There are a few ways to change this code such that the execution path does not get screwed up, but I'd like to understand why it's breaking with the current setup.

Also, if you have any tips for tools that could aid me in debugging something like this in the future I would be very grateful. For the most part I used console.log to narrow this down.

node.js version v0.8.6. Running on Mac OSX version 10.7.5. Thanks

like image 572
user1797466 Avatar asked Nov 04 '12 03:11

user1797466


1 Answers

If you take out the IF statement it is gonna be fine, it will return only '2' on every iteration. The variable prev_difference is 'undefined' every time and this seems to cause issues.

like image 198
Sergiu Nicuta Avatar answered Sep 27 '22 02:09

Sergiu Nicuta