0

I've tried this in Chrome, Opera, Microsoft Edge, Internet Explorer and Mozilla Firefox and still gotten the same case: A ReferenceError exception is not thrown that the variable I assigned a value is not defined.


The syntax is:

// Where `identifier_name` was not formally declared/ initialized.
(function() {})(identifier_name = 2)

Why does this behavior occur?

Edit: Just to add, this doesn't work if what is being assigned is a property of an object i.e.:

// Throws a ReferenceError that `object_name` is not defined.
(function() {})(object_name.property_name = 2)
Lapys
  • 936
  • 2
  • 11
  • 27

2 Answers2

3

Thats what we used to call the horror of implicit globals

You basically create a global variable by accident. You can "use strict";mode to prevent that.

Your second snippet does not work because you are trying to access a variable that was not declared yet, which is different from assigning to a variable that was not declared already (cause that implicitly declares the variable).

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

You have declared a global variable here in both cases without the 'var' keyword.

Andrew Daly
  • 537
  • 3
  • 12
  • Yes, and that was the oddity here. Implicit globals: Declaring variables on the global scope without the `.` operator, or the `const`, `let`/ `var` keywords. The best part? Does not cause an error except in Strict Mode (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode). – Lapys May 11 '19 at 07:22