JavaScript function call passes x && y as parameters [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
&& operator in Javascript
In the sample code of the ExtJS web desktop demo there is the following call:
this.setActiveButton(activeWindow && activeWindow.taskButton);
to method:
setActiveButton: function(btn) {
if (btn) {
btn.toggle(true);
} else {
this.items.each(function (item) {
if (item.isButton) {
item.toggle(false);
}
});
}
}
What is the purpose of the && in the function call?

It's to make sure that, before trying to find a property on an object referenced by the variable "activeWindow", the variable actually does reference something. If it's null (or a few other things; we'll assume the code knows that it's either an object reference or null), that would cause an exception. This way, the function is passed either the button reference (whatever that is), or null.
To put it another way, it's the same as this:
this.setActiveButton(activeWindow != null ? activeWindow.taskButton : null)
The && operator in JavaScript is kind-of special compared to the && in C or Java or other languages like that. In JavaScript, the left side is evaluated first. If that value is "falsy" (null, undefined, false, zero, or an empty string), then that's the value of the expression. Otherwise, the value of the expression is the value of the right-hand side.

See Short-circuit evaluation for additional information regarding this method.
The short-circuit expression x Sand y (using Sand to denote the
short-circuit variety) is equivalent to the conditional expression if
x then y else false; the expression x Sor y is equivalent to if x then
true else y.

Related

JS object null checking - weird JS problem [duplicate]

This question already has answers here:
Why don't logical operators (&& and ||) always return a boolean result?
(9 answers)
Javascript AND operator within assignment
(7 answers)
Closed 4 years ago.
Imagine this simple scenario. I have variable that can be plain JS object with one property, ID, that is a number or obj variable can be null. I have simple test() function that checks if the variable is not null and that it must have valid id property.
var obj = { id: 111 };
function test() {
return (obj && obj.id);
}
I am expecting that this function will always return boolean but in fact it returns undefined if the obj is undefined or value of obj.id if object exists like in case above. Why this function return 111 instead of true.
I am going to rip off hair of my head ... Please illuminate my mind :)
It's a common misconception. In JS (unlike in e.g. PHP) an expression like x && y does this:
execute the expression x
if the expression x returned true, then execute the expression y as well and return it (y). Otherwise return x (which would be falsy in this case e.g. 0, '', false, null, undefined).
In other words it works more like a ternary expression x ? y : z.
If you want a boolean, then use !!(x && y).
When obj is defined, why does if (obj && obj.id) return 111?
The logical AND (&&) operator returns expr1 if it can be converted to false; otherwise, returns expr2.
MDN: Logical Operators - Description (slightly paraphrased)
expr1 (obj) cannot be converted to false, therefore it returns expr2 (111).
Why does it not return true?
Logical operators are typically used with Boolean (logical) values. When they are, they return a Boolean value. However, the && and || actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value.
MDN: Logical Operators
Because you are using the logical operator with non-Boolean values, the result will be non-Boolean as well.

Logical OR with a variable and a function definition as operands [duplicate]

This question already has answers here:
What does the construct x = x || y mean?
(12 answers)
Closed 6 years ago.
I saw this line when I was reading a custom library created by a third party developers. What does this do in Javascript? Does it perform Logical OR on "modifier" and a return value from the function?
modifier = modifier || function( x ){ return x; };
Yes.
More in detail, it checks if modifier evaluates to true; in this case it assigns modifier value to modifier variable (noop); otherwise it assigns an anonymous function to modifier.
It returns modifier, if it has a truthy value, like function. Otherwise it returns a function without calling it.
Yes. In JavaScript, the || returns the left if it is a truthy value or the right if the left is a falsy value.
Effectively, if modifier is already a function, it will just leave it set. If it is undefined or null, it will set a reference to the right side function. It will not evaluate the function, however.
It would look like this if evaluated.
modifier = modifier || function( x ){ return x; }(); // notice the method invocation
The || operator is a lazy one. If it has the means necessary to compute it's value it doesn't evaluate the rest of the expression. The value of the logical operation OR is true when one of the parameters is true, so if modifier is considered to be a true value it will return itself and when not it returns the second parameter.
To see what is considered true in JS check here.

