What is the correct use of the || in javascript - javascript

In the code below, because s is null d = "test"
but if s = "hello" then d would = "hello".
Is this correct as it works? what is the correct way to use ||
var s = null;
var d = s || "test";
alert(d);

|| is "or" ; and understanding what happens here is a bit trickery
var a=false;
var b=true;
result=a||b
will give "result" true (as b is true). What happens is:
'a' is checked - it is false
'b' is checked AFTERWARDS (as no "true" result has been obtained yet, and ONE "true" result would suffice to make the whole || operator be true) - the value of it will be assigned to the left side
if you had
var a=true;
var b="test";
result=a||b
result will yield true; as no other value needs to be checked by the logic of "||"
with
var a=null;
var b="test";
result=a||b;
a will be checked first - it is null, which converts to "false". b is "test", which is non-null, and converts to "true". so the value of b will be assigned.
And yes, this is a correct way to use || ; the feature you use is also called short-circuit evaluation (as it stops evaluating the boolean expression as early as possible)

This works, but if s evaluates to a 'falsy' value, you'll get your default, which might not be what you intended. A more robust, but wordy idiom is
d = (typeof s === "undefined") ? "test" : s;

Yes it is correct unless s is allowed to be blank or 0 which are also falsy values
var s = null;
var d = s || "test";
var s = 0;
var d = s || "test";
var s = "";
var d = s || "test";
All will result in d being "test"

|| is a logical operator. When s is not null then the condition of (s) is true so d is assigned the value of s, otherwise it is assigned 'test'

|| is the OR operator in javascript
so a||b means a OR b in simple terms
explanation of question you have asked is that id you simply do somethings like these in js you will ultimately get in the else block
if(null)
if(undefined)
so s||"test" will mean which ever is not null or undefined
which in this case is test

yes correct, || symbols just does the job of OR. when the first condition is true its gonna return that one.. else it will move to the next... simple as it is...

Related

How to get the variable that triggered the if function?

So, I'm working on a game, and I want it so that if any of the variables are "NaN" or undefined, variableThatTriggeredThis will be set to 0.
I didn't try anything so far, I have no ideas how I can fix it.
if(example == NaN || foo == NaN || bar == NaN) {
variableThatTriggeredThis = 0;
}
I also wanted to ask if there's a way to select every variable in the code, or for example multiple variables, just like var(one, two) == "100".
You can check variables directly. NaN or undefined are valued as false.
Then use Logical OR ||
expr1 || expr2 If expr1 can be converted to true, returns expr1; else, returns expr2
Example:
example = example || 0 ;
foo = foo || 0 ;
bar = bar || 0 ;
There are several ways you could write this. Here's one option using array destructuring:
let a = 10;
let b = 0/0; // NaN
let c; // undefined
const undefinedOrNaNCheck = value => (value === undefined || Number.isNaN(value)) ? 0 : value;
[a, b, c] = [a, b, c].map(undefinedOrNaNCheck);
console.log([a, b, c]);
To coerce a variable into a number (defaulting to 0):
example = isNaN(example) ? 0 : example * 1;
To process several variables, one approach is to create a parent object:
const scores = {};
scores.example = 10;
scores.foo = undefined;
scores.bar = 'not a number';
... allowing iteration like this:
Object.keys(scores).forEach(function(key) {
scores[key] = isNaN(scores[key]) ? 0 : scores[key] * 1;
});
Here's a working fiddle.
If you're supporting an older version of javascript (eg. older browsers) you'll need to use "var" instead of "const" and use a "for" loop instead of the "forEach" loop shown above.

Why does ( true && 1 ) return 1, but ( 1 && true ) returns true?

