I\'m trying to learn JavaScript by going through some code in an application and I keep seeing !variable
in if conditions. For example:
if (!va
! is a logic reversal operator, if something was true it will change it to false, if something is false, it will change to true.
example, we know that empty string or 0 in boolean is false.
let a = Boolean("")
console.log(a) // shows false, because empty string in boolean is false
console.log(!a) // shows true, because logic is reversed
easier example:
let a = 5
let b = 1
let c = a > b
console.log(c) // shows true, since a,5 is bigger than b,1
console.log(!c) // shows false, since logic is now reversed
!
is the logical not operator in JavaScript.
!expression
is read as:
expression
and evaluate it. In your case that's variable.onsubmit
onsubmit
is likely a function, it means - if the function is null or undefined - return false, otherwise return true.In your case !variable.onsubmit
means return true if there isn't a function defined (and thus is falsy), otherwise return false (since there is a function defined).
Simply put - !variable
means take the truth value of variable
and negate it.
Thus, if (!variable) {
will enter the if
clause if variable is false
(or coerces to false)
if (!variable.onsubmit || (variable.onsubmit() != false)) {
Means - check if variable.onsubmit
is defined and truthy (thus true), then it checks if calling onsubmit
returns a result that coerces to true. In a short line it checks if there is no onsubmit
or it returns true.
It is a negation operator used for truth tests on a variable.
var myVariable = 1;
if ( ! myVariable )
{
// myVariable evaluates as false
}
if ( myVariable )
{
// myVariable evaluates as true
}
The selected answer already answers the question. One thing to add in this is that !
operator can be used in a rather interesting fashion.
obj = {}
if (!!obj) {console.log('works')} // !!obj = true
obj = undefined
if (!!obj) {console.log('does not work')} // !!obj = false
So double !!
will change any expression to a boolean
value with no exceptions.
This has a very peculiar use case in some cases.
Lets say there is a function that returns either true or false and nothing else. In that case one could just change return returnValue
to return !!returnValue
for extra caution (although not need in most of the cases)
Conversely, if a function only accepts true or false and nothing else, one could just call the function as functionA(!!parameter)
instead of functionA(parameter)
, which again is not needed in most of the cases, but could ensure extra security