Using Ternary Operator to Handle Three Different Conditions - javascript

I'm using the ternary operator to handle importing data from SQL to Mongo for a variety of fields. For one particular field it's a little trickier than the others, because I want to handle three different conditions:
1 should port to true,
0 should port to false,
and null should port to null.
This is what I'm trying:
saved: data.saved && data.saved === 1 ? true : data.saved && data.saved === 0 ? false : null
Would this accomplish what I'm needing?

You could take a direct check for null and if not convert the numerical values to boolean.
value === null ? null : Boolean(value)

You can just coerce the value to boolean:
saved: (data === null) ? null : !!data

Related

Can someone explain this simple concept of null and undefined, more specifically single double & triple equals, or can you link the best explanation [duplicate]

This question already has answers here:
why null==undefined is true in javascript
(6 answers)
Closed 1 year ago.
How is null equal to undefined and not equal to undefined within the same operator.
undefined == null
true
undefined !== null
true
undefined === null
false
undefined != null
false
== converts the variable values to the same type before performing the actual comparison(making type coercion)
=== doesn't do type coercion and returns true only if both values and types are identical for the two variables being compared.
Let's take a look at some examples:
console.log(5 == "5"); // no type coercion is being made - hence, the result is true.
console.log(5 === "5"); // type coercion is being made, value is the same but the data types are not (number vs string);
console.log(undefined == null); // should be true because type coercion is not being made and the data values are both falsy!
console.log(undefined !== null); // should be true cause type coercion is being made and the data types are differnt!
console.log(undefined === null); // // should be false cause type coercion is being made and the data types are differnt.
console.log(undefined != null); // should be false cause type coercion is not being made and the data values are both falsy!
Undefined and null are empty variables. But to understand whats above you have to understand comparison operators. == is a comparison operator that can convert. === really tests if its the same without doing type conversion. So null is practically the same as undefined. Its a bit hard to understand when you first think about it but its really not that hard. Some examples:
'' == '0' // false
0 == '' // true
0 == '0' // true
false == 'false' // false
false == '0' // true
false == undefined // false
false == null // false
null == undefined // true
Please find my answer below.
"==" coerces the type of the variable before making a comparison.
i. so undefined == null is true since both the variables coerces to false (since they both indicate an empty value) and post that comparison is made making them equal.
!== makes a strict comparison so the type is not changed, in case of undefined the type is "undefined" and in case of null the type is "object" which can be verified using typeof.
ii. so since the type does not match,!== return true i.e. undefined !== null.
iii. Same way === makes a strict comparison, so undefined === null is false, since the type is only different
iv. Lastly undefined != null is false, since != like == coerces the type of the variables to false, and then compares. Hence they both seem equal to != and it return false.

How can I set firebase rule for switch button

in the realtime firebase
the child Button's value is 'true'
I want new value has to be only 'false' while it is 'true'
the opposite, it has to be true
how can I code up for firebase rule?
guessing to use data.exists() or 'true' or 'false' as string
but using data.exists() is further reaching to me.
Something like this should work:
".validate": "
(data.val() === 'true' && newData.val() === 'false') ||
(data.val() === 'false' && newData.val() === 'true')
"
Note that I use string values since you mentioned those in your question, but I usually would store boolean values in an actual boolean node.

Determining string length in Node JS when string may be null

