Many of my scripts look like this:
JavaScript
x
15
15
1
if ( ) {
2
3
const myvariable1 = document.querySelector('.class-1');
4
const myvariable2 = document.querySelector('.class-2');
5
6
function someFunction() {
7
8
// Do something with myvariable1 or myvariable2
9
10
}
11
12
someFunction();
13
14
}
15
They work fine on Chrome, Firefox, Edge and Opera but on Safari I get the error:
JavaScript
1
2
1
ReferenceError: Can't find variable myvariable1
2
Workaround
If I declare the constants before the if statement the code works…
JavaScript
1
15
15
1
const myvariable1 = document.querySelector('.class-1');
2
const myvariable2 = document.querySelector('.class-2');
3
4
if ( ) {
5
6
function someFunction() {
7
8
// Do something with myvariable1 or myvariable2
9
10
}
11
12
someFunction();
13
14
}
15
…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.
Advertisement
Answer
This weird behaviour is explained in Block-level functions in non-strict code – MSN.
Enable strict mode will solve this problem.