Jackal21
Jackal21

Reputation: 27

Does the if false statement always return undefined in javascript?

I am currently developing a website and plan on using JavaScript.

function func() {
    if (false) {
        var a = 'goodbye';
    }
    console.log(a);
}

This above example shows scope and I would like to know how you would prevent this coming out undefined and why this would be the case.

I've researched mdn, w3 schools and varius sites but they are either to specific or too general.

It would be great for people who use JavaScript regularly but are not the team leads to have this resource - and I plan to use this knowledge to make a web page using front end languages (JavaScript, html, CSS, etc.)

online-editor

Please feel free to add more tags if appropriate!

Upvotes: 0

Views: 813

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1075567

The reason you're seeing undefined when the condition in that if is false is that var is hoisted to the top of the function and variables get undefined as their default value.

After hoisting, your code is this:

function func() {
    var a; // Defaults to `undefined`
    if (false) {
        a = 'goodbye';
    }
    console.log(a);
}

Since the condition is false, a's default value is never changed.

More about var hoisting on my anemic little blog: Poor misunderstood var

Upvotes: 6

Amar Pathak
Amar Pathak

Reputation: 130

You are confused with how if statement works,

if(Condition comes out to true)
{
 This will work
}

Other wise it will not work, you have entered Condition to be false by default so the if block is not executed. And as you have defined "a" inside the if block, the variable "a" is never getting defined as the if block is not executed . thus you are getting undefined when you are logging a

Upvotes: 0

Related Questions