Undefined variable is used to check if the variable has assigned any value or not? In this example of undefined, We are checking if the variable x is undefined and yes this is undefined. you can check it by clicking on the button.
JavaScript undefined Example - 1
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>
<body>
<p>Click the button to test if a variable is undefined.</p>
<button onclick="checkUndefined()">Click it</button>
<p id="sample"></p>
<script>
function checkUndefined() {
var x;
if (x === undefined) {
txt = "x is undefined";
} else {
txt = "x is defined";
}
document.getElementById("sample").innerHTML = txt;
}
</script>
</body>
</html>
Example of undefined: In this example, it will return variable is undefined because it will check the datatype as well.
JavaScript undefined Example - 2
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>
<body>
<p>Click the button to test if a variable is undefined.</p>
<button onclick="checkUndefined()">Click it</button>
<p id="sample"></p>
<script>
function checkUndefined() {
var y;
if (typeof y === undefined) {
txt = "y is undefined";
} else {
txt = "y is defined";
}
document.getElementById("sample").innerHTML = txt;
}
</script>
</body>
</html>