If value exists, do this. undefined vs null?

Viewed 87

I want to render certain action upon button click.

The condition is: (If value exists in input field, then write 'value exists'. If value doesn't exists, then alert).

I tried to replace undefined with null. I also try to replace operator === and ==. None works! Please help.

<html>
<head>

</head>
<body>

<input id='typer' type='text'></input>
<button onclick='hey()'>click</button>

<p id='pw'></p>

<script>

var pw
pw = document.querySelector('#pw');

function hey() {
    if (document.getElementById('typer').value !== undefined) {
        pw.innerHTML = 'value exists';
    } else {
        alert('value does not exists');
    }
}

</script>
</body>
</html>
2 Answers

null, undefined, and an empty string ("") are all 'falsey' values in JavaScript; this means that if you pass them into the ! operator, the result will be true. You can test this out in your console by running !(""), !(null), or (for undefined) by defining var x; and then calling !x.

What's more, an if statement doesn't actually check if its condition is equal to true, it checks if the condition is 'truthy' (i.e. evaluates to false when passed through !).

Therefore, all you need to do is set the condition of the if statement to document.getElementById('typer').value, since as long as the value of the element isn't null, undefined, or an empty string (or false, which is also falsey), the condition is truthy.

For <input type="text">, the documentation states that the type of its .value property is a DOMString.

DOMString is a UTF-16 String. As JavaScript already uses such strings, DOMString is mapped directly to a String.

This means that .value will never be null or undefined; with this knowledge, when you want to know whether a value is present, you can do two things:

  1. Use value.length to determine if the string is empty
  2. Use value or !value itself in an if statement to determine whether it's present or empty respectively (an empty string evaluates to false, whereas a nonempty string evaluates to true)
Related