First lets understand difference between '==' and '==='
1 == '1';// returns true
1==='1'; //returns false
First line will return a Boolean(true or false) value of true, has '==' doesn't check the the data type so number 1 and string 1 will still return a value of true.
On second line 1==='1'
will return false has '===' checks the data type and only return true
when both values are of same type.
In simple words Use a ===
strict equality (or !==
strict inequality) comparisons to compare values and avoid type conversion.
The following values are always falsy:
false
0 (zero)
-0 (minus zero)
'', "", `` (empty string)
null
undefined
NaN
we can use truthy or falsy values to check and run certain code only if user have given input example(Input validation):
<input id="user-input" type="text" />
<button id="check-btn">Check</button>
<div class="output"></div>
<script>
const checkBtn = document.querySelector("#check-btn");
const userInput = document.querySelector("#user-input");
const output = document.querySelector(".output");
checkBtn.addEventListener("click", function () {
if(userInput.value){// only returns true when user give input
// some code.
}
else{// if user doesn't type anything in input form then this msg will be shown
output.innerText ="Invalid input please fill the form"
}
}
</script>
Everything else is truthy. That includes:
'0' (a string containing a single zero)
'false' (a string containing the text “false”)
[] (an empty array)
{} (an empty object)
function(){} (an “empty” function)
I hope this blog is understandable if not let me know in comment which part you didn't understand I will try to explain it better