Assignment with double ampersand "&&" [duplicate] - javascript

This question already has answers here:
Javascript AND operator within assignment
(7 answers)
Closed 7 years ago.
I just saw someone use this piece of code:
ctx = canvas.getContext && canvas.getContext('2d');
How does the double ampersand work in this context? Would it not just assign "true" to the ctx variable?

This is a common way to make sure your function exists before you call it.
It works like this (From developer.mozilla.com):
expr1 && expr2 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 other words, Javascript does not coerce the operands to boolean values unless it has to.
4 && 5 Returns 5, not true.
In your case, if the first expression is undefined (which is convertible to false), then ctx will be false, and the second expression does not get evaluated. If the first expression is a function (which cannot be converted to false), then Javascript evaluates the second expression, and assigns it's value to the ctx variable.

It will assign the return value of canvas.getContext('2d') to ctx if canvas.getContext is actually a function.
The part on the left is just to avoid an error. It makes sure that canvas has a getContext property before trying to call getContext(). This way, the code won't call canvas.getContext() if the function doesn't exist. If it didn't check first and called when the function didn't exist, an error would be logged to the console and execution would halt.

Related

Checking value with JavaScript [duplicate]

This question already has answers here:
How does the single equal sign work in the if statement in javascript
(6 answers)
Closed 3 years ago.
This is my general code (in JavaScript):
let x = Math.floor(Math.random()×6)+1);
if (x=1){
do this
} else if (x=2){
do that
} else if.... and so on.
Whenever I test this code in a browser, only actions that could happen in the {do this} section happen. x is being locked as 1, even though it is meant to be a fair 6 sided die. Any ideas why this is happening, and how I can fix it?
The = operator in JavaScript is for assignment. x=1 will always return true because that is an assignment that will never fail. To test for equality use == (equality with conversion) or === (strict equality).
You have your if (x=1) assigning the value of 1 to x, rather than checking if it's equal to it. This results in it always returning TRUE. Using a pair of == (or ===) will solve this.

How do multiple OR's || work in JavaScript? [duplicate]

This question already has answers here:
javascript multiple OR conditions in IF statement
(6 answers)
Closed 3 years ago.
if(eggsAmount < eggsMin || milkAmount < milkMin || flourAmount || FlourMin)
Does it mean whichever of these are true?
Yes, in an if statement with only OR || operators, it will simply go through each condition and as soon as it finds one that is true, the if statement resolves as true, the rest are not checked, and the code in the if block.
An if statement containing multiple OR conditions (||) has in Javascript the same behaviour descripted by Boolean Algebra: the whole evaluation is True if any of the conditions is true.
At this w3schools link you can find JS logic operators description.
Anyway the evaluation of the expression itself is not necessarily a boolean value. The expression
Res = expr1 || expr2 || ... || exprN
is evaluated as the first condition that can be evaluated as true (for example if expr1 is 4+7, Res=11.
If none of the condition can be evaluated as true the assigned value is the value contained in the last condition: Res = exprN.
(thanks to Jared Farrish, Barmar and Teemu)

JavaScript declaring variable as " g = g || {}; " what does it means? [duplicate]

This question already has answers here:
What does the construct x = x || y mean?
(12 answers)
Closed 7 years ago.
Good day, was reading a JavaScript script library and come across this
var g = g || {};
What does this means?
This is a way to ensure g is actually initialized as an object. It is the same as:
if(!g) g = {};
The || is an OR. The second operand will be returned only if the first one evaluates to false.
It means, that if g is 0/null/undefined, the g will be defined as an empty object.
The common way:
function foo(g) {
// If the initial g does not defined, null or 0
if(!g) {
// Define g as an empty object
g = {}
}
}
JavaScript returns the first argument if true, otherwise the second one. This is equivalent to an OR.
So in your example, if g is not set, it is set to an empty object.
Following description is taken from this page.
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 can be converted to true; if both can be converted to false, returns false.
In your case, if g has a falsy value (false/null/undefined/0/NaN/''/(document.all)[1]), then g will be set with {}

How can jquery || "OR" be used outside of an if statement? [duplicate]

This question already has answers here:
JavaScript OR (||) variable assignment explanation
(12 answers)
What does the construct x = x || y mean?
(12 answers)
In Javascript, what does it mean when there is a logical operator in a variable declaration? [duplicate]
Closed 8 years ago.
I've never seen the OR paramater || used outside of an if statement.
What does this line of code do?
var doc = ($iframe[0].contentWindow || $iframe[0].contentDocument).document
Is it saying making it equal to either one of those???
A || B
evaluates A first. If it is true, A is returned, and B never needs to be looked at.
If A is false, B is evaluated and returned.
For example, if you write
function (x)
{ x = x || 50
...
This would make x=50, if x is nil (or some kind of false value).
Otherwise, x would not be changed.
It is like having a default value, or a failsafe protection. If you know that the answer should never be false, then if A is false, you provide a backup value of B.
A way to get a DOM reference to the iframe's window object is to use:
contentWindow.document
Now, cause IE<8 has problems with it, a small polyfill is to use
var doc = ($iframe[0].contentWindow || $iframe[0].contentDocument).document;
// Browser you get this one ^^^ ? NO? Sh** you're IE7, go with^^
So earlyer versions of IE will skip the contentWindow cause not recognized, and thanks to the || (or) operator will follow up with the next contentDocument.
I don't have to repeat what's the OR operator cause other smart people already explained it: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators
This is just a short form of the ternary operator, which always returns a value depending to a statement. So, e. g.:
var fruit = "apple";
var test = fruit === "apple" ? fruit : "banana";
This sets the variable test to the value of fruit, when fruit is set to "apple". Otherwise, test will be initialized with "banana".

What it exactly means in Javascript (assigning variable) [duplicate]

This question already has answers here:
Is there a "null coalescing" operator in JavaScript?
(19 answers)
What does "var FOO = FOO || {}" (assign a variable or an empty object to that variable) mean in Javascript?
(8 answers)
Closed 9 years ago.
I have question because I am not sure and cannot find answer on Stack Overflow about this.
What this exactly mean:
variable = variable || {}
or something that:
this.pointX = options.pointX || 6;
I understand that it assign to variable a variable if it exist or empty Object if variable doesn't exist but why it working that?
Is || not mean 'or' here?
The || is effectively working like a SQL COALESCE statement.
var x = y || z;
means:
if y evaluates to a "truthy" value, assign y to x.
if y evaluates to a "falsy" value, assign z to x.
See http://11heavens.com/falsy-and-truthy-in-javascript for more detail on "truthy/falsy" (or just google it).
The || is an or operator.
It basically means if variable is undefined, it will assign variable to a new object literal.
https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Expressions_and_Operators#Logical_operators
|| does mean OR here:
var x = 5
var x = x || {} //If v is defined, v = v, else v = {} (new, empty, object).
//x = 5 since x already was defined
var y = y || {}
//y = {} since y was undefined, the second part is run.
The || operator returns the actual object that determines its "truthiness" value, not just a boolean (true or false). It "short circuits" in that once it can determine the result, it stops.
If variable has a truthiness value of true, it is returned (since when true is ored with anything, the result is true). Otherwise, the second operand is returned (even if it has a truthiness value of false) since it determines the truthiness of the whole expression.
this.pointX = options.pointX || 6;
Means assign this.pointX the value of options.pointX if available(i.e. not null) otherwise assign the value of 6
The || operator in JavaScript differs from some other languages you'll find it in. When JavaScript evaluates || it seems to return one operand OR the other. It doesn't do a typical truth table evaluation evaluating to true if any operand evaluates to true, and false if not.

Categories