+ 3

How to check null value?[SOLVED]

If the prompt is empty how could I check the value if it is null? Using if condition.

21st Mar 2019, 9:50 AM
Sarthak Gupta
Sarthak Gupta - avatar
6 Answers
+ 4
The easiest way is: var val = prompt('Hello'); if(val){ alert('Not null'); } else { alert('Null'); } This code works because if the input value is empty, it converts to boolean false. Otherwise it converts to boolean true. For whitespace, it behaves same as val != null checking.
22nd Mar 2019, 1:23 AM
Adnan Zawad Toky
Adnan Zawad Toky - avatar
+ 8
this function will return true if val is empty, null, undefined, false, the number 0 or NaN. You are a bit overdoing it. To check if a variable is not given a value, you would only need to check against undefined and null. This is assuming 0 , "" , and objects(even empty object and array) are valid "values". //i think my answer will help you😉😁
21st Mar 2019, 9:58 AM
Max Andal
Max Andal - avatar
+ 6
The prompt() method returns String. If the user clicks "OK", the input value is returned. If the user clicks "cancel", null is returned. If the user clicks OK without entering any text, an empty string is returned. source: https://www.w3schools.com/jsref/met_win_prompt.asp Checking for an empty string. https://www.w3schools.com/code/tryit.asp?filename=G2AN4FX57NDN
21st Mar 2019, 10:53 AM
ODLNT
ODLNT - avatar
+ 5
let ans = prompt('Question?') if(ans !== null && ans.trim()){ alert('not empty') } else { alert('empty') }
21st Mar 2019, 9:57 AM
Ulisses Cruz
Ulisses Cruz - avatar
+ 5
Sarthak An Empty string and null will convert to 0, so you would have to check for 0. https://www.w3schools.com/js/js_type_conversion.asp There is a chart on conversion at the bottom of the page, that make an excellent reference for type conversion
21st Mar 2019, 5:41 PM
ODLNT
ODLNT - avatar
+ 2
Max Andal Prompt takes only string inputs. So, "0" === 0 // false Thus the only possible inputs to come is either a string or empty value. Strings are truthy and empty or null is falsy. So, Adnan Zawad Toky 's solution holds true. And also thanks to ODLNT for helping me
14th Jan 2020, 6:06 PM
Sarthak Gupta
Sarthak Gupta - avatar