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

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.

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.

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

Meaning of || in javascript argument [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What does “options = options || {}” mean in Javascript?
What is the meaning of the || in the second argument?
var obj = this;
var settings = $.extend({
param: 'defaultValue'
}, options || {});
Also would be nice if anyone knows how to search that character("|") here or in google! Thank you
That would be the logical OR. The statement will return the first truth-y value it finds.
In this case, if options is null (or any other value that isn't truth-y) it will evaluate to false. The || will then return the empty object.
That is some kind of fallback value or default value. So if the object is null or false the second value is used.
More importantly in that scenario, if options is not defined then an empty object {} is passed as an argument. Its kind of a side-effect use case of the logical OR operator. More specifically, it uses short circuiting. For example in the below case
a || b
if a is true then b never gets executed, but if a is false then b gets executed. Hence in the example you have shown, if options is not defined and thus false, then {} gets executed and thus passed as a parameter.
|| = or
As in the comparison operator.
|| = "OR". Example:
alert(false || false || false || "I'm valid!"); // alerts "I'm valid"
In your question, the example above demonstrates that the function requires an object for it's options. In this case, if the local variable "options" is not available, then just pass an empty object. Later, in the function that's being called, it's probably setting default values in that new object.

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

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.

What does this JS Expression mean?

What does this JS expression mean? What are we returning?
return dihy(year) in {353:1, 383:1};
This is a return statement that causes the containing function to return a Boolean value.
It calls the function dihy() with the value of the variable year as its argument.
It checks whether the return value is either 353 or 383 (the names of the properties that exist in the object literal). It does not matter what value the property has; it just needs to exist within the object. (That is, 1 is just an arbitrary value.)
If so, the function returns true, otherwise false.
JavaScript programmers sometimes use this approach because it is shorter than checking against each value individually, and it is easy to programmatically add new values to check against:
var foo = {353: 1, 383: 1};
function bar(year) {
return year in foo;
}
alert(bar(1955)); // false
foo[1955] = 1;
alert(bar(1955)); // true
You may want to look at the MDC documentation for the in operator.
It will be true if the call to the function dihy with the argument year is a key in the object {353:1, 383:1} and false otherwise.
It could be rewritten like this for example:
var result = dihy(year);
return result == 353 || result == 383;
This is an expression:
dihy(year) in {353:1, 383:1}
The dihy(year) function call presumably returns a Number value. If that value is either 353 or 383, the expression will evaluate to true, otherwise to false.
Note that your code is not an expression, but a statement, the return statement:
return expression;
So, the return statement will either return true or false.
Returns true or false, depending is the result that dihy() returns 353 or 383 (true for those two, anything else is false).
And it means exactly that... is the result of this function contained in this data collection...
There is no reason to use an object here, i.e. {353: 1, 383: 1}. In fact, the values of 1 are confusing and can make the uninitiated think that the value of 1 is being returned when it is not and is purely arbitrary.
The following is equivalent:
dihy(year) in [353, 383]

Categories

Resources