Brandon
Brandon

Reputation: 1195

how to scope try declarations to the finally block also?

Is there a way that I can get age to be defined in the finally block without using the var keyword? I haven't found a way to do this which I feel is a bit odd so I'm assuming there is a way.

try{
    let age=prompt("What is your age?");
    if(age<=0){
        throw new Error("Your age can not be " + age + " please type your real age.");
    }
    else if(typeof age==="string"){
        throw new Error("What is not a number please type a number");
    }
    else if((age % 1) != 0){
            throw new Error("Please type an whole number");
    }
}
catch(e){
    console.log(e)
}
finally{
    parseInt(age);// age come up as undefined
}

Upvotes: 0

Views: 57

Answers (1)

Bergi
Bergi

Reputation: 664484

There's no reason to put the prompt inside the try, just declare the variable outside of it. You can still use a block for local scoping if you want.

{
    let age =prompt("What is your age?");
    try {
        …
    } catch(e) {
        console.log(e)
    }
    console.log(parseInt(age));
}

Upvotes: 1

Related Questions