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

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

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

Why || operator is behaving like this?

Why _value is foo on second function call? It took me a while to find this bug.
function doSomething(value) {
console.log('should be:', value);
const _value = value || Math.random() > 0.5 ? 'foo' : 'bar';
console.log('actually is:', _value);
}
let values = ['foo', 'bar'];
const first = doSomething(values[0]);
const second = doSomething(values[1]);
To understand better I put a parenthes around the testing code:
(value || Math.random() > 0.5)
Since value is always defined (non null) the condition avaluates to true and assigns 'foo' to '_value'
Hope this explains it for you.
Because the expression
const _value = value || Math.random() > 0.5 ? 'foo' : 'bar';
is evaluated as:
const _value = (value || (Math.random() > 0.5)) ? 'foo' : 'bar';
The conditional operator has lower precedence than other operators in the expression.
value is a non-empty string, so it evaluates to true in boolean context. Thus, the condition evaluates to true, and the final result is always 'foo'.
Because:
> 'bar' == true
false
So:
const _value = value || Math.random() > 0.5 ? 'foo' : 'bar';
_value will be randomly assigned the value 'foo' or 'bar', because value is 'bar' which evaluates to false, so the second half of the or-expression || is evaluated and assigned to _value.
Try this.
const _value = value || (Math.random() > 0.5 ? 'foo' : 'bar');
Because JS in your code check such
`if(value || Math.random() > 0.5){
_value = 'foo';
}else{
_value ='bar'
}`
The construct const a = b || c is common Javascript shorthand. It means:
If b is not falsy assign it to a. Otherwise assign c to a.
It can also be written const a = b ? b : c; or
const a;
if (b) a = b;
else a = c;
A value is falsy generally speaking if it is empty or has the value zero.

What does this condition do in ternary?

Javascript Ternary Condition
I have javascript with this condition, what is this?
var y = (typeof x !== undefined) ? x || 0 : 1;
This (typeof x !== undefined) ? x || 0 : 1; is going to return always true because the typeof operator will return a string.
That condition should compare a string as follow:
(typeof x !== 'undefined') ? x || 0 : 1;
var x;
var str = typeof x !== 'undefined' ? x || 0 : 1;
console.log(str);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Conditional (ternary) Operator explanation:
+--- When condition is true
|
| +--- When condition is false
| |
| |
v v
typeof x !== 'undefined' ? x || 0 : 1;
^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| |
| +---- The condition should be:
| (x === undefined ? 1 : x || 0)
|
+--- Checks for the type of x
Code refactored
var x = 4;
var str = x === undefined ? 1 : x || 0;
console.log(str);// should return 4
var y;
str = y === undefined ? 1 : y || 0;
console.log(str);// should return 1
y = null;
str = y === undefined ? 1 : y || 0;
console.log(str);// should return 0
y = 5;
str = y === undefined ? 1 : y || 0;
console.log(str);// should return 5
y = 5-"5";
str = y === undefined ? 1 : y || 0;
console.log(str); // should return 0
.as-console-wrapper { max-height: 100% !important; top: 0; }
Docs
Conditional (ternary) Operator
typeof
First, there is an error with the condition:
(typeof x !== undefined)
because you are comparing a type against a value.
typeof always returns a string, while undefined is a value. So, whatever type x is, it will be returned as as string. Even if it's value is undefined, "undefined" (notice the quotes?) will be returned as its type and since the string "undefined" has a typeof === "string", the condition will actually branch into the true section, even when x actually is undefined.
So, it needs to be: (typeof x !== "undefined").
Or, you could test the value of x against the value undefined:
(x !== undefined)
But, you can't mix and match values and types.
Now, assuming we correct that, the next part (the true branch):
x || 0
Simply returns x, as long as it is not "falsy" (that is, any value that would convert to the Boolean false). 0, false, NaN, undefined, "" or null are all falsy. So, if x is not falsy, x is returned. If x is falsy, then 0 is returned. This is a way to provide a default return value in case the first value doesn't exist. But, the logic is a bit off here, because if the code has entered the true branch, it's because x is not undefined, which means it's "truthy". And, if it's truthy, then we can safely just return x. So, it really should just be:
x
Finally, the last part (the false branch)
1
Is what will be returned if the original condition is false. In this case, if x is undefined.
So, the code has flaws in it and really should be:
(typeof x !== "undefined") ? x : 1
EXTRA CREDIT:
In reality, any expression you place into the condition of an if statement is going to be converted to a Boolean for the if to do its job. If all you need to know is if x is not a "falsy" value, then all you need to do is write:
x ? x : 1;
The x will be converted to a Boolean.
If it's true (truthy), then x is returned.
If it's false (falsy), then 1 is returned.
Examples:
function testX(x){
return x ? x : 1;
}
// Truthy:
console.log(testX(10)); // 10
console.log(testX({})); // {}
console.log(testX(true)); // true
console.log(testX("something")); // "something"
// Falsy:
console.log(testX("")); // 1
console.log(testX()); // 1
console.log(testX(4-"Z")); // 1 because 4-"Z" == NaN
console.log(testX(false)); // 1
console.log(testX(0)); // 1
console.log(testX(null)); // 1
The condition
(typeof x !== undefined)
asks if x is not of type undefined. Or, if x is defined. This will include any value or even null.
...? x || 0
If so, the expression evaluates to this. Which is the value of x in most cases or 0 if x is anything evaluated to be boolean false, e.g., null, false, etc.
... : 1;
Otherwise (i.e. case when x is undefined), evaluates to 1.
Typing in Javascript is complicated (in my opinion), sometimes it is not easy to remember what it is when you're comparing mixed type stuff, see https://dorey.github.io/JavaScript-Equality-Table/ for a summary matrix.
Admitting that you have a left-hand operand, it does the same thing as :
var y;
if(typeof x !== undefined) {
if(x)
y = x;
else
y = 0;
}
else
y = 1;

