Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only in Safari: ReferenceError Can't find variable

Many of my scripts look like this:

if (...) {

    const myvariable1 = document.querySelector('.class-1');
    const myvariable2 = document.querySelector('.class-2');

    function someFunction() {

        // Do something with myvariable1 or myvariable2

    }

    someFunction();

}

They work fine on Chrome, Firefox, Edge and Opera but on Safari I get the error:

ReferenceError: Can't find variable myvariable1

Workaround

If I declare the constants before the if statement the code works...

const myvariable1 = document.querySelector('.class-1');
const myvariable2 = document.querySelector('.class-2');

if (...) {

    function someFunction() {

        // Do something with myvariable1 or myvariable2

    }

    someFunction();

}

...but I don't understand why and I don't what to make the constant globally available.

Maybe someone can explain to me that Safari-only-behavior.

like image 725
Sr. Schneider Avatar asked May 21 '26 02:05

Sr. Schneider


1 Answers

This weird behaviour is explained in Block-level functions in non-strict code - MSN.

Enable strict mode will solve this problem.

like image 53
andylizi Avatar answered May 23 '26 16:05

andylizi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!