Search code examples
javascriptvariablesconditional-statementstypeof

Variable defined inside conditional not available outside


I know this is super basic but I cannot figure out why it is not working. I was expecting to see the element .basic_form logged in the last console.log. Instead I get the following:

if ( typeof basic_form === 'undefined' || basic_form === nulll ){
        console.log( 'not defined yet' );
        let basic_form = document.querySelector( '.basic_form' );
        console.log( basic_form) ;
    }
    console.log( basic_form );

Output:
1> not defined yet
2> the element .basic_form
3> Uncaught ReferenceError: basic_form is not defined (???)

Any insights would be greatly appreciated!


Solution

  • Variable declared inside block are not accessible outside. You can find more on this Variable scope and closure.