0

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!

Mauricio
  • 51
  • 4

2 Answers2

2

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

MORÈ
  • 2,480
  • 3
  • 16
  • 23
0

basic_form it's defined inside the if statement you need to define it outside. I think it should be like this.

let basic_form = document.querySelector( '.basic_form' );

if ( typeof basic_form === 'undefined' || basic_form === nulll ){
        console.log( 'not defined yet' );
        console.log( basic_form) ;
    }
console.log( basic_form );
Said Taher
  • 51
  • 3
  • Yes, that would work. And although, this would be a different question, my issue is that these pages are ajax loaded, and can be loaded multiple times, so doing it this way, I get another error, saying the variable has been already defined. – Mauricio Apr 11 '22 at 18:58