Sunday, November 6, 2016

JavaScript: ReferenceError vs. Undefined variable

When 'use strict' is not used

console.log(aVar);

Uncaught ReferenceError: aVar is not defined(…)

---

var aVar;
console.log(aVar);

undefined

---

var aVar = "a";
console.log(aVar);

a

---

aVar = "a";
console.log(aVar);

a

---

console.log(aVar);
var aVar = "a";

undefined

---
console.log(aVar);
aVar = "a";

Uncaught ReferenceError: aVar is not defined(…)

When 'use strict' is used

'use strict';
console.log(aVar);

Uncaught ReferenceError: aVar is not defined(…)

---

'use strict';
var aVar;
console.log(aVar);

undefined

---

'use strict';
var aVar = "a";
console.log(aVar);

a

---

'use strict';
aVar = "a";
console.log(aVar);

Uncaught ReferenceError: aVar is not defined(…)

---

'use strict';
console.log(aVar);
var aVar = "a";

undefined

---

'use strict';
console.log(aVar);
aVar = "a";

Uncaught ReferenceError: aVar is not defined(…)