jeudi 28 février 2019

why is outer variable not available in if conditional

    function NumStuff(num) {
    this.num = num;
    this.multipleOfFour = function () {

        //if multiple of 4
        if (this.num % 4 === 0) {
            console.log(this.num + " is a multiple of Four");
            console.log("the structure of the given integer " + 
                        this.num + " is ");

            for (let i = 0; i < this.num; i++) {
                if (4 * i === this.num) { //why is this.num outside of 
                                          //lexical scope
                    console.log(this.num + " = " + i + " x 4");
                    break;
                }
            }
            //if not a multiple of 4
        } else {
            console.log(this.num + " isn't a multiple of 4 but here is the integer's structure:");
            let remainder = this.num % 4;
            let tempNum = this.num - remainder;
            for (let i = 0; i < tempNum; i++) {
                if (4 * i === tempNum) {
                    console.log(this.num + " = " + i + " x 4 + " + remainder);
                    break;
                }
            }
        }
    };
}

let num = prompt("Enter an integer:");
let n = new NumStuff(num);
n.multipleOfFour();

Say we enter 20 as our num. It passes through the multipleOfFour() and hits the first if conditional. This.num(20) % 4 is equal to 0 so it passes.Then we loop through i to find what number times 4 is equal to 20. This.num is in the scope of the for statement but not in the scope of the inner if conditional of the for statement. Why is that so?

Aucun commentaire:

Enregistrer un commentaire