Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't const App = App || {}; work but using var does?

In the past I have used

var App = App || {};

to assign or instantiate a common App object in various js scripts loaded separately into the browser.

However, using let and const instead of var throws a reference error:

const App = App || {}; // or let App = App || {};

Uncaught ReferenceError: App is not defined
at <anonymous>:1:11

What's going on here? If I want to continue using this pattern, do I have to stick to var?

like image 455
Lex Power Avatar asked May 23 '26 10:05

Lex Power


2 Answers

This is because when you are declaring a variable using let or a constant, the variable is in the temporal dead zone before being initialized.

In other words, trying let foo = foo will throw an error because foo is still in the temporal dead zone, and cannot be used. The same goes for const.

Note also that a variable defined whith let or a constant defined with const cannot share its name space in the same scope with another variable, be it with let, const, or var.

like image 193
theAlexandrian Avatar answered May 24 '26 23:05

theAlexandrian


When javascript engine sees the statement, var App = App || {}, it breaks the statement down as follows:

var App;
App = App || {};

Due to variable hoisting, var App = App || {} is broken down into two parts.

  1. Declaration: var App
  2. Assignment: App = App || {}

The let and const declarations on the other hand, don't involve variable hoisting. Hence, the ReferenceError, as no variable called App exists yet.

like image 32
Parama Kar Avatar answered May 25 '26 00:05

Parama Kar



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!