3

I have a prompt at the beginning of my page, and the text of a header is changed depending on the user's input. Since clicking the Cancel button returns null and clicking the Ok button without any text entered in the field returns an empty string, I used the two checks in my code to alter the text accordingly. The issue is that the prompt isn't actually returning null when the Cancel button is clicked. It is instead returning it as a string.

Javascript:

var name = prompt("Enter your name");
var header = document.getElementById("welcome-header");

if (name !== "null" && name !== "") {
    header.innerHTML = `Welcome, ${name}!`;
}

To accommodate for this, I had to actually put null in a string, as shown in the code snippet. Am I missing something?

Here's where W3 shows that it should return null.

Chris Lallo
  • 310
  • 2
  • 10

2 Answers2

0

You can just do a falsy check:

if (!name) {...}
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
0

Try this, you should not care if it's null, if it's not null it should have a length of > 0 but you can just use simple regex to look for any word in case only blank spaces are entered. Not sure why null is getting passed as a string, I can't duplicate that behavior but if it's an edge case, try:

if (name != 'null' && name.match(/\w/).length > 0 {
    header.innerHTML = `Welcome, ${name}!`;
}
lacostenycoder
  • 10,623
  • 4
  • 31
  • 48