What does an exclamation mark before a variable mean in JavaScript

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?


! 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 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?

  • MDN has a list of operators here.
  • The language specification specifies such operators, though being the official specification it does contain some jargon which might be hard to understand.

  • 它是一个用于对变量进行真值测试的否定运算符。

    var myVariable = 1;
    
    if ( ! myVariable )
    {
        // myVariable evaluates as false
    }
    
    if ( myVariable )
    {
        // myVariable evaluates as true
    }
    
    链接地址: http://www.djcxy.com/p/74986.html

    上一篇: JavaScript分割并添加一个字符串

    下一篇: JavaScript中变量的意思是什么?