if statement

Posted on
  • Can someone explain why the following if statement does not execute when I change the variable 'a' in the active command line?

    var a = 10;
    
    if (a != b) {
    	var b = a;
    	var c = 1;
    	var d = 1;
    	var e = 1;
    	var f = b+c+d+e;
    }
    

    I'm sure I had it working at some point but I forgot to save what I was doing!!!

  • I just tried this, and it worked. End result was:

    >dump()
    var a = 10;
    var b = 10;
    var c = 1;
    var d = 1;
    var e = 1;
    var f = 13;
    

    Which version of Espruino were you using? the one from the website, espruino-nightly, or your own build?

  • I get the same but I expected it to re-evaluate the if statement if I typed in var a = 20 in the active command line i.e. the black screen on the left using the Chrome app.

  • The command-line still evaluates everything in order, as you type it... The if statement won't evaluate again unless you tell it to.

    You could do something like:

    setInterval(function() {
     if (a != b) {
        var b = a;
        var c = 1;
        var d = 1;
        var e = 1;
        var f = b+c+d+e;
     }
    },100);
    

    And now, that code will keep being called every 100ms so if you write a=20, everything will update as you expect.

  • Okay, I would ideally like parts of code to execute when values change rather than on a timed basis. I'm sure I had it working earlier...

  • I'm afraid that's just not how JavaScript works. You could probably implement something with callbacks, but JavaScript wouldn't normally work like that.

    There's an online 'command prompt' type example here that uses your Web Browser's JS engine: http://www.jsconsole.com/

    It's an easy way to see what kind of things it can do.

  • Its weird because I'm absolutely sure I had something working before stupidly forgot to save my work.
    I have tried using a while statement instead but that doesn't seem to be working either.

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

if statement

Posted by Avatar for StuntMonkeh @StuntMonkeh

Actions