I want to run a code only if the argument[0].recordCount is greater than zero or is NOT undefined. However, the code is ran when the argument[0].recordCound alert shows undefined.
if(arguments[0].recordCount > 0 &&
arguments[0].recordCount !== 'undefined')
{ //if more than 0 records show in bar
document.getElementById('totalRecords').innerHTML =
arguments[0].recordCount + " Records";
}
How can I test for undefined here?
When using undefined as a string you need to do so with the typeof operator.
Also, you should be checking if it's defined before any other checks on the property.
if ( 'undefined' != typeof arguments[0].recordCount && arguments[0].recordCount > 0 )
undefined is a keyword a global variable with constant value, use it without quotes:
if(arguments[0].recordCount > 0 && arguments[0].recordCount !== undefined)
But actually it would be sufficient to test only the first condition:
if(arguments[0].recordCount > 0)
because if recordCount is larger than zero, it is defined anyway.
More common is to switch the conditions and test first whether it is defined, to avoid possible errors in the following tests (not sure if this is necessary here):
if(arguments[0].recordCount !== undefined && arguments[0].recordCount > 0)
To check for a variable to be not null and not undefined,
if(thatVariable) is enough though implicit conversion can cause problem for some cases where thatVariable is empty string, or a boolean, or number 0. If implicit conversion is not the case for our variable, the following would do,
if(arguments[0].recordCount && arguments[0].recordCount > 0)
But the following would be problematic,
if(arguments[0].recordCount !== undefined && arguments[0].recordCount > 0)
Consider,
var undefined = 'surprise' //possible since undefined is not a keyword
if(arguments[0].recordCount !== undefined && arguments[0].recordCount > 0)
Now this 'if' will break even though recordCount is undefined.
One more thing: if(a != null) will also check undefined due to implicit conversion. Hence if(a != null && a != undefined) is redundant
Related
Is there an elegant way to check if variable is NOT falsy but in case of 0 it passes. The issue with this way of verifying
if(var !== undefined && var !== null)
is that it's long and doesn't cover all cases like undecalred or NaN. I'm also using typescript and declare it as optional number.
You can do exactly what your first sentence asks:
if (!x && x !== 0)
means literally "if x is falsy and x is not 0".
Also the == and != comparison operators explicitly consider null and undefined to be equal, so
if (x != null)
is true for both null and undefined. (That's !=, not !==.)
function Check(input) {
if (!input && input!==0){
return "falsy";
}
else if (input === 0){
return "zero";
}
}
console.log(Check(0));
console.log(Check(false))
Totally newbie to JS so apologise for the probably obvious solution to this issue!
I'm trying to write a bit of code for use in google sheets that basically removes elements of a 2D array if the 3rd value in each nested array is empty eg.
[[1,2,3],[4,5,,],[7,8,9],[,,,]
would become
[[1,2,3],[7,8,9]]
I've currently got:
if (bkLoc=='HALL'){
var sumRng = sh.getRange('MIC_SUMM').getValues();
for (var i =0; i<sumRng.length ; i++){
if(sumRng[i][2] !== (undefined || '' || null)){
micSumm.push(sumRng[i]);
}
}
}
But the output seems to contains loads of empty arrays almost like its pushing every loop and I'm not sure why.
Any help would be gratefully received!
EDIT1: So with the help of you guys I got it to work. Using Nikhils answer I am now using this for the IF
if (bkLoc=='HALL'){
var sumRng = sh.getRange('MIC_SUMM').getValues();
for (j =0; j<sumRng.length ; j++){
var x = sumRng[j][2];
if(x != 0 && x != '??' && x != undefined){
micSumm.push(sumRng[j]);
}
}
}
But to be honest I don't really understand it. My understanding was || is OR so in my original code
if(sumRng[i][2] !== (undefined || '' || null))
If the tested content DOESN'T CONTAIN undefined OR "" OR null , the if statement should be true. I thought && meant AND so I'm unclear as to why that ever passes
Apologies for being so dumb!
Cheers
In your current if condition, undefined || '' || null evaluates to null. Hence, the condition eventually becomes sumRng[i][2] !== null.
However, as you need to check for undefined and '' too, you will need to update your condition
From
if(sumRng[i][2] !== (undefined || '' || null)){
to
if(sumRng[i][2] !== undefined && sumRng[i][2] !== '' && sumRng[i][2] !== null){
Assuming you've defined micSumm somewhere and started out with a blank array in it (var micSumm = [];), then you're on the right track, the issue is here:
if(sumRng[i][2] !== (undefined || '' || null)){
That's not how you do a check against multiple values in JavaScript. The way that's evaluated is:
sumRng[i][2] is evaluated; let's call the resulting value left
undefined || '' is evaluated, the result is ''; let's call it temp¹
temp || null ('' || null) is evaluated, the result is null; let's call that right
The result of left !== right is evaluated
So you end up only checking for null, not undefined or ''.
Instead:
var value = sumRng[i][2];
if (value !== undefined && value !== '' && value !== null) {
Or you can take advantage of the fact != undefined also checks for null:
var value = sumRng[i][2];
if (value != undefined && value !== '') {
...but that can be a bit less clear.
¹ Why does undefined || '' result in ''? Because an expression a || b is evaluated like this:
Evaluate a
If the value from Step 1 is truthy, make that the result of the || operation
Otherwise, evaluate b and make that the result of the || operation
undefined is falsy, not truthy. (A falsy value is any value that coerces to false when used as a boolean. The falsy values are undefined, null, "", 0, NaN, and of course, false. All other values are truthy.)
You could also use filter(which is supported by apps-script):
var filteredArr = sumRng.filter(function(e) {return e[2];})
Note that you're getting a 2D array with a specific rectangular dimension. So, there's no possibility of a value being undefined. Unless you specifically made a value null,null isn't returned. As noted in the comments below, the above also filters out 0 and boolean false. So, You can use
sumRng.filter(function(e) {return e[2].toString();})
or
sumRng.filter(function(e) {return e[2] || e[2] === false || e[2] === 0;})
References:
Array#filter
Primitives
null
Comparison Operators
Truthy
I still struggle with the why the original OR method I had doesn't work. In fact I went over to reddit to try and see if I could get anymore clarification but still it won't go in. But I appreciate all your help trying.
I did get an alternative solution to my conundrum though which seems a more condensed version of what I was using. That was simply this (courtesy of user insertAlias)
if(sumRng[i][2]){}
Apparently that will only pass for anything truthy so seems to fit the bill. But please point out any shortcomings
How can i create an Or statement from what I have now... I want to do a check to see if urlParams["rs"] is undefined / null
If cookie 123_rs is not present and URL query urlParams["rs"] is not null/undefined then ...write cookie only if its not present and query string exist
if(document.cookie.indexOf("123_rs=") < 0) {
if(document.cookie.indexOf("123_rs=") < 0 || !urlParams["rs"])
Simply use the or operator?
Use the logical AND && operator to combine multiple conditions that must all evaluate to true.
if(
document.cookie.indexOf("123_rs=") < 0 &&
(typeof urlParams["rs"] != 'undefined') &&
urlParams["rs"] != ''
) {
// 123_rs is not found in the cookie string
// urlParams["rs"] is set and is not an empty string
}
Sidenote: the cookie check is very simple and is susceptible to false positives. For example if you had a cookie called abcde123_rs then your indexOf() would still consider it found 123_rs=. For a more robust solution you can use the MDN simple cookie library:
if(
docCookies.getItem('123_rs') == null &&
(typeof urlParams["rs"] != 'undefined') &&
urlParams["rs"] != ''
) {
// 123_rs is not found
// urlParams["rs"] is set and is not an empty string
}
Is there any difference between the below statements:
if(newValue && newValue != '') and
if(newValue != '')
I have observed expression 1 in many scripts but always got confused.
Please assist!
if(newValue && newValue != '').
This guards against a value of null or undefined.
Out of the possible '', 0, false, undefined and null, only the last two are not equal to '' (using !=), requiring the extra condition.
console.log(null && null != '') // null -> falsy
console.log(null != '') // truthy
var undef = void 0;
console.log(undef && undef != '') // undefined -> falsy
console.log(undef != '') // truthy
Answer is no,
1) for (newValue && newValue != ''),it checks whether newValue exist(non false values) and its not empty
2) for if(newValue != ''),it only checks whether newValue is not empty
Just one more thin I thought worth adding to the answers already posted.
As you, the OP, say: you've seen the first expression in existing code many times, so you've probably seen things like this:
if (foo && foo.bar)
{
foo.bar();
}
In this case, this is to avoid errors in certain browsers. In most modern browsers accessing somehting like localStorage.doesNotExist won't raise errors, but not all browsers support this so we: first check if the localStorage object exists, and if so, if the property can be resolved to a non-falsy value.
The same logic applies to methods of objects, that may be different in various browsers:
var domElement = document.getElementById('foobar');//might not exist, though
if (domElement && domElement.addEventListener)
{//does element exist && does it have a method called addEventListener
domElement.addEventListener('click', functionRef, false);
}
else if (domElement && domElement.attachEvent)
{
domElement.attachEvent('onclick', functionRef);
}
if you were to omit the first domElement in the if statement, and simply write domElement.addEventListener, that could be the same as writing null.addEventListener which throws a TypeError (because you're trying to access a property on a primitive value)
I am using Y.one(selector).getAttribute('value'); to return the value on a page and I am having trouble dealing with cases where value="".
var check_value = Y.one(selector).getAttribute('value');
if (check_value != undefined || check_value != null || check_value != "") {
alert(check_value);
}
With all of these checks I am getting an empty alert box when the value of the element I am looking at is "". In this case since I know the value I am looking for is a number I can change the check to just look for a number > 0 and have it work but I was wondering if anyone knew of a method to check for no value for cases where I was not dealing with numeric data.
if (check_value >0) {
alert(check_value);
}
This method does work in my case.
Why don't you just check for 'truthiness' instead?
if (check_value) {
alert(check_value);
}
It's basically the same as your (intended) check, I suppose. And if you need to check for 0 (a Number), just use this:
if (check_value || check_value === 0) {
...
}
If it is an empty string, then it isn't undefined and it isn't null. Since you check if it is not undefined or not null or not an empty string, then it will pass.
Use && not ||
You might look at Y.Lang.isValue()
http://yuilibrary.com/yui/docs/api/classes/Lang.html#method_isValue
Look at the logic in plain english check_value != undefined || check_value != null || check_value != "" if it's undefined or null or "", if it's null it's not undefined, if it's blank it's not null, so everything gets through; you're looking for a logical AND instead of OR
try this:
var check_value = Y.one(selector).getAttribute('value');
if (check_value != undefined && check_value != null && check_value != "") {
alert(check_value);
}
You're seeing the alert because your if statement has OR (||) clauses. In the case that the value attribute is an empty string, the last condition (check_value != "") should fail. However, since "" is not equal to undefined the first condition has already returned true, the if statements test passes (it won't evaluate the other conditions because it doesn't need to) and the if block is executed.
I suspect you actually wanted to use AND (&&) instead.