In C I know true and false evaluate to 1 and 0 respectively. show in this case just prints to the screen... Not sure what's going on here. I'm expecting to get true back. This 1 is messing up my karma.
show(1 && true);
true
show(true && 1);
1
Simply put - that's how && is defined. In Javascript, a && b returns a if a is falsy and b if a is truthy.
Conversely a || b returns a if a is truthy and b if a is falsy.
This makes sense intuitively - if a is false in a && b, then why bother reading the rest of the expression? You already know the whole thing is false. So just return false. But Javascript makes the decision to return a, which is falsy, instead of making up the value false to return out of nowhere.
This is based on short-circuit evaluation common to all C-style languages.
It allows for much expressiveness in Javascript. For instance this pattern:
var foo = function(opts) {
opts = opts || {}
// ...
}
Implements an optional parameter opts. If opts is not passed in at all, opts = opts || {} will set opts to {}, so the rest of the code does not have to know opts wasn't passed.
In long-hand it is equivalent to the following:
var x = a || b; // is equivalent to
var x;
if(a) {
x = a;
}
else {
x = b;
}
and
var y = a && b; // is equivalent to
var y;
if(!a) {
y = a;
}
else {
y = b;
}
Therefore Javascript can be much more terse than C or Java, because simple if statements can be replaced by || or && entirely. Sometimes this makes the code more terse and less readable and more like Perl, other times it allows for new Javascript patterns, like opts = opts || {}.
Another use is in patterns like
var displayName = user.fullname || user.email;
Which means "use the full name if available; if not, fall back to email." I personally find this expressive and readable, but it's arguably terse and obscure depending on which part of the Javascript community you hail from. Because of examples like this, and essentially the fact that truthy values are far more diverse then falsy values, using short-circuit || is much more common than short-circuit &&, as in your question.

Javascript Value Comparison Explanation

What is the difference between these two conditional statements in Javascript?
function comparisonTest() {
var value = "A value";
var compare1 = 5;
var compare2 = "String";
var compare3 = false;
if (value == compare1 || value == compare2 || value == compare3) console.write("True");
else console.write("False");
}
This works as it should - it returns false because the values don't match. However, when I change the conditional to the following...
function comparisonTest() {
var value = "A value";
var compare1 = 5;
var compare2 = "String";
var compare3 = false;
if (value == compare1 || compare2 || compare3) console.write("True");
else console.write("False");
}
it always returns True. I thought that maybe there would be a shorter way of writing that condition for multiple comparisons (although a loop would function just fine), but this is clearly not a way to approach this.
What is going on behind-the-scenes or, rather, how is it being interpreted so that in the second case it always returns true? None of the values I declared are 1 or true, so that's definitely not the problem.
That's because this:
if (value == compare1 || compare2 || compare3)
is the same as this:
if ((value == compare1) || compare2 || compare3)
And, you will see that compare2is a truthy value which satisfies the || operator. See this MDN article on operator precedence for why the == gets evaluated first which makes your first code block work, but makes your second one evaluate like I've shown.
If you want to compare all of them to value, you have to write it out the longhand way like you did in your first code block where you compare each one separately to value.
You may also want to look into using === more often so then you don't have to worry about possible type conversions making things equal that you never intended to be equal. I have a guideline in my own coding to always used === and !== unless there's an explicit reason to want a type conversion. I believe this saves some accidental bugs. See here for more info.
Here is another option:
function comparisonTest() {
var value = "A value";
var answers = [5, "String", false];
/* IE may requires shim found here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf
*/
if (answers.indexOf(value) === -1) {
// False
} else {
// True
}
}
Unfortunately I do not believe there is a short way to write conditionals in JavaScript.
The reason the second example returns true is because when you evaluate compare2 this is a truthy value in JavaScript.
I recommend this post about truthy and falsey values in JavaScript
As an aside you may want to look into the difference between == and === in JavaScript

If variable is false will it be passed over in Javascript

