1

I was investigating one problem where content of web page is not getting loaded in Safari, on further investigation it was found that it is because of variable scope (const vs var).

if (1 == 1) {
  const a = 1;

  function f() {
    console.log(a);
  }
  f();
}

Error:

Can't find variable: a

With variable type as const was getting error in Safari browser and all browser in Iphone, And it was working in all other browser except Safari on desktop.

After changing it to var it has solved the issue. But still not able to find the justification why with const it was not working in Safari.

What is correct behaviour for const?

Barmar
  • 741,623
  • 53
  • 500
  • 612
Ravi
  • 719
  • 8
  • 23
  • @Barmar ReferenceError: Can't find variable: subscribeAbleEvents when i use const – Ravi Apr 15 '22 at 01:15
  • I can't think of any reason why it wouldn't work. `const` has been fully supported since Safari 11, and before that it worked partially (it had function scope). But maybe it's a weird incompatibility between the function scope of `function` and the block scope of `const`. – Barmar Apr 15 '22 at 01:19
  • It sounds like a Safari bug to me. Can you create a [mre]? – Barmar Apr 15 '22 at 01:20
  • Currently, I was debugging one of the production issues, where it was not working in safari in. I will try to reproduce it with small example. To add more context, this method window.addEventListener("message", onNewPostMessageFromChild, true); is a mesage listner from child iframe inside page – Ravi Apr 15 '22 at 01:24
  • I don't think it should matter what the event is listening for. It probably has something to do with defining a function inside `if` and that function refers to a `const` variable declared in the same block. – Barmar Apr 15 '22 at 01:26
  • @Barmar similar issue https://stackoverflow.com/questions/70367435/safari-cant-find-global-const-variable-used-in-function-cant-find-variable-er – Ravi Apr 15 '22 at 01:27
  • 1
    I've replaced your code with a simpler test case based on that other question. – Barmar Apr 15 '22 at 01:36
  • @Barmar Now this looks like a bug with Safari, Should we file this to Safari? – Ravi Apr 15 '22 at 01:37
  • Take a look at the duplicate question first. – Barmar Apr 15 '22 at 01:38

0 Answers0