What does || mean in JavaScript? [duplicate] - javascript

This question already has answers here:
Javascript || operator
(5 answers)
Closed 9 years ago.
I'm fairly new to JavaScript. What does || do?

It is a condition operator, meaning “or”, typically used like this:
if (browserIsMSIE || browserIsFirefox) {
…
}

MDN Expressions and Logical statements
(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.
var o1 = true || true; // t || t returns true
var o2 = false || true; // f || t returns true
var o3 = true || false; // t || f returns true
var o4 = false || (3 == 4); // f || f returns false
var o5 = "Cat" || "Dog"; // t || t returns Cat
var o6 = false || "Cat"; // f || t returns Cat
var o7 = "Cat" || false; // t || f returns Cat

It's same as in other C type languages. A Logical Operator, for the OR condition.
Here's the Docs on Mozilla Developer Network.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators

If something1 or something2, do something: equates to this
if (something1 || something2){
... do something
}
If something1 and something2, do something: equates to this
if (something1 && something2){
... do something
}

Related

Is it ok to use javascript `??` operator as shorthand

I normally use ternary operators like:
let foo = str.match(/[*]/g) ? str.match(/[*]/g) : "none!";
Since using PHP, I've noticed the language has a lot of shorthand and for ternary operators, would use:
$foo = $view->test ?? "none";
I have not seen that in javascript (or documentation on it) but tried it like:
let str = "1234";
let foo1 = str.match(/[*]/g) ?? "none;
console.log(foo) // "none"
let str1 = "1*2*";
let foo1 = str1.match(/[*]/g) ?? "none;
console.log(foo1) // ['*','*']
and it seemingly works. Is this an acceptable way of using ternary operators when checking against the existence of an element?
I guess it's totally legit to use the nullish coalescing operator or ??.
See https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator for examples and some documentation on it.
Make sure to check browser compatibility though !
=======
There is also the logical OR || operator which can be used for similiar operations:
o1 = true || true // t || t returns true
o2 = false || true // f || t returns true
o3 = true || false // t || f returns true
o4 = false || (3 == 4) // f || f returns false
o5 = 'Cat' || 'Dog' // t || t returns "Cat"
o6 = false || 'Cat' // f || t returns "Cat"
o7 = 'Cat' || false // t || f returns "Cat"
o8 = '' || false // f || f returns false
o9 = false || '' // f || f returns ""
o10 = false || varObject // f || object returns varObject
Check out : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators for reference

You Don't Know JS: Up & Going - example problem

In page 38 I found - arrays are by default coerced to strings by simply
joining all the values with commas (,) in between. You might think
that two arrays with the same contents would be == equal, but
they’re not:
var a = [1,2,3];
var b = [1,2,3];
var c = "1,2,3";
a == c; // true
b == c; // true
a == b; // false
But when I run my code like the following:
var a = [1,2,3];
var b = [1,2,3];
var c = "1,2,3";
console.log(typeof a == c); // false
console.log(typeof b == c); // false
console.log(typeof a == b); // false
I got different answers! Why typeof a == c and typeof b == c is false here?
its doing
typeof a == c
=> (typeof a) == c
=> "object" == c // which is false
basically typeof operator works before == sign
My cliche advice, always use paranthesis to make your intent clear
typeof (a==b) vs (typeof a) == b
The typeof operator returns the type of the content of a variable as a string. So if your variable a contains an array, typeof a will return the string "object" (as arrays are a special kind of objects).
So typeof a == c and typeof b == c compare the string "object" with the string "1,2,3". As they are obviously not the same, this returns false.
Note that the typeof operator has a higher precedence than the == operator.

That Operator || in console.log() works like || operator?

How it's work for example;
let x;
console.log(x || 2); // 2
if
let x = 4;
console.log(x || 2); // 4
if
let x = 5;
let y = 7;
console.log( y || x || 2);
it's mean that console.log() write first value that is true ?
What you're seeing isn't related to console.log. It's called short circuiting.
When comparing values with ||, it will always return the first truthy value. If no truthy values are present, it will return the last value being compared.
let a = false || true;
let b = false || null || 'b';
let c = undefined || !a || 10;
let d = undefined || false || null; // no truthy values
console.log(a); // true
console.log(b); // 'b'
console.log(c); // 10
console.log(d); // null
let x = 5;
let y = 7;
console.log( y || x || 2); //return 7
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.
Documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators

&& operator on strings in javascript

I have the following expression :
if(a && b === c) {//do something}
What would be the meaning of this condition if I consider that a,b, and c are strings ?
This is equal to if (a == true && b === c). (note that == is lose comparison. Eg. "foo" is loosely equal to true, however "" is not loosely equal to true, hence this says "if a is not an empty string, and b has the same content, and is the same type as c, then do something")).
Examples:
var a = 'foo';
var b = 'bar';
var c = 'bar';
Will be true because a is not falsy (a non empty string is truthy), and b is the same type and has the same content as c.
var a = '';
var b = 'bar';
var c = 'bar';
Will be false because a is falsy (an empty string is falsy).
var a = 'foo';
var b = 'rab';
var c = 'bar';
Will be false because b does not have the same content as c.
var a = 'foo';
var b = true;
var c = 1;
Will be false because b is not the same type as c (boolean vs number - with == this would be true, as true == 1).
Your expression expands to this:
if (a) {
if (b === c) {
// do something
}
}
It first checks that a is some truthy value. It then checks that b and c are of the same value and the same type. Read up on truthy and falsey values in JavaScript.
This means:
a is truthy
AND
b exactly equal to c (including type)
Here a is truthy means it is NOT ('undefined' or "" or 'null' or 0 or 'NaN' or 'FALSE')
if a have some value (not null and "") and b's value (string, case sensitive) is equal to c's value then your code

Testing for equality of regular expressions

I was surprised to see that
/a/ === /a/
evaluates to false in JavaScript. Reading through the specs:
Two regular expression literals in a program evaluate to regular
expression objects that never compare as === to each other even if the
two literals' contents are identical.
Since === cannot be used to test for equality, how can equality of regular expressions be tested in JavaScript?
Here's a case that even covers ordering of flags.
function regexEqual(x, y) {
return (x instanceof RegExp) && (y instanceof RegExp) &&
(x.source === y.source) && (x.global === y.global) &&
(x.ignoreCase === y.ignoreCase) && (x.multiline === y.multiline);
}
Tests:
regexEqual(/a/, /a/) // true
regexEqual(/a/gi, /a/ig) // also true.
regeXEqual(/a/, /b/) // false
Here's a function that fully tests all the relevant regex properties and makes sure it's the right type of object:
function regexSame(r1, r2) {
if (r1 instanceof RegExp && r2 instanceof RegExp) {
var props = ["global", "multiline", "ignoreCase", "source", "dotAll", "sticky", "unicode"];
for (var i = 0; i < props.length; i++) {
var prop = props[i];
if (r1[prop] !== r2[prop]) {
return false;
}
}
return true;
}
return false;
}
And, since flags sometimes get added to the regex object with new features (as has happened since this original answer in 2012 - though the above code has been updated as of 2019), here's a version that is a bit more future proof on future flags being added since it compares whatever flags are there rather than looking for a specific set of flags. It sorts the flags before comparing to allow for minor differences in how the regex was specified that wouldn't not actually change functionality.
function regexSame(r1, r2) {
return r1 instanceof RegExp &&
r2 instanceof RegExp &&
r1.source === r2.source &&
r1.flags.split("").sort().join("") === r2.flags.split("").sort().join("");
}
Compare them using toString(), and check their type too:
var a = /a/,
b = /a/;
a.toString() === b.toString() && typeof(a) === typeof(b) //true
var c = /a/,
d = /b/;
c.toString() === d.toString() && typeof(c) === typeof(d) //false
You can check the types with typeof, then toString() both regexes and compare those. It won't cover cases with equivalent flags, such as /a/gi and /a/ig, though.
function regexEquals(a, b)
{
if (typeof a !== 'object' || typeof b !== 'object') return false;
return a.toString() === b.toString();
}
Unfortunately there's no more-specific type from typeof, so if you really want to make sure they're regexes (or regex-like) you could do something along these lines:
RegExp.prototype.regexEquals = function (other)
{
return (typeof other.regexEquals === 'function')
&& (this.toString() === other.toString());
}
Then:
/a/.regexEquals(/a/); // true
/a/.regexEquals(/b/); // false
Answers above didn't consider case-sensitivity. So built upon jfriend00's answer, the function should be
function regexEqual(a, b) {
if (!(a instanceof RegExp) || !(b instanceof RegExp)) {
return false;
}
let sourceA = a.source;
let sourceB = b.source;
const flagsA = a.flags.split('').sort().join(',');
const flagsB = b.flags.split('').sort().join(',');
if (flagsA.includes('i') && flagsB.includes('i')) {
sourceA = sourceA.toLowerCase();
sourceB = sourceB.toLowerCase();
}
return sourceA === sourceB && flagsA === flagsB;
}

Categories

Resources