javascriptsafariscopemobile-safari

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.


Solution

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

    Enable strict mode will solve this problem.