Coffeescript and variable check - javascript

I have the following code:
if variablename?
alert "YES!"
l = []
if l[3]?
alert "YES!"
It's translated into this:
var l;
if (typeof variablename !== "undefined" && variablename !== null) {
alert("YESSS!");
}
l = [];
if (l[3] != null) {
alert("YESSS!");
}
In Coffeescript, how would I express l[3] !== "undefined" ?

Just add typeof operator, like this:
if typeof l[3] != 'undefined'
alert 'Yes!'

Beware that l[3] !== "undefined" is asking whether l[3] is different from the string that says "undefined", not if its value isn't undefined. The comparison that CoffeeScript generates for l[3]? -> l[3] != null will verify when l[3] is some value different from undefined or null, which is what you want to ask most of the time :)

Related

Check for empty of null in javascript

I had a bug that turned out to be because I forgot to check for null values. I added the check, but would like if it could be written more concise.
<ListItem onClick={!pattern.capped && !pattern.hasInlineRef ? search(pattern.dbValue, pattern.dbValue === "" || pattern.dbValue === null) : undefined}>
Can this check for empty or null be shortened?
search(pattern.dbValue, pattern.dbValue === "" || pattern.dbValue === null)
It's written in Typescript, but I guess the curly braces make it JavaScript.
First, you can create an util function to check null, empty or undefined:
export function isNullOrEmpty(value) {
return (value === null || value === undefined || value === "") ? true : false
}
Or, you can fast test with falsy and truthy:
search(pattern.dbValue, !pattern.dbValue)
List of falsy values in JavaScript: MDN Falsy
false
null
undefined
0
NaN
''
document.all
You can create an helper function in a separate folder and pull out this function into the files where you need to check for null, undefined, empty string or an empty object.You can write something like this:
export default value =>
value === undefined ||
value === null ||
(typeof value === 'object' && Object.keys(value).length === 0) ||
(typeof value === 'string' && value.trim().length === 0);
Hope this helps

If (myVar != "undefined")