use of OR in javascript object in my case confusion [duplicate]

This question already has answers here:
Javascript || operator
(5 answers)
Closed 8 years ago.
Question 1
What does options.left = options.left || _KSM.drawOption.left means? I know _KSM.drawOption is referring to the object (also a function), but how does the || operator work here? Does it mean if _KMS.drawOption.left is undefinded, assign options.left to options.left?
Question 2
Why the author didn't use this keyword in this case? I assume it's because in this demo he didn't create an instance, because he just do the calling once. Rigtht? (I've seen a lots of this in jquery plugin that's why I'm consufed when the author call the function name instead of this within a function)
Question 1
This is a way to set a default value to a variable. It actually evaluate the left side and if it is falsy, the variable will be equal to the right side (even if it is also falsy).
That is a bad way of assigning default variable especially when working with integer. 0 is considered as falsy, so you will never be able to assign 0 as a left property. Instead, it will always be the default parameter of _KMS.drawOption .
Question 2
We don't have the full code so we can only assume. But my assumption would be that draw is an event, a function bind with addEventListener. That mean the context (this value) is the target of the event. My guess would be a canvas.
Logical Operators in JavaScript work a bit differently than most people expect.
Logical OR (||)
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.
So instead of the expression resulting in a boolean value, it returns the first value that isn't "falsey". This has the benefit of being a great way to fill in default values in case it is undefined, null, 0, or an empty string.
var myObj = { name: 'Josh' };
myObj.age = myObj.age || 33;
Logical AND (&&)
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.
Basically just the opposite. Since any expression that evaluates to false will short circuit the logical check, it can be useful to test for the existence of a field, before trying to use it.
var myObj = null;
if(myObj && myObj.person && myObj.person.name === "Josh") // false, no error
var myObj = {};
if(myObj && myObj.person && myObj.person.name === "Josh") // false, no error
var myObj = {person: {}};
if(myObj && myObj.person && myObj.person.name === "Josh") // false, no error
var myObj = {person: {name: "Josh"}};
if(myObj && myObj.person && myObj.person.name === "Josh") // true
However! Caution should be taken here because in the case of both boolean values true or false and integer values 0 or anything not 0 you might end up overwriting a legitimate value.
Question 2: Not enough context

Why does this Javascript line contain just the function name and the function call? [duplicate]

