Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
63
rated 0 times [  68] [ 5]  / answers: 1 / hits: 58687  / 11 Years ago, mon, october 21, 2013, 12:00:00

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 (!variable.onsubmit || (variable.onsubmit() != false)) {


What is it? Some kind of test if the variable is empty?


More From » variables

 Answers
22

! is the logical not operator in JavaScript.


Formally


!expression is read as:



  • Take expression and evaluate it. In your case that's variable.onsubmit

  • Case the result of that evaluation and convert it to a boolean. In your case since onsubmit is likely a function, it means - if the function is null or undefined - return false, otherwise return true.

  • If that evaluation is true, return false. Otherwise return true.


In your case


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)


In total


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.


Next time, how do I find this myself?



[#74843] Saturday, October 19, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
zahrafrancisr

Total Points: 176
Total Questions: 105
Total Answers: 99

Location: Svalbard and Jan Mayen
Member since Sun, Sep 25, 2022
2 Years ago
;