Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
338 views
in Technique[技术] by (71.8m points)

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...