!!
to convert to booleanif
, it will either execute a true
code branch (when the object is true
), or execute a false
branch (respectively, when the object has a false
value).true
. Sometimes you may need to convert a variable to a boolean value. This can be done with the help of the operator !!
: var something = 'variable'; !!something // returns true
if (x == "test")
you can simply write if (x)
. If x
is an empty variable, then just the code from the else
block will be executed.+
, this is a unary operator that returns a numeric representation of an operand or NaN
if the operand does not have one. For example, using this operator, you can check whether the variable x
number (such code can be seen in the underscore library): x === +x
.parseFloat
and parseInt
methods.||
is an example of the execution of a short circuit . This operator first analyzes the expression to its left, and, if it is false, analyzes the expression to the right. In any case, it returns the first true expression. Consider the following example: function setAge(age) { this.age = age || 10 } setAge();
setAge()
function setAge()
no arguments, so age || 10
age || 10
returns 10 ( !!age == false
). This method is very good for setting variable values by default. In fact, this approach is equivalent to the following example: var x; if (age) { this.age = age; } else { this.age = 10; }
||
more concise, so this method is used throughout the world. this.age = (typeof age !== "undefined") ? age : 10;
void
keyword takes one argument and always returns undefined
. Why not just use undefined
? Because in some browsers, undefined
is just a variable that can be overridden. Therefore, void 0
gives us more confidence that nothing will be accidentally broken. Although you can find this hack in the source files of many libraries, I would not recommend using it regularly, since all undefined
. (function() { function div(a, b) { return a / b; } function divBy5(x) { return div(x, 5); } window.divBy5 = divBy5; })() div // => undefined divBy5(10); // => 2
age = age || 10
age = age || 10
you can write the following: function(age = 10) { // ... }
(function() {...})()
, which you are unlikely to use anymore after ES6 modules are supported by modern browsers.Source: https://habr.com/ru/post/240357/
All Articles