This question already has answers here:
What is "x && foo()"?
(5 answers)
Closed 8 years ago.
I'm reading the source code for the Twitter Bootstrap Tabs Plugin and there's a line that appears to be short hand for something, but I don't understand what it is. Here's a snippet from the source (version 3.0.0):
Tab.prototype.activate = function (element, container, callback) {
var $active = container.find('> .active')
var transition = callback
&& $.support.transition
&& $active.hasClass('fade')
function next() {
$active
.removeClass('active')
.find('> .dropdown-menu > .active')
.removeClass('active')
// some code removed for conciseness
callback && callback()
}
The line in question is this: callback && callback().
I've never seen a function or variable name just typed out like that and then a function being called after the && operator.
I'm guessing this is short hand. What is it and what is it meant to do? And how does it work?
It is shorthand for
if (callback)
{
callback();
}
Basically if the first part is null (or undefined) which both equate to false, the && (logical and) fails and it does nothing.
If the callback is defined, the first part of the && is true, so it evaluates the second part (in this case calling the method).
This is known as short-circuiting as an initial false on the left hand side of the logical AND operator means it does not attempt to evaluated the second part of the expression on the right hand side (as it has already failed the test for "is everything true"). Note: not all languages implement short circuiting in logical AND expressions (VB does not from memory), but javascript is one of the sensible ones! :)
For those that care about the finer points of undefined vs null vs 0 checks:
http://www.sitepoint.com/javascript-truthy-falsy/
*Disclaimer: The code example was intentionally simple and performed by a trained stunt-coder. Please do not attempt this at home. It is dangerous and may lead to down-votes :)
The && operator works like this:
a && b
Evaluate a
If a is falsy, return a
Return the result of Evaluate b
So, the line your mentioned is equivalent to this:
if the value of callback is truthy, call callback as a function
You can easily trip up this code if you supply callback as non-zero number, non-empty string or object, but if you supply a function or nothing (that's what the author of the code expects), then it will work properly and only call the callback if it is provided.
EDIT:
Truthy/Falsy explained in short:
Falsy values: undefined, null, false, 0, '', NaN
Truthy values: everything else
Longer explanation: http://www.sitepoint.com/javascript-truthy-falsy/
It will check if callback exists and if it does then it will run it. The reason is the && operator which will short circuit in the case that the first argument is false. So if callback does not exist it will not check the second half
It's the same as:
if (typeof callback != "undefined"){
callback();
}
All objects are considered to be true.
Strings are considered to be false if they are empty.
null and undefined are considered to be false.
A Number is false if it is zero.
http://msdn.microsoft.com/en-us/library/ie/719e8e30%28v=vs.94%29.aspx
and in logical && if first one is false so is the entire statement. hence if there is no callback (false), then next part of the && won't execute (which is the callback() function calling)!

What kind of Javascript notation / shortcut is this? [duplicate]

This question already has answers here:
Javascript || operator
(5 answers)
Closed 9 years ago.
Came across the following on someone's site and I'm curious to understand the shortcut applied here. I simplified the variables for demo purposes.
function(){
_imaboolean || ($element.removeClass("hidden").addClass("visible"), this.imaboolean = !0)
}
Same thing with
this._imaboolean && ($element.removeClass("visible").addClass("hidden"), this._imaboolean = !1)
That is some awful "clever" code, however, let's decompose it!
_imaboolean || ($element.removeClass("hidden").addClass("visible"), this.imaboolean = !0)
First, let's replace all the expressions with placeholders (note these expressions are not pure and have side-effects):
a || (b, c)
Note that || is short-circuiting such that the right expression - (b, c) - will only be evaluated if a evaluates to a false-y value.
So, let's assume that a evaluates to a false-y value, then (b, c) is evaluated. In this case the , operator separates sub-expressions; all the sub-expressions are evaluated in order. The result of the expression is the result of the last sub-expression.
This means it is roughly equivalent to (although there is no function or binding context and the result is thrown out anyway):
(function () { b; return c })()
Did that make sense? No, of course not!
Write it like you mean it:
if (!_imaboolean) {
$element.removeClass("hidden").addClass("visible");
this.imaboolean = true; // get rid of !0 too
}
This code can be inflated to:
function() {
if (!this.imaboolean) {
$element.removeClass("hidden").addClass("visible");
this.imaboolean = true;
}
}
The || is used as a short circuit, if imaboolean is true it will break out, however if it's false it will execute the remaining portion of the expression. !0 is a minified way of saying true (because 0 evaluates to false in a boolean expression).
I believe it is short for
function(){
if( ! _imaboolean){
$element.removeClass("hidden").addClass("visible");
this.imaboolean = true;
}
}
Its also generally terrible coding in my opinion and should not be copied.
It's a short-circuit evaluation where the second part will only be evaluated if the first part fails.
function(){
_imaboolean || ($element.removeClass("hidden").addClass("visible"), this.imaboolean = !0)
}
Let's break this down. First we see the || operator, so we have (statement) || (anotherStatement). The way || works is that it evaluates the first statement. If that evaluates to true, it short-circuits and does not evaluate the second statement. The first statement is just _imaboolean. If that's a truthy value (i.e., not 0 or false or undefined...), then we stop right there and don't go to the second statement.
The second statement is
($element.removeClass("hidden").addClass("visible"), this.imaboolean = !0)
Again, there's two statements, separated by a comma. The comma operator evaluates BOTH statements, and returns the last one. So it evaluates $element.removeClass("hidden").addClass("visible") (which sets some classes on $element), and then it evaluates this.imaboolean = !0 (which sets this.imaboolean to a truthy value). The next time this function is run, it will short circuit due to the || operator.

Categories

Resources