What does an exclamation mark before a variable mean in JavaScript

后端 未结 4 1479
说谎
说谎 2020-11-28 08:13

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         


        
4条回答
  •  佛祖请我去吃肉
    2020-11-28 08:42

    ! 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
    

提交回复
热议问题