When can != be used instead of !==?

Consider the code snippet below from this AngularJS tutorial:
app.factory('Auth',
function ($firebaseSimpleLogin, FIREBASE_URL, $rootScope) {
var ref = new Firebase(FIREBASE_URL);
var auth = $firebaseSimpleLogin(ref);
var Auth = {
register: function (user) {
return auth.$createUser(user.email, user.password);
},
signedIn: function () {
return auth.user !== null;
},
logout: function () {
auth.$logout();
}
};
$rootScope.signedIn = function () {
return Auth.signedIn();
};
return Auth;
});
I understand the difference between != and !== is the first compares by reference and the second compares by value. Since the comparison here is to null, then why has the developer chosen to use !== instead of !=? Is my understanding correct that both would work here?
== / != operator only compares the value of the variables, not the type
=== / !== operator compares the type and the value of the variables
Some examples:
var varA = 5; // int
var varB = '5'; // string
var varC = 5; // int
if(varA == varB) // true (only value compared)
if(varA === varB) // false: because varB is of type string and varA of type int
if(varA == varC) // true
if(varA === varC) // true: because varA and varC are of the same type and have the same value
I often use "if(x != null)" to check if x is either null or undefined. It's safer than just saying "if(x)" since there are other falsey values besides null and undefined.
Here's an overview table, for your convenience: http://jsfiddle.net/QQcVw/1/
0 "" false null undefined
0 Y Y Y n n
"" Y Y Y n n
false Y Y Y n n
null n n n Y Y
undefined n n n Y Y
As you can see, == considers equal three empty "values" (0, "" and false) and two "non-values" (null and undefined). See javascript standard for the exact algorithm.
In most cases, it's a good idea to avoid == and always stick to ===.

What does || mean in JavaScript? [duplicate]

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
}

Categories

Resources