JavaScript ReferenceError - Assignment to undeclared variable
Last Updated : 22 May, 2023
Improve
This JavaScript exception Assignment to undeclared variable occurs in strict-mode If the value has been assigned to an undeclared variable.
Message:
ReferenceError: assignment to undeclared variable "x" (Firefox) ReferenceError: "x" is not defined (Chrome) ReferenceError: Variable undefined in strict mode (Edge)
Error Type:
ReferenceError
Cause of the error: Somewhere in the code, there is an assignment without the var, let, or const keywords. When a value is assigned to an undeclared variable this error occurs.
Example 1: In this example, the const keyword is used with the variable assignment, So the error has not occurred.
<!DOCTYPE HTML>
<html>
<body style="text-align:center;">
<h1 style="color:green;">
GeeksforGeeks
</h1>
<p>
JavaScript ReferenceError-
Assignment to undeclared variable
</p>
<button onclick="Geeks();">
click here
</button>
<p id="GFG_DOWN">
</p>
<script>
let el_down = document.getElementById("GFG_DOWN");
function GFG() {
'use strict';
const var_1 = "Value assigned without declaration";
}
function Geeks() {
try {
GFG();
el_down.innerHTML =
"'Assignment to undeclared variable'" +
"error has not occurred";
} catch (e) {
el_down.innerHTML =
"'Assignment to undeclared variable'" +
"error has occurred";
}
}
</script>
</body>
</html>
Output:
Example 2: In this example, the var, let or const keyword is not used with the variable assignment, So the error has occurred.
<!DOCTYPE HTML>
<html>
<body style="text-align:center;">
<h1 style="color:green;">
GeeksforGeeks
</h1>
<p>
JavaScript ReferenceError -
Assignment to undeclared variable
</p>
<button onclick="Geeks();">
click here
</button>
<p id="GFG_DOWN">
</p>
<script>
let el_down = document.getElementById("GFG_DOWN");
function GFG() {
'use strict';
var_1 = true;
}
function Geeks() {
try {
GFG();
el_down.innerHTML =
"'Assignment to undeclared variable'" +
"error has not occurred";
} catch (e) {
el_down.innerHTML =
"'Assignment to undeclared variable'" +
"error has occurred";
}
}
</script>
</body>
</html>
Output: