What is an exclamation point in JavaScript?
A !
negates an expression.
In your example, if loadDynamicBlock()
returned true, the function calling it would return false, and vice-versa: !true == false
It can also be used to create actual booleans from JavaScript's ideas of truthy and falsy.
var a = 5;
!!(a - 5) === false;
!!(a + 5) === true;
What does an exclamation mark before a variable mean in JavaScript
!
is the logical not operator in JavaScript.
Formally
!expression
is read as:
- Take
expression
and evaluate it. In your case that'svariable.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?
- 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.
In Typescript, what is the ! (exclamation mark / bang) operator when dereferencing a member?
That's the non-null assertion operator. It is a way to tell the compiler "this expression cannot be null
or undefined
here, so don't complain about the possibility of it being null
or undefined
." Sometimes the type checker is unable to make that determination itself.
It is explained in the TypeScript release notes:
A new
!
post-fix expression operator may be used to assert that its operand is non-null and non-undefined in contexts where the type checker is unable to conclude that fact. Specifically, the operationx!
produces a value of the type ofx
withnull
andundefined
excluded. Similar to type assertions of the forms<T>x
andx as T
, the!
non-null assertion operator is simply removed in the emitted JavaScript code.
I find the use of the term "assert" a bit misleading in that explanation. It is "assert" in the sense that the developer is asserting it, not in the sense that a test is going to be performed. The last line indeed indicates that it results in no JavaScript code being emitted.
What does exclamation point after variable mean in JavaScript?
In TypeScript, a postfix !
removes null
and undefined
from the type of an expression.
This is useful when you know, for reasons outside TypeScript's inference ability, that a variable that "could" be null
or undefined
actually isn't.
What does the exclamation mark do before the function?
JavaScript syntax 101: here is a function declaration:
function foo() {}
Note that there’s no semicolon; this is just a function declaration. You would need an invocation, foo()
, to actually run the function.
Now, when we add the seemingly innocuous exclamation mark: !function foo() {}
it turns it into an expression. It is now a function expression.
The !
alone doesn’t invoke the function, of course, but we can now put ()
at the end: !function foo() {}()
, which has higher precedence than !
and instantly calls the function.
function foo() {}()
would be a syntax error because you can’t put arguments (()
) right after a function declaration.
So what the author is doing is saving a byte per function expression; a more readable way of writing it would be this:
(function(){})();
Lastly, !
makes the expression return a boolean based on the return value of the function. Usually, an immediately invoked function expression (IIFE) doesn’t explicitly return anything, so its return value will be undefined
, which leaves us with !undefined
which is true
. This boolean isn’t used.
Why does an exclamation mark before a variable return 'true' if the variable value is zero?
! is known as the logical NOT operator. It reverses the boolean result of the operand (or condition)
0 is also considered as the boolean false, so when you use !variable you are using the logical operator and saying it to change the value of the variable to its opposite, that in boolean is true
0 == false == !1 == !true
1 == true == !0 == !false
in Javascript are considered false:
false, null, undefined, "", 0, NaN
are considered true:
true, 1, -0, "false". <- the last one is a not empty string, so its true
if( false || null || undefined || "" || 0 || NaN) //never enter
if( true && 1 && -1 && "false") //enter
https://developer.mozilla.org/en-US/docs/Glossary/Falsy
ES6 template literals vs. concatenated strings
If you are using template literals only with placeholders (e.g. `Hello ${person.name}`
) like in the question's example, then the result is the same as just concatenating strings. Subjectively it looks better and is easier to read, especially for multi-line strings or strings containing both '
and "
since you don't have to escape those characters any more.
Readability is a great feature, but the most interesting thing about templates are Tagged template literals:
let person = {name: 'John Smith'};
let tag = (strArr, name) => strArr[0] + name.toUpperCase() + strArr[1];
tag `My name is ${person.name}!` // Output: My name is JOHN SMITH!
In the third line of this example, a function named tag
is called. The content of the template string is split into multiple variables, that you can access in the arguments of the tag
function: literal sections (in this example the value of strArr[0]
is My name is
and the value of strArr[1]
is !
) and substitutions (John Smith
). The template literal will be evaluated to whatever the tag
function returns.
The ECMAScript wiki lists some possible use cases, like automatically escaping or encoding input, or localization. You could create a tag function named msg
that looks up the literal parts like My name is
and substitutes them with translations into the current locale's language, for example into German:
console.log(msg`My name is ${person.name}.`) // Output: Mein Name ist John Smith.
The value returned by the tag function doesn't even have to be a string. You could create a tag function named $
which evaluates the string and uses it as a query selector to return a collection of DOM nodes, like in this example:
$`a.${className}[href=~'//${domain}/']`
Is !!!foo the same as !foo?
Yup. Just for clarity:
!!x === x
is not generally true, but it is true if x
is already a boolean: "not (not true)" is true, and "not (not false)" is false.
!foo
is always a boolean; if foo
is truthy, it's false
, otherwise it's true
.
So if you substitute !foo
in for x
you get that !!(!foo) === (!foo)
is always true. Removing the parentheses doesn't change the meaning, so !!!foo === !foo
is always true.
Which means there's no good reason to write !!!foo
in actual code. Just use !foo
instead.
Related Topics
R Networkd3 Package: Node Coloring in Simplenetwork()
How to Save a Leaflet Map with Drawn Shapes/Points on It in Shiny
Decryption of Aes Created with Sjcl.Js in Ruby
How to Geocode 20 Addresses Without Receiving an Over_Query_Limit Response
Fire Jquery Event on Div Change
JavaScript with Embedded Ruby: How to Safely Assign a Ruby Value to a JavaScript Variable
How to Intercept Xmlhttprequests from a Greasemonkey Script
"Cannot Use Import Statement Outside a Module" Error When Importing React-Hook-Mousetrap in Next.Js
How to Use Source: Function()... and Ajax in Jquery UI Autocomplete
Angular 2: Two Backend Service Calls on Success of First Service
Uint8Array to String in JavaScript
Compare JavaScript Array of Objects to Get Min/Max
Extending an Object in JavaScript
Create an Object from an Array of Keys and an Array of Values