e.g if(variable name) or
var x;if(x){some code} else{some code}
I understand
if(x>7)
conditions but only variable name inside bracket followed by if does not make me any sense.
Here variable can be a boolean value or sometime to check variable existence you check it in if statement. Condition you might test with if statement.
Element exist or not
Input value empty or not
collection length zero or greater
So following code:
if(result){
//do something
}
will cause false in the following condition(also called falsy):
false
0 (zero)
"" (empty string)
null
undefined
NaN (a special Number value meaning Not-a-Number!)
Either they contain a true or false value or the if statement checks if the variable is defined or undefined or even null.
If contains an expression. And a single variable is an expression that evaluates to its value. Hence it can be used in if condition.
Moreover, if extracts the the Boolean value of the expression. So any non zero variable becomes true and others become false. This helps to write less.
The value should first be converted to a boolean and this is how it's done:
if (x) means if (x != 0 && !isNaN(x)) for numeric values
means x != "" for string values
means x != null && x != undefined for objects
In JS, if a variable has a value, it is true, otherwise, it is false.
For example, "", 0, -0, NaN, etc., all evaluate to false.
http://www.w3schools.com/JS/js_booleans.asp
Related
I know that in JavaScript you can do:
var oneOrTheOther = someOtherVar || "these are not the droids you are looking for...";
where the variable oneOrTheOther will take on the value of the first expression if it is not null, undefined, or false. In which case it gets assigned to the value of the second statement.
However, what does the variable oneOrTheOther get assigned to when we use the logical AND operator?
var oneOrTheOther = someOtherVar && "some string";
What would happen when someOtherVar is non-false?
What would happen when someOtherVar is false?
Just learning JavaScript and I'm curious as to what would happen with assignment in conjunction with the AND operator.
Basically, the Logical AND operator (&&), will return the value of the second operand if the first is truthy, and it will return the value of the first operand if it is by itself falsy, for example:
true && "foo"; // "foo"
NaN && "anything"; // NaN
0 && "anything"; // 0
Note that falsy values are those that coerce to false when used in boolean context, they are null, undefined, 0, NaN, an empty string, and of course false, anything else coerces to true.
&& is sometimes called a guard operator.
variable = indicator && value
it can be used to set the value only if the indicator is truthy.
Beginners Example
If you are trying to access "user.name" but then this happens:
Uncaught TypeError: Cannot read property 'name' of undefined
Fear not. You can use ES6 optional chaining on modern browsers today.
const username = user?.name;
See MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
Here's some deeper explanations on guard operators that may prove useful in understanding.
Before optional chaining was introduced, you would solve this using the && operator in an assignment or often called the guard operator since it "guards" from the undefined error happening.
Here are some examples you may find odd but keep reading as it is explained later.
var user = undefined;
var username = user && user.username;
// no error, "username" assigned value of "user" which is undefined
user = { username: 'Johnny' };
username = user && user.username;
// no error, "username" assigned 'Johnny'
user = { };
username = user && user.username;
// no error, "username" assigned value of "username" which is undefined
Explanation: In the guard operation, each term is evaluated left-to-right one at a time. If a value evaluated is falsy, evaluation stops and that value is then assigned. If the last item is reached, it is then assigned whether or not it is falsy.
falsy means it is any one of these values undefined, false, 0, null, NaN, '' and truthy just means NOT falsy.
Bonus: The OR Operator
The other useful strange assignment that is in practical use is the OR operator which is typically used for plugins like so:
this.myWidget = this.myWidget || (function() {
// define widget
})();
which will only assign the code portion if "this.myWidget" is falsy. This is handy because you can declare code anywhere and multiple times not caring if its been assigned or not previously, knowing it will only be assigned once since people using a plugin might accidentally declare your script tag src multiple times.
Explanation: Each value is evaluated from left-to-right, one at a time. If a value is truthy, it stops evaluation and assigns that value, otherwise, keeps going, if the last item is reached, it is assigned regardless if it is falsy or not.
Extra Credit: Combining && and || in an assignment
You now have ultimate power and can do very strange things such as this very odd example of using it in a palindrome.
function palindrome(s,i) {
return (i=i || 0) < 0 || i >= s.length >> 1 || s[i] == s[s.length - 1 - i] && isPalindrome(s,++i);
}
In depth explanation here: Palindrome check in Javascript
Happy coding.
Quoting Douglas Crockford1:
The && operator produces the value of its first operand if the first operand is falsy. Otherwise it produces the value of the second operand.
1 Douglas Crockford: JavaScript: The Good Parts - Page 16
According to Annotated ECMAScript 5.1 section 11.11:
In case of the Logical OR operator(||),
expr1 || expr2 Returns expr1 if it can be converted to true;
otherwise, returns expr2. Thus, when used with Boolean values, ||
returns true if either operand is true; if both are false, returns
false.
In the given example,
var oneOrTheOther = someOtherVar || "these are not the droids you are looking for...move along";
The result would be the value of someOtherVar, if Boolean(someOtherVar) is true.(Please refer. Truthiness of an expression). If it is false the result would be "these are not the droids you are looking for...move along";
And In case of the Logical AND operator(&&),
Returns expr1 if it can be converted to false; otherwise, returns
expr2. Thus, when used with Boolean values, && returns true if both
operands are true; otherwise, returns false.
In the given example,
case 1: when Boolean(someOtherVar) is false: it returns the value of someOtherVar.
case 2: when Boolean(someOtherVar) is true: it returns "these are not the droids you are looking for...move along".
I see this differently then most answers, so I hope this helps someone.
To calculate an expression involving ||, you can stop evaluating the expression as soon as you find a term that is truthy. In that case, you have two pieces of knowledge, not just one:
Given the term that is truthy, the whole expression evaluates to true.
Knowing 1, you can terminate the evaluation and return the last evaluated term.
For instance, false || 5 || "hello" evaluates up until and including 5, which is truthy, so this expression evaluates to true and returns 5.
So the expression's value is what's used for an if-statement, but the last evaluated term is what is returned when assigning a variable.
Similarly, evaluating an expression with && involves terminating at the first term which is falsy. It then yields a value of false and it returns the last term which was evaluated. (Edit: actually, it returns the last evaluated term which wasn't falsy. If there are none of those, it returns the first.)
If you now read all examples in the above answers, everything makes perfect sense :)
(This is just my view on the matter, and my guess as to how this actually works. But it's unverified.)
I have been seeing && overused here at work for assignment statements. The concern is twofold:
1) The 'indicator' check is sometimes a function with overhead that developers don't account for.
2) It is easy for devs to just see it as a safety check and not consider they are assigning false to their var. I like them to have a type-safe attitude, so I have them change this:
var currentIndex = App.instance && App.instance.rightSideView.getFocusItemIndex();
to this:
var currentIndex = App.instance && App.instance.rightSideView.getFocusItemIndex() || 0;
so they get an integer as expected.
let x;
console.log("shubham" == true ); // gives false
"shubham" ? x=2 : x=3;
console.log(x); // gives 2, so "shubham" must be true?
//I am hoping to get value 3
when you use this:
"shubham" == true
before comparing, true turned to 1,so the actually comparsion is
"shubham" == 1
so ,it gives false;
the book:
When performing conversions, the equal and not-equal operators follow
these basic rules:
If an operand is a Boolean value, convert it into a
numeric value before checking for equality. A value of false converts
to 0, whereas a value of true converts to 1.
If one operand is a string and the other is a number, attempt to convert the string into a number before checking for equality.
when you use this:
"shubham" ? x=2 : x=3;
works like:
Boolean("shubham")?x=2:x=3
so,it gives you x=2;
the book:
variable = boolean_expression ? true_value : false_value;
This basically allows a conditional assignment to a variable depending
on the evaluation of the boolean_expression. If it’s true, then
true_value is assigned to the variable; if it’s false, then
false_value is assigned to the variable.
the book:
Professional JavaScript for Web Developers.3rd.Edition.Jan.2012
Yes, this is due to the underlying code behind the 'if' statement in Javascript. It relies on a method 'ToBoolean' which converts the condition of the if statement to a boolean value. Any string that is not empty, is converted to true. Thus, why you get the above logic.
inside conditional statement any logical operation will evaluate to a boolean value which determines whether or not the conditional block will be executed or not. Like the following statement will determine the IF statement will execute or not
if(null || 1){} // evaluates to boolean value
but the same conditional statement will evaluates to Number value when assigned to a variable.Consider this:
var x = null || 1 // x will become 1
my another question is does the order of null and 1 matters here?
what determines when a conditional operation will become Boolean or Number ?
They both result in the same thing. The difference, however, is that the if statement parses the value as a boolean: the 1 returned is parsed as a boolean.
> (null || 1)
1
> Boolean(1)
true
The if(null || 1){} simply evaluates to if(1){} which in turn evaluates to if(true){} since 1 is truthy.
Thus, there is no deterministic difference, the if statement simply parses the parameter as a boolean while the variable definition merely returns the number itself.
From mozzila.org:
In JavaScript, a truthy value is a value that is considered true when evaluated in a Boolean context. All values are truthy unless they are defined as falsy (i.e., except for false , 0 , "" , null , undefined , and NaN ). JavaScript uses type coercion in Boolean contexts
In JavaScript, 1 is "truthy", which is why the if statement is entered. Basically, (null || 1) always evaluates to 1, but if forced, we say that it's true rather than false.
Let me start off by saying I understand the difference between =, ==, and
===. The first is used to assign the right-hand value to the left-hand variable, the second is used to compare the equivalency of the two values, and the third is used not just for equivalency but type comparison as well (ie true === 1 would return false).
So I know that almost any time you see if (... = ...), there's a pretty good chance the author meant to use ==.
That said, I don't entirely understand what's happening with these scripts:
var a = 5;
if (a = 6)
console.log("doop");
if (true == 2)
console.log('doop');
According to this Javascript type equivalency table, true is equivalent to 1 but not 0 or -1. Therefore it makes sense to me that that second script does not output anything (at least, it isn't in my Chrome v58.0.3029.110).
So why does the first script output to the console but the second doesn't? What is being evaluated by the first script's if statement?
I dug into my C# knowledge to help me understand, but in C# you cannot compile if (a = 5) Console.WriteLine("doop"); so I had to explicitly cast it to a bool by doing if (Convert.ToBoolean(a = 5)) but then that makes sense it would evaluate to true because according to MSDN's documentation, Convert.ToBool returns true if the value supplied is anything other than 0. So this didn't help me very much, because in JS only 1 and true are equal.
There's a difference between making an abstract equality comparison with == and performing a simple type cast to boolean from a number value. In a == comparison between a boolean and a number, the boolean value is converted to 0 or 1 before the comparison. Thus in
if (true == 2)
the value true is first converted to 1 and then compared to 2.
In a type cast situation like
if (x = 2)
the number is converted to boolean such that any non-zero value is true. That is, the value 2 is assigned to x and the value of the overall expression is 2. That is then tested as boolean as part of the evaluation of the if statement, and so is converted as true, since 2 is not 0.
The various values that evaluate to boolean false are 0, NaN, "", null, undefined, and of course false. Any other value is true when tested as a boolean (for example in an if expression).
Why does an assignment in an if statement equate to true?
It doesn't. An assignment is evaluated as whatever value is assigned.
This expression is a true value:
a = true
But this expression is a false value:
b = false
That's true whether or not you put it in an if statement or not.
This question already exists:
Closed 12 years ago.
Possible Duplicate:
In Javascript, what does it mean when there is a logical operator in a variable declaration?
Stumbled across this code online, have no idea what it does, wasn't able to find out with FireBug either, and I can't google it because of the special characters...
var myValue = myInput.value || 0;
if myInput.value is undefined (or another falsy value) then the default value of 0 will be set
some examples...
myInput.value = undefined
var myValue = myInput.value || 0;
// myValue = 0
myInput.value = 10
var myValue = myInput.value || 0;
// myValue = 10
|| is often called the default operator. It lets you give a default value, if something else is falsy. So if myInput.value is undefined, for example, myValue will be assigned 0.
Because of the way the javascript interpreter is built, it can interpret certain classes of values or even the existence (or non-existence) of values as true or false
undefined, null, false, 0, empty string, NaN can be interpreted as false
the existence of a non-false value can be interpreted as not-false, thus in many cases, true; Don't confuse not-false with true though. They are sometimes loosely interpreted as the same, but not-false contains everything that isn't interpreted as false, whereas true is much more specific.
Thus:
if (myMethod)
myMethod();
Can be used to check for the existence of myMethod before running it.
The || symbol is a short-circuiting OR statement. If the first part of the OR is or can be interpreted as not-false, then that part of the statement will preside and the value will be taken and used as myValue. If javascript deems that the first part of the statement is interpreted as false, then the second part of the OR will be returned.
Thus in the statement:
var myValue = myInput.value || 0;
myValue will become whatever myInput.value contains if it contains anything that javascript can interpret as not false. Thus it could contain "Hi, hell of a day we've got here!" and that would be returned to myValue.
When I say not-false, I don't strictly mean true, because "Hi, hell of a day we've got here" isn't [strictly speaking] interpreted as true, but is "coerced" to being interpreted that way.
If myInput.value doesn't contain anything that javascript could coerce to being interpreted as true, then 0 will be returned to myValue.
So in this case, if myInput.value is undefined, null, false, 0 etc. then myValue = 0
It's a way of having a default value of 0 in case myInput.value is null (undefined)
Javascript has a defined left to right evaluation order. So if you write something like
if (method() || method2()) { ... }
method2() will never happen if method() returns true, because true OR anything will always be true.
This works the same for the example you are giving in Javascript.
If "myinput.value" evaluates to something trueish, this value will be assigned, otherwise 0 will be assigned for every falsish value (null, 0, "").
It sets myValue to the value of myInput or to 0, if the myInput value is anything that’s considered false in JavaScript (especially undefined or null). The trick is the short-circuit behaviour of the || operator. When you evaluate a||b and a is true, the || operator returns a:
console.log('a'||'b'); // 'a'
When the first argument is false, the || operator returns its second argument:
console.log(undefined||'b'); // 'b'
It’s also good to ponder this:
var foo = 0;
console.log('a'||foo++);
console.log(foo); // 0
console.log(undefined||foo++); // 0
console.log(foo); // 1
The || operator in many langiages includes an optimization called short-cutting: if the left side evaluates to a true value then the right side does not need to be evaluated. True || anything == true. This is often used to provide default values, as in your example code. If the left hand side myInput.value evaluates to true, then the whole expression will return that value. Otherwise, the whole expression will return the right hand value of 0.
Note that this also depends on the || operator returning the original values rather than a boolean true or false value. Each side is evaluated to true or false for the logic test, but not for the expression's return value.
function or(a, b) {
if (a) { return a; }
return b;
}
MyValue will be equal to myInput.value OR 0 if the previous value can be regarded as False.
Value can be regarded as False is its empty string (''), zero (0) etc. Anything that say True in this code myInput.value == False
It means that if myInput.value isn't defined, myValue will be set to 0. Think || same as OR.