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
}
Related
What is the difference between next if statements in javascript when checking with null?
var a = "";
if( a != null ) // one equality sign
....
if( a !== null ) // two equality sign
....
When comparing to null I can't find any difference.
According to http://www.w3schools.com/js/js_comparisons.asp
!= - not equal
!== - not equal value or not equal type
In JavaScript, null has type: object (try yourself executing the following sentence typeof null).
That is, !== will check that a is also object before checking if the reference equals.
Actually you know that === and !== are meant to check that both left and right side of the equality have the same type without implicit conversions involved. For example:
"0" == 0 // true
"0" === 0 // false
Same reasoning works on null checking.
!= checks
negative equality
while !== checks for
negative identity
For example,
var a = "";
a != false; //returns false since "" is equal false
a !== false; //returns true since "" is not same as false
but if you are comparing it with null, then value will be true in both ocassion since "" is neither equal nor identical to null
There is no difference between them when comparing to null.
When we use strict equality (!==) it is obvious because they have different types, but when we use loose equality (!=) it is an important thing to remember about JavaScript language design.
Because of language design there are also some common questions:
How do you check for an empty string in JavaScript?
Is there a standard function to check for null, undefined, or blank variables in JavaScript?
var a = "";
(1) if( a != null ) // one equality sign
Above condition(1) checks value only and not data-type, this will return true.
....
(2) if( a !== null ) // two equality sign
This checks value and data-type both, this will true as well.
To understand it more precisely,
var a = "1";
if( a == 1) {
alert("works and doesn't check data type string");
}
if( a === 1) {
alert('doesn't works because "1" is string');
}
if( a === "1") {
alert('works because "1" is string');
}
There is a difference if variable has value undefined:
var a = undefined;
if( a != null ) // doesn't pass
console.log("ok");
if( a !== null ) // passes
console.log("ok");
Got idea from reading this great post Why ==null, Not ===null. Also != is faster.
I have this code:
if (window.content.document.getElementById("error-msg") != null )
{
if (window.content.document.getElementById("error-msg").offsetParent !== null)
{
...
}
}
Can it be written in one if statement?
I tried the following...
if ( (window.content.document.getElementById("error-msg") != null) || (window.content.document.getElementById("error-msg").offsetParent !== null) ) {}
But, it didn't work, and produces an error:
TypeError: window.content.document.getElementById(...) is null
The common idiom is to use the && operator like this
var errorMsg = window.content.document.getElementById("error-msg");
if (errorMsg && errorMsg.offsetParent) {
...
}
Here, JavaScript will evaluate errorMsg first and if it is Truthy, then it will evaluate the errorMsg.offsetParent part. The condition will be satisfied only if both the expressions in && are Truthy.
Note: The Truthy evaluation will return false, if the expression being tested is 0, false etc (See the list of Falsy values here). So, if you want to test if they are not null, just write that explicitly, like this
if (errorMsg !== null && errorMsg.offsetParent !== null) {
...
}
On the other hand, the || operator will evaluate the second operator only if the first expression is Falsy. In your case, if
(window.content.document.getElementById("error-msg") != null)
is true, it means that getElementById("error-msg") returns null. Since the first expression is evaluated to be Truthy, it evaluates the other expression and it effectively tries to check
null.offsetParent !== null
That is why it fails.
Maybe you want to use &&
if (a != null && b != null) {
// Do something.
}
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)
If Not (oResponse.selectSingleNode("BigGroupType") Is Nothing) Then
End If
I need to convert this to javascript. Is that enough to check null?
This was my lead's answer, plz verify this,
if(typeof $(data).find("BigGroupType").text() != "undefined" && $(data).find("BigGroupType").text() != null) {
}
JavaScript has two values which mean "nothing", undefined and null. undefined has a much stronger "nothing" meaning than null because it is the default value of every variable. No variable can be null unless it is set to null, but variables are undefined by default.
var x;
console.log(x === undefined); // => true
var X = { foo: 'bar' };
console.log(X.baz); // => undefined
If you want to check to see if something is undefined, you should use === because == isn't good enough to distinguish it from null.
var x = null;
console.log(x == undefined); // => true
console.log(x === undefined); // => false
However, this can be useful because sometimes you want to know if something is undefined or null, so you can just do if (value == null) to test if it is either.
Finally, if you want to test whether a variable even exists in scope, you can use typeof. This can be helpful when testing for built-ins which may not exist in older browsers, such as JSON.
if (typeof JSON == 'undefined') {
// Either no variable named JSON exists, or it exists and
// its value is undefined.
}
You need to check for both null and undefined, this implicitly does so
if( oResponse.selectSingleNode("BigGroupType") != null ) {
}
It is the equivalent of:
var node = oResponse.selectSingleNode("BigGroupType");
if( node !== null &&
node !== void 0 ) {
}
void 0 being a bulletproof expression to get undefined
In JavaScript equvalent for Nothing is undefined
if(oResponse.selectSingleNode("BigGroupType") != undefined){
}
This logic:
If Not (oResponse.selectSingleNode("BigGroupType") Is Nothing)
Can be written like this in JavaScript:
if (typeof oResponse.selectSingleNode("BigGroupType") != 'undefined')
Nothing would equal undefined, but checking against undefined is not recommended for several reasons, it’s generally safer to use typeof.
However, if the selectSingleNode can return other falsy values such as null, it’s probably OK to just do a simple check if it is truthy:
if (oResponse.selectSingleNode("BigGroupType"))
JavaScript:-
(document.getElementById(“BigGroupType”) == undefined) // Returns true
JQuery:-
($(“#BigGroupType”).val() === “undefined”) // Returns true
Note in above examples undefined is a keyword in JavaScript, where as in JQuery it is just a string.
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