JavaScript check if a variable is defined

A good way to check if a variable has been defined is to make use of JavaScript typeof:

<script type="text/javascript">
    var varA = "Hello World!";

    if (typeof varA !== "undefined") {
        console.log("Defined");
    } else {
        console.log("Undefined");
    }
    
    // Undefined variable
    if (typeof varB !== "undefined") {
        console.log("Defined");
    } else {
        console.log("Undefined");
    }
</script>

Leave a Reply

Your email address will not be published. Required fields are marked *