Search code examples
javascripttype-conversionconventions

Javascript variable declaration and number conversion


I was curious in this example why the declare the variables first. then the next line they define what the variable is. Is there a reason for this?

could you not just say

 var message = document.GetElementById("message").innerHTML;

and why do they declare Number(x) in the middle of the if statments? If you put it before the other if statments, would it take a string and convert it to a number?

javascript:

<script>
function myFunction() {
    var message, x;
    message = document.getElementById("message");
    message.innerHTML = "";
    x = document.getElementById("demo").value;
    try { 
        if(x == "")  throw "empty";
        if(isNaN(x)) throw "not a number";
        x = Number(x);
        if(x < 5)    throw "too low";
        if(x > 10)   throw "too high";
    }
    catch(err) {
        message.innerHTML = "Input is " + err;
    }
}
</script>

trying to understand why its written like this.


Solution

  • By convention, variables are often declared together at the top of a function, when they can be, so that that all their names are obvious. I think JSHint and JSLint enforce this by default, for example.

    The second 2 if conditionals are done after x is converted to a number, in case it was a string. If the variable was for instance the string "3" rather than the number 3, before conversion by Number(x), then if(x < 5) would be comparing a number to a string. If it were done before all of the conditionals, it might throw an error, if it were empty, or undefined or the letter s, for example.