If co.chkShowRSB is false, what is the expected result? I would expect it to be false, but is this the way it works? And why?
var test = chkShow:co.chkShowRSB || true;
It's true in your case, as true is the second operand of || (so-called 'short-circuit or') operator. The common rule is...
var x = a || b; // = a (and b won't be evaluated), if it's a truthy value, b otherwise
var y = a && b; // = a (and b won't be evaluated), if it's a falsy value, b otherwise.
false || true
is true. There is no case where a boolean term with "or true" can be false.
Ok, so you got the picture by now x = false || true; assigns true. Why? It's quite easy knowing the use of the short-circuit-operator is the same as doing:
x = (false ? false : true);
However, it's mostly used to set default values for function arguments, so I'm guessing you're assuming x to be assigned the second operand if the first is undefined. There is no way to filter out undefined values exclusively except for explicitly checking for them. You should then use:
x = val === undefined ? defaultVal : val;
Or, because undefined needn't be undefined, and you want to be absolutely sure:
x = (function(val,undefined)//second argument will be the true undefined value
{
return (val === undefined ? defaultVal : val);
})(val);//don't pass second argument
you should use tertiary operator. your code will always return true if chkShow:co.chkShowRSB is boolean;
var test = chkShow:co.chkShowRSB == false ? false : true;

JavaScript || or operator with an undefined variable

I have been doing some reading lately one article I read was from Opera.
http://dev.opera.com/articles/view/javascript-best-practices/
In that article they write this:
Another common situation in JavaScript
is providing a preset value for a
variable if it is not defined, like
so:
if(v){
var x = v;
} else {
var x = 10;
}
The shortcut notation for this is the
double pipe character:
var x = v || 10;
For some reason, I can't get this to work for me. Is it really possible to check to see if v is defined, if not x = 10?
--Thanks.
Bryan
That Opera article gives a poor description of what is happening.
While it is true that x will get the value of 10 if v is undefined. It is also true that x will be 10 if v has any "falsey" value.
The "falsey" values in javascript are:
0
null
undefined
NaN
"" (empty string)
false
So you can see that there are many cases in which x will be set to 10 besides just undefined.
Here's some documentation detailing the logical operators. (This one is the "logical OR".) It gives several examples of its usage for such an assignment.
Quick example: http://jsfiddle.net/V76W6/
var v = 0;
var x = v || 10;
alert( x ); // alerts 10
Assign v any of the falsey values that I indicated above, and you'll get the same result.
var x = v || 10;
That operator (the "logical" or "short-circuit" OR operator) would normally check the value of v, and if it is a "falsy" value (i.e. it would fail as a condition used in an if statement), 10 becomes the value of x, otherwise v does (and if 10 were a function, it would never be executed).
undefined, null, and 0 are all examples of falsy values that a variable can hold (yes, even the first one), and the operator (or if statement) acts accordingly. In contrast, all objects and arrays (not including null) are "truthy" values, which allows for such things as this (used in the Google Analytics tracker code):
var _gaq = _gaq || []; // Makes a new array _gaq if it is not already there
However, if the referenced variable is not even declared anywhere within the scope chain, then a JavaScript exception will occur.
One way to avoid this is by declaring all your global variables from the start:
var iAmAGlobalVariable; // Holds the value undefined by default
If this is not possible, you should use the typeof operator. It does not attempt to evaluate its operand, and thus an exception will not occur:
var x;
if(typeof v != 'undefined' && v) {
x = v;
} else {
x = 10;
}
Or even better, if you know that the variable would be a global variable, you can treat it as a property of the global (window) object:
var x = window.v || 10;
If v evaluates to false (for example, 0, null, false) then it won't work. You can manually check for undefined:
var x = v !== undefined ? v : 10;
I would use triple equals with ternary in a function for this.
function myTest(x){
return x === undefined ? true: false;
}
Only returns true if x is undefined
See
(http://www.impressivewebs.com/why-use-triple-equals-javascipt/)
and
(http://jsfiddle.net/V76W6/)
I would just use a try-catch
var x = 0;
try
{
x = v;
}
catch(err)
{
x = 10;
}
Here is how to get it working:
var v; //declare v as undefined
// v = 5; //if uncommented x will be 5
var x = v || 10;
alert(x); //output: 10
http://jsfiddle.net/uLLtu/1/

Categories