3 Example(s) of JavaScript undefined


Description :

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>

Output

Description :

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>

Output

Description :

undefined-3


JavaScript undefined Example - 3
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>
<body>
<p>Click the button to check whether the variables have been assigned a value or not.</p>
<button onclick="checkUndefined()">Click it</button>
<p id="sample"></p>
<script>
function checkUndefined() {
    var x1 = "myFunction";
    var x2;
    if (x1 === undefined) {
        txt1 = "x1 is undefined";
    } else {
        txt1 = "x1 is defined";
    }
    if (x2 === undefined) {
        txt2 = "x2 is undefined";
    } else {
        txt2 = "x2 is defined";
    }
    txt = txt1 + "<br>" + txt2;
    document.getElementById("sample").innerHTML = txt;
}
</script>
</body>
</html>

Output