I'm trying to learn Node and have the function:
this.logMeIn = function(username,stream) {
if (username === null || username.length() < 1) {
stream.write("Invalid username, please try again:\n\r");
return false;
} else {
....etc
and I'm passing it
if (!client.loggedIn) {
if (client.logMeIn(String(data.match(/\S+/)),stream)) {
I've tried both == and ===, but I'm still getting errors as the username is not detecting that it is null, and username.length() fails on:
if (username === null || username.length() < 1) {
^
TypeError: Property 'length' of object null is not a function
I'm sure that Node won't evaluate the second part of the || in the if statement when the first part is true - but I fail to understand why the first part of the if statement is evaluating to false when username is a null object. Can someone help me understand what I've done wrong?
length is an attribute, not a function. Try username.length
You're passing String(data.match(/\S+/)) as username argument, so when data.match(/\S+/) is null, you get "null" not null for username, as:
String(null) === "null"
So you need to change your condition:
if( username === null || username === "null" || username.length < 1 )
If you require a non-empty string, you can do a simple "truthy" check that will work for null, undefined, '', etc:
if (username) { ... }
With that approach, you don't even need the .length check. Also, length is a property, not a method.
Edit: You have some funkiness going on. I think you need to start with how you're passing in your username - I don't think that your String(data.match(/\S+/)) logic is behaving the way that you're expecting it to (credit to #Engineer for spotting this).
Your match expression is going to return one or two types of values: null or an Array. In the case that it's null, as #Engineer pointed out, you end up passing in "null" as a string, which should resultantly pass your username check later on. You should consider revising this to:
if (!client.loggedIn) {
var matches = data.match(/\S+/);
if (client.logMeIn(matches ? matches[0] : '',stream)) {
Regarding .length being equal to 1 in all cases - that doesn't honestly make a lot of sense. I would recommend adding a lot of console.log() statements to try and figure out what's going on.
Try
if( username === null || username.toString().length < 1 )
I used if( username === null || username.length < 1 ) and it failed at length check.

equality in javascript [duplicate]

This question already has answers here:
Which equals operator (== vs ===) should be used in JavaScript comparisons?
(48 answers)
Closed 6 years ago.
When working within javascript can someone provide me a good reference or explanation over testing for equality/inequality and type coercion?
From what I have been reading I see where there are two principles of thought on using eqeq (==) vs. eqeqeq (===) some feel that you should not use eqeq and always as use eqeqeq as it is safer to use.
I have been playing around with some basic samples and I am having trouble discerning the difference or when best to use one over the other:
For example: here is some basic script I was writing out. When I test using eqeq or eqeqeq I get the same result. I have not seen an example yet where I would get a different results (ie. using eqeq returns true where eqeqeq returns false).
function write(message){
document.getElementById('message').innerHTML += message +'<br/>';
}
var tim = { name: "tim" };
var tim2 = { name: "tim" };
//objects are equal to themselves ( == vs ==== eqeq or eqeqeq)
write("tim eq tim: " + (tim == tim)); //returns true
//objects are only equal to themselves regardless of containing value got that
write("tim eq tim2: " + (tim === tim2)); //returns false
//access the primative type to test true or false
write("tim value eq tim2 value: " + (tim.name === tim2.name)); //returns true
//how does this differ in efficency over the eqeq operator? is one safer to use over the other?
//write("tim value eq tim2 value: " + (tim.name == tim2.name)); //also returns true
//testing primatives
write("apple eqeqeq apple: " + ("apple" === "apple")); //true
write("apple eqeqeq apple: " + ("apple" == "apple")); //true
Can someone provide an explanation or reference I can read that helps clarify this a bit more.
cheers,
The difference between == and === is fairly simple: == is a comparison of value. === is a comparison of value and type. Using === will prevent JavaScript from dynamically determining type and compares values exactly as they are.
5 == "5" //true - JS compares the number 5 to a string of "5" and determines the contents are the same
5 === "5" //false - A character is not a number, they can't be the same.
0 == false //true - false is a bool, 0 is numerical, but JS determines that 0 evaluates to false
0 === false //false - numeric is not boolean, they can't be exactly the same thing
5 == 5.0 //true - need I say more?
5 === 5.0 //true - one is a float and one is an int, but JS treats them all as numerical
I find it's critical for tests with functions that can return both false (for failure) and 0 (as a legitimate result).
JS has a total of 5 primitive types = numerical, string, boolean, null and undefined. === requires both arguments to be of the same type and equal value to return true. There are no float, int, long, short, etc - any type of number is lumped together as numerical.
It is simple.
== performs a type conversion and then compares converted values to your desired value
=== doesnt perform type conversion and directly compares your values.
Obviously === is better in terms of performance and accuracy but == is also convinient in some cases so you can use them both if they suit your needs.
comparisons
Cheers!
Below is a very complete list of things that you won't expect when using equality operators
All of the following are true:
0 == ""
0 == " "
0 == []
false == ""
false == " "
false == []
[] == ""
null == undefined
"str" == ["str"]
"1" == true
"0" == false
"null" != null
"false" != false
"true" != true
"undefined" != undefined
"NaN" != NaN
NaN != NaN //exception: NO exception
{} != {} //exception: same reference
[] != [] //exception: same reference
--------------------------------------
new Number(10) !== 10
new String("str") !== "str"
NaN !== NaN //exception: NO exception
{} !== {} //exception: same reference
[] !== [] //exception: same reference
(Some of them came from this source)
In conclusion, never use ==. Not even when you want to:
"It is highly recommended to only use the strict equality operator. In
cases where types need to be coerced, it should be done explicitly and
not left to the language's complicated coercion rules."
(source)
=== is the strict equality operator which returns true only if the variables have the same type and value.
a = 1;
b = "1";
a == b will return true, a === b will return false
The rule of == is not easy to remember, can you get all the right answer of below examples?
"" == "0" // false
0 == "" // true
0 == "0" // true
false == "false" // false
false == "0" // true
false == undefined // false
false == null // false
null == undefined // true
" \t\r\n" == 0 // true
So it is better only use ===, and never use ==.
You must have heard someone that javascript is very loosely typed language.
So as surreal said above
The (==) operator is used when you only want to compare the values of the arguments and do not care about their type
like 5=="5" will return true. This is the case when you want to see (for instance what key the user pressed and you don't care about the the type of it may be a string, a char or an integer).
But there me be a case when the type of arguments also matters. In such cases you want to compare the types of the operators. So in those cases you use the triple equality operator.
For example if you are performing some addition or multiplication operations then you want to make sure that the operands are of the compatible type. So you use the triple (===) operator.

What is the difference between != and !== operators in JavaScript?

What is the difference between the !== operator and the != operator in JavaScript? Does it behave similarly to the === operator where it compares both value and type?
Yes, it's the same operator like ===, just for inequality:
!== - returns true if the two operands are not identical. This operator will not convert the operands types, and only returns false if they are the same type and value. —Wikibooks
Yes, !== is the strict version of the != operator, and no type coercion is done if the operands are of different type:
0 != '' // false, type coercion made
0 != '0' // false
false != '0' // false
0 !== '' // true, no type coercion
0 !== '0' // true
false !== '0' // true
I was about to post this W3Schools page, but funnily enough it didn't contain this operator!
At least, the !== is indeed the inverse of === which tests the equality of both type and value.

Categories

Resources