I wanted to check whether an item in localWebstorage was not yet given a value. I tried doing this by:
//Change localStorage.intervalSetting from 'Undefined' to 'Never'
function initialIntervalSetting() {
var getValue = localStorage.intervalSetting;
if (typeof getValue === undefined) {
localStorage.intervalSetting = "option1";
alert("Changed the localWebstorage item from undefined to "option1");
}
else {
alert("JavaScript thinks that the item is not undefined");
}
}
This does not work, HOWEVER.. The question was asked here:
How to check for "undefined" in JavaScript? and someone answered:
if (typeof getValue != "undefined") {
localStorage.intervalSetting = "option1";
}
They suggested replacing === with !=
For some reason, this works- How???
Shouldn't (getValue != "undefined") return false because != means NOT EQUAL??
In your code you compared typeof getValue with the literal type undefined. Since typeof actually gives you a string, you should compare this value to the string "undefined".
Either
if (typeof getValue !== "undefined")
Or
if (getValue !== undefined)
will do the trick.
I recommend using a "truthy" check. This will check if the object is null or undefined. You can do this by just checking your getValue.
if(getValue) {
// not undefined
}
Another SO post for reference: Understanding JavaScript Truthy and Falsy

Checking if multiple variables is not null, undefined or empty in an efficient way

At the moment I have an if condition like this:
if(
(variable != null && variable != '' && !variable) &&
(variable2 != null && variable2 != '' && !variable2) &&
(variable3 != null && variable3 != '' && !variable3)
//etc..
)
I need to use it to check if multiple variables have value (were not left out), but I feel like this is a messy solution and wanted to ask if there is a more efficient way? Maybe additional checks as well?
Because if(variable) ignores any falsy value, this will work for you
if(variable && variable2 && variable3)
The following values are always falsy in JS:
false.
0 (zero)
"" (empty string)
null.
undefined.
NaN (a special Number value meaning Not-a-Number!)
Update:-
If there is a case when you want to execute if block even if the value is 0, you have to add an extra check saying either 0 or some other value.
if((variable || variable === 0) && (variable2 || variable2 === 0) && (variable3 || variable3 === 0))
If IE support matter to you (IE9+), you could use the following solution.
You could use Array.prototype.some(). In a nutshell this array method will return true if any of the elements in the array meet a certain condition. This condition will be el == null this will work because undefined == null and null == null both resolve in true
See this stackoverflow post for more information
Which equals operator (== vs ===) should be used in JavaScript comparisons?
Array.prototype.some() browser support (93% time of writing) here
var a = 5;
var b = null;
var c = undefined;
if ( [a,b,c].some(el => el == null) ) {
console.log("You f*d up")
}
Or you could use Array.prototype.includes()
See support (93% time of writing) here here
var a = 5;
var b = null;
var c = undefined;
if ( [a,b,c].includes(undefined) || [a,b,c].includes(null) ) {
console.log("You f*d up")
}
If you want good browser support and you don't mind an external library, use lodash.
var a = 5;
var b = null;
var c = undefined;
if ( _.some([a,b,c], el => _.isNil(el)) ) {
console.log("You f*d up")
}
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>
If your variables are containing some values that are truthy, like a string, and that is considered positive in your condition, then you could simply check using Array.prototype.every()...
if (![var1, var2, var3].every(Boolean)) {
throw new exc;
}
Which will check to ensure every variable has a truthy value.
I assume you are checking for truthy values? If so, you can just do:
variable && variable2 && variable3
See JavaScript: What is the difference between if (!x) and if (x == null)?
!variable will be true for all falsy values so you only have to
if(variable1 && variable2 && variable3 && ...)
Long hand -
if (var1 !== null || var1 !== undefined || var1 !== '') {
let var2 = var1;
}
Short hand -
const var2 = var1 || '';
let variable null;
let variable2 undefined;
let variable3 'string';
let variable4 '';
let variable5 true;
let variable6 false;
let variable7 0;
let variable8 1;
Validating multiple values using the filter function. One could expect this example to return true as the count would be 5 for (variable, variable2, variable4, variable6, variable7)
if([variable, variable2, variable3, variable4, variable5, variable6, variable7, variable8]
.filter(q=>!q).length > 0) {
//take action
}

JavaScript : Check if variable exists and if equal to value

I have three pages utilizing the same code and on one of the pages this variable doesn't exist, on the other two the variable ticketType has a value of 1 or 2. I need to first check if ticketType exists and isn't undefined and secondly, need to determine if it's one or 2.
This if statement generates an error:
if(typeof ticketType != undefined && ticketType == 1){}
It's saying ticketType isn't defined. I tried nesting the if statements to check if it was defined first thinking it wouldn't go and try the inner if statement but firebug still generates an error.
Any ideas? There has to be a way to do this...
'undefined' needs to have quotes around it when used with typeof
if(typeof ticketType != 'undefined' && ticketType == 1){}
undefined should be within quotes...
if (typeof ticketType !== "undefined" && ticketType == 1)
{
}
EDIT
Here we are not talking about global.undefined which doesn't have to be enclosed within quotes. We are talking about the return type of typeof operator which is a string. Incidentally for undefined variable, the typeof returns "undefined" and thus we need to enclose it within string.
// ticketType is not defined yet
(typeof ticketType !== undefined) // This is true
(typeof ticketType === undefined) // This is false
(typeof ticketType !== "undefined") // This is false
(typeof ticketType === "undefined") // This is true
var ticketType = "someValue"; // ticketType is defined
(typeof ticketType !== undefined) // This is still true
(typeof ticketType === undefined) // This is still false
(typeof ticketType !== "undefined") // This is true
(typeof ticketType === "undefined") // This is false
So the correct check is against "undefined" not against global.undefined.
Wrap it in parenthesis.
if (typeof(ticketType) !== 'undefined' && ticketType === 1)
The error message is pretty clear. Try with this:
var ticketType;
if(typeof ticketType != undefined && ticketType == 1){}
You cannot just reference a variable that does not exist. You can only do this when assigning:
ticketType = 1;
The browser complaints because ticketType is an unknown identifier. However if we first declare it (even without assigning it any value) it becomes known but with undefined value.
if(typeof ticketType != 'undefined' && ticketType == 1){}
I think you need the quotes around the undefined word. At least I always do it that way.
you're incorrectly checking for an undefined variable, but if you're planning on using it, why not just make sure that it gets defined?
ticketType = ticketType || 1;
if (ticketType === 1) {
//do stuff
}
As everyone else has shown, the standard way of checking for undefined values in JS is:
typeof somevar === 'undefined'
The correct syntax is:
if (typeof ticketType !== 'undefined' && ticketType === 1) { }
The result of the typeof operator is always a string. See here: http://www.javascriptkit.com/javatutors/determinevar2.shtml
simlpe using console.log(someVar);

Checking undefined value not working?

I have the following javascript code:
var currentIds = localStorage.getItem('currentPairsIds');
if ((typeof currentIds === "undefined") ||
(currentIds == null))
$.myNameSpace.currentIDs = new Array(3);
else
$.myNameSpace.currentIDs = currentIds.Split(',');
I'm debugging with Firebug and although currentIds hasn't got any value it always executes else statement.
UPDATE: I'm getting this value from HTML5 storage.
What am I doing wrong?
This is how I have solved my problem:
var currentIds = localStorage.getItem('currentPairsIds');
if ((currentIds === undefined) ||
(currentIds == null) || (currentIds == "undefined"))
$.myNameSpace.currentIDs = new Array(3);
else
$.myNameSpace.currentIDs = currentIds.split(',');
localStorage.getItem('currentPairsIds'); returns the string "undefined".
There is another error in Split() function. The right version is without any capital letter.
I would use a direct comparison instead of the notoriously odd "typeof" operator:
if ((currentIds === undefined) || (currentIds === null)) {
//...
It's not working because localStorage.getItem returns null if the item is not defined, it does not return undefined http://dev.w3.org/html5/webstorage/#dom-storage-getitem
Example: http://jsfiddle.net/mendesjuan/Rsu8N/1/
var notStored = localStorage.getItem('ffff');
alert(notStored); // null
alert(typeof notStored); // object, yes, null is an object.
Therefore you should just be testing
alert(notStored === null);
I think you have to make checking for undefined comparing with == instead of ===.
Example:
typeof currentIds == "undefined"
This will make sure, the variable is really undefined or not.
[Edit Edit Edit Edit :P]
currentIds = "undefined"
implies
typeof currentIds == "String"
Also see, Detecting Undefined, === isn't necessary for string comparison.
In my case LocalStorage.getItem() was converting it to "undefined" as string.
I also needed to check if it s "undefined" as a string.
var myItem = LocalStorage.getItem('myItem');
if(myItem != "undefined" && myItem != undefined && myItem != null){
...
}
if( typeof(varName) != "undefined" && varName !== null )
be sure, you use ( " " ) quotes when checking with typeof()

Categories

Resources