I wonder, are these absolutely the same:
var a = something1.something2 === undefined ? 1 : something1.something2;
var b = something1.something2 || 1;
No. In the first one, something1.something2 has to be undefined in order to get the value 1. In the second one it merely has to be falsy. There are lots of falsy values: 0, "", NaN, null, undefined, and of course, false.
No they are not.
If you take the value 0 for something1.something2, then in the first case the return value is 0.
The second case returns 1, because of the falsy value of 0.
Related
Can someone please explain JavaScript Truthy and Falsy, using the below sample data. I have read other threads but still confused.
var a = 0;
var a = 10 == 5;
var a = 1;
var a = -1;
From my understanding, I believe that var a = 1; is the only truthy and the rest are falsy - is this correct?
From my understanding, I believe that var a = 1; is the only truthy and the rest are falsy’s - is this correct?
No.
var a = 0;
Number zero is falsy. However, note that the string zero "0" is truthy.
var a = 10 == 5;
This is same as var a = (10 == 5);, so this is falsy.
var a = 1;
var a = -1;
Any non-zero number including negative numbers is truthy.
Quoting from MDN
In JavaScript, a truthy value is a value that translates to true when evaluated in a Boolean context. All values are truthy unless they are defined as falsy (i.e., except for false, 0, "", null, undefined, and NaN).
List of falsy values in JavaScript:From MDN
false
null
undefined
0
NaN
'', "", ``(Empty template string)
document.all
0n: BigInt
-0
There's a simple way to check, which you can use now and forever:
function truthyOrFalsy(a) {
return a ? "truthy" : "falsy";
}
To wit:
> truthyOrFalsy(0)
"falsy"
> truthyOrFalsy(10 == 5)
"falsy"
> truthyOrFalsy(1)
"truthy"
> truthyOrFalsy(-1)
"truthy"
Also see a list of all falsey values in JavaScript.
Truthy -> Value that resolve to true in boolean context
Falsy -> Value that resolve to false in boolean context
For better understanding, `falsy` values are given below.
false
0
empty string
null
undefined
NaN
FALSY
false
0 (zero)
"", '', `` (empty strings)
null
undefined
NaN (not a number)
note : Empty array ([]) is not falsy
TRUTHY
Everything that is not FALSY
The below answer might help someone.
As well as a type, each value also has an inherent Boolean value, generally known as either truthy or falsy. Some of the rules are a little bizarre, so understanding the concepts and effect on comparison helps when debugging JavaScript applications.
The following values are always falsy:
false
0 (zero)
-0 (minus zero)
0n (BigInt zero)
'', "", `` (empty string)
null
undefined
NaN
Everything else is truthy. That includes:
'0' (a string containing a single zero)
'false' (a string containing the text “false”)
[] (an empty array)
{} (an empty object)
function(){} (an “empty” function)
A single value can therefore be used within conditions. For example:
if (value) { // value is truthy } else { // value is falsy // it could be false, 0, '', null, undefined or NaN }
one more check version:
function truthyOrFalsy(a) {
return (a && "truthy") || "falsy";
}
In short there are only 6 types of falsy values:
You can use this snippet to test them:
function isTruthy(val){
if(val){
console.log(val + ' is Truthy');
}else{
console.log(val + ' is falsy');
}
}
// all below are truthy
isTruthy (true)
isTruthy ({})
isTruthy ([])
isTruthy (42)
isTruthy ("0")
isTruthy ("false")
isTruthy (new Date())
isTruthy (-42)
isTruthy (12n)
isTruthy (3.14)
isTruthy (-3.14)
isTruthy (Infinity)
isTruthy (-Infinity)
//all below are falsy
isTruthy(0);
isTruthy("");
isTruthy(false);
isTruthy(NaN);
isTruthy(null);
isTruthy(undefined);
Refer this site for details: https://developer.mozilla.org/en-US/docs/Glossary/Falsy
Easy way to check Falsy Value and True value
function truthyOrFalsy(val){
if(val){
console.log (`${val} is truthy`);
} else{
console.log (`${val} is falsy`);
}
}
Check all FALSY value:
truthyOrFalsy(false); //Output: false is falsy
truthyOrFalsy(null); //Output: null is falsy
truthyOrFalsy(0); //Output: 0 is falsy
truthyOrFalsy(''); //Output: is falsy [blank refers to '']
truthyOrFalsy(NaN); //Output: NaN is falsy
truthyOrFalsy(undefined); //Output: undefined is falsy
Please note that undefined is not explicitly used to set as value.
Some common scenarios will create undefined:
Parameter defined in function but not passed argument in callback function.
If nothing returns in function
If accessing to an object property/method which is not defined
If accessing to an array element which is not defined
function add(num1, num2){
console.log(num1, num2);
}
const result = add(44);
console.log(result);
//Output: 44 undefined
// undefined
const car = {color:"Blue", price: 200000};
console.log(car.category);
//Output: undefined
arrColors = ["Blue", "Sky", "Purple"];
console.log(arrColors[5]);
//Output: undefined
Check all TRUTHY values
All values are truthy unless they are defined as falsy.
Although ' ', '0', -1, [] could be enlisted to be checked.
truthyOrFalsy(' '); //Output: is truty [blank refers to space inside
// quote ]
truthyOrFalsy('0'); //Output: 0 is truty
truthyOrFalsy([]); //Output: is truty [blank refers to an empty array]
truthyOrFalsy(-1); //Output: -1 is truty
Another way to evaluate whether something is truthy or falsy that I like to use is
function truthyOrFalsy(a) {
return !!a;
}
The following code uses the reduce method. It outputs the number of times an element appears in the array. If element appears once then it only outputs 1, otherwise if it is a repeated item then it it is added..
let a = ["a", "b", "c", "a", "b"]
const t = a.reduce((aa, ll) => {
const count = aa[ll];
count
?
aa[ll] = count + 1 :
aa[ll] = 1
return aa
}, {})
console.log(JSON.stringify(t))
// output
// { "a":2, "b":2, "c":1 }
Question is regarding the condition in the ternary operation, specifically the count variable. How is the count variable able to resolve true or false.
The concept is called "Truthy" and "Falsy" respectively. Ie anything that is different from false, 0, -0, 0n, NaN, null, undefined and "" (empty string) can be evaluated to true in Javascript
So your assign var counter = aa[ll] to be the value of the key ll in object aa. That's either a number or undefined. If it's a number !== 0 it's a truthy, if it's 0 or undefined it's falsy. Thus it can be used in a ternary operatator. Depending on the value of counter either the value of the first or the second assignment will be returned (but ignored). The return value of an assignment is always the value of the right hand side ...
While you can use also assignments in the expressions of a ternary operator, I personally wouldn't use it that way but write this assignment as follows
const t = a.reduce((aa, ll) => {
aa[ll] = (aa[ll] || 0) + 1;
return aa
}, {})
(aa[ll] || 0) will return the value of aa[ll] if it's a truthy or 0 otherwise. Thus, in your case, the result of this expression will always be a number >= 0. Then you increase the result by 1 (for the currenct occurence of ll) and assign it back to aa[ll]. This is much shorter than your original code and IMHO much more readable
Heres the answer I found.
"A javascript object consists of key-value pairs where keys are unique. If you try to add a duplicate key with a different value, then the older value for that key is overwritten by the new value."
basically the count variable was checking to see if the new property already exists.
I saw in a pull request that the double negation operator (!!) is used for the focus attribute of a text field as follows:
focused: !!value || value === 0,
As far as I know, the operator converts everything to a boolean. If it was falsy (for example 0, null, undefined,..), it will be false, otherwise, true.
In my case, i.e. if value = 0, the following comes out:
focused: false || true
The || operator here therefore makes no sense for the value 0 or am I completely confused?
It looks like a check for numbers to get false for '', "", false, NaN, undefined and null. Other bjects, like functions, arrays or simple objects returns true;
const check = value => !!value || value === 0;
console.log(check(0));
console.log(check(1));
console.log(check(''));
console.log(check(""));
console.log(check(false));
console.log(check(NaN));
console.log(check(null));
console.log(check(undefined));
console.log(check({}));
Im brand new to javascript. I simply have an exercise where i need the array numbers to add each index to the next one.
The result should be:
var result = [4,8,15,21,11];
I tried something like this. It works on the first 4 indexes, however gives NaN on last since it doesnt have a next number to add to.
var numbers = [1, 3, 5, 10, 11];
var result = numbers.map((x, index) => x + numbers[index + 1])
console.log(result)
Is there any smarter way to do this and how do i get index 4 to stay as 11? And please explain as im trying to learn.
That's a perfectly valid way to do it. You can handle the last index by taking advantage of the fact that numbers[index] will be undefined (not an error) if index is beyond the end of the array, and undefined is a falsy value, so you can use || 0 to use 0 instead of undefined if it's there:
var result = numbers.map((x, index) => x + (numbers[index+1] || 0));
Live Example:
var numbers = [1, 3, 5, 10, 11];
var result = numbers.map((x, index) => x + (numbers[index + 1] || 0));
console.log(result);
|| is the logical OR operator, but it's a bit special in JavaScript: It evaluates its left-hand operand and, if that value is truthy¹, takes that value as its result; if the left-hand is falsy, the operator evalutes the right-hand operand and takes that value as its result.
In ES2020+ you can use the new nullish coalescing operator (??) instead of ||:
var result = numbers.map((x, index) => x + (numbers[index+1] ?? 0));
That will only use the 0 if numbers[index] is null or undefined, rather than if it's any falsy value.
¹ "truthy" and "falsy" - A truthy value is a value that evaluates to true when used as a condition (for instance, if (x) or x || y); a falsy value is a value that evalutes to false. The falsy values are 0, "", NaN, null, undefined, and of course, false. All other values are truthy. (Except there's a special case on browsers: document.all is falsy for legacy reasons.)
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;