Checking Whether a Variable or Property Is null or undefined - Javascript Language Basics

Javascript examples for Language Basics:Introduction

Introduction

To check whether a property is null or undefined, you can use an if statement and the negation operator !.

Demo Code

ResultView the demo in separate window

<!DOCTYPE HTML>
<html>
    <head>
        <title>Example</title>
    </head>
    <body>
        <script type="text/javascript">

            var myData = {//from w w w .j a  v a 2  s. co  m
                name: "java2s.com",
                city: null
            };

            if (!myData.name) {
                document.writeln("name IS null or undefined");
            } else {
                document.writeln("name is NOT null or undefined");
            }

            if (!myData.city) {
                document.writeln("city IS null or undefined");
            } else {
                document.writeln("city is NOT null or undefined");
            }

        </script>
    </body>
</html>

If a variable or property is null or undefined, the coerced boolean value is false.

Related Tutorials