JavaScript progressive undefined checks - javascript

Let's say I have the following code:
var t = $("#objectID").html();
Checking that t is defined and has a proper value is easy.
if (typeof(t) === 'undefined' || t == null || t == '')
t = 'something else';
OR
var t = $("#objectID").html() || 'something else';
My question is though, what if you have something like the following: How would would you check it for undefined values before continuing?
$("#object").find("element").html().replace(/ |t/g, '').trim();
How do I ensure that each part of the object is legitimate before continuing down the line without having a large block of checks?
What if there's many things similar to .replace and .trim, like 10 or so? How do you check for each one?

You can use the function parameter of .html()
$("#object").find("element").html(function(html){
return ((html || 'Something').replace(/ |t/g, '') || 'Something else').trim();
});
So, what you are doing is first you're checking html has value and give it some default value if it doesn't have one. Then you group the returned string from replace and check if it has truthy value or give it a default value too and then trim it.

Here's how I would do that, checking as needed.
var element = $("#object").find("element");
var t = element.length ? element.html() : '';
t = t.replace(/ |t/g, '').trim();
First step is making a variable called element to save the jQuery object. Anytime you use the same jQuery search more than once, it's a good idea to save it to a variable: it avoids repetition and speeds up performance.
The next step is calling jQuery's length method to test if it really found any HTML elements. If either "#object" or "element" are not found, element becomes an empty jQuery object with a length of 0, and 0 is considered false in a JavaScript conditional check.
If the length of element is at least 1, then we know it's legitimate, and call safely html() on it.
If length is 0, then t is just set to an empty string. Checking length was necessary because calling html() on an empty jQuery object would have returned undefined instead of a string and caused an error.
I used the ? conditional operator for brevity but you can do the exact same check with an if statement
var element = $("#object").find("element");
if (element.length) {
var t = element.html();
} else {
var t = '';
}
t = t.replace(/ |t/g, '').trim();
I like making t default to an empty string, to ensure the variable is always a string. That way I can call replace() or trim() or any other string method with it.
An empty string also evaluates to false in JavaScript conditions, making it easy to check later on.
if (t) {
doSomethingWith(t);
}

Related

var x; ... x.trim(); Why sometimes it allows but sometimes it makes the rest of the code stop working?

This minor issue causes me 5 hours to fix. Finally I figured out. See this code:
<script language="JavaScript" type="text/javascript">
var x;
.... // a lot of codes here
var k=x.trim();
</script>
The above code made the whole app stop working!
I remembered that I used to do like that before but got no problem.
So, about var x; ... x.trim();, Why sometimes it allows but sometimes it makes the rest of the code stop working?
And what is the best code practice for it?
You can do like this:
if(typeof x === 'undefined'){
// your get an error message
}
else
{
var k=x.toString().trim();
}
Using strict equality operator === above is good idea there because in JS, you can name a variable as undefined too:
var undefined = "something";
So using === makes sure that you are really checking against undefined value for a variable.
trim is a function of String. Refer MDN - String.trim().
So when you apply it to an integer, it fails and throws error, causing you code to stop work
Example
try{
var a = 1;
console.log(a.trim());
}
catch(ex){
console.log(ex);
}
You can try to convert number to string using .toString() and then apply .trim()
try{
var a = 1;
console.log(a.toString().trim());
}
catch(ex){
console.log(ex);
}
I would expand Rajesh's answer. He's right, when you try to call a method that does not exist, a TypeError is thrown. The easiest and fool-proof approach would be to use try/catch to ensure that the rest of the code would be executed as it should. But it's likely that even if it does, you don't get the result you want.
I believe the best way to do would be to wrap the value you're having into String object. It's as easy as
var k = String(x).trim();
It does several important things:
Converts the value of x, whatever it be, into a string, i.e. when you check its type, it's always 'string' and is always an instance of the String object.
Ensures that the resulting value has the method trim which does what it should.
Doesn't throw any error, so the rest of the code is executed.
There may be several pitfalls. If x is undefined, null, NaN or an object, the result of String(x) would be, correspondingly, 'undefined', 'null', 'NaN', or '[object Object]'. If x is an array, it's a specific case, and the value would be the same as if you call x.join(','), for example
x = [1, 2, 3];
var k = String(x).trim; // k is now '1,2,3'
So always keep in mind what types you're dealing with.
Just as with String, you can cast variables to other types, but naïvely converting anything into a Number, a String or an Array is considered a very bad practice. You should always be somewhat sure what type you're working with.

What is this ternary expression doing?

I have a function I'm testing that takes two arguments Definition and Element, and has a ternary statement in it that goes like
otherThingName: (_.has(Definition.thing, 'thingName') ? Element[Definition.thing.thingName] : null)
Now Definition.thing.thingName will exist, but Element does not have a property named Definition.
Is that property being set on Element while at the same setting otherThingName?
A ternary expression is sort of a short hand if/else, so in the first instance, its testing the statement (_.has(Definition.thing, 'thingName').
I don't work with underscore, but it looks like this test is checking if Definition.thing has a property of thingName.
If this comes back true, it will set otherThingName to be Element[Definition.thing.thingName].
Otherwise it will set it to null.
Element[Definition.thing.thingName] is looking at an object called Element, and pulling back the property with the key matching the value of Definition.thing.thingName.
For example, if
Definition.thing.thingName == "name",
Element[Definition.thing.thingName] == Element["name"] == Element.name.
Hope this helps.
Expanding out the text it becomes a bit more clear:
var str;
if (_.has(Definition.thing, 'thingName')) {
str = Element[Definition.thing.thingName]
} else {
str = null;
}
...
otherThingName: str
It looks like it is defining the member of some object 'otherThingName' to be either whatever Element has set for field Definition.thing.thingName if that exists, or null otherwise.

Purpose of -1 in String.fromCharCode(k)

I have the following snippet of code :
return (AllowableCharacters.indexOf(String.fromCharCode(k)) != -1);
Now, I don't quite get the usage of -1 in this script.
The way the script reads is as follows:
first String.fromCharCode(k) != -1 is executed (k is a key code , I am dynamically getting from some other script).
Then I get the indexof(String.fromCharCode(k) != -1) from AllowableCharacters.
Which is a string something like this:
AllowableCharacters = "abc" ;
I also understand that if the indexof can't find a value in the above string it return -1.
Coming back to my question, however, why the -1 in the script?
EDIT ::
To make my question simpler , how would you read the following line :
String.fromCharCode(k))!=-1
in simple plain english .
EDIT 2::
ok so i just read guffa's answer and made a random script to check , heres the script :
var store = "abcdefgpS";
function check_index(){
console.log(store.indexOf(String.fromCharCode(83)));
};
in the above function the !-1 is excluded , so on console.log , if a match is found we get the indexOf where the character was found and well if a match is not found we get -1 .
NOW , now thats not what we want , what we want is a "tell me if the value is there"(return true) or "tell me if the value is not there"(return false).
so what we do is we change the above script to :
var store = "abcdefgpS";
function check_index(){
console.log(store.indexOf(String.fromCharCode(83)) !-1);
};
which, gives ur true or false values .
now how does :
return (store.indexOf(String.fromCharCode(83)) !-1)
read as :
if (store.indexOf(String.fromCharCode(83)) !-1){
return true;
}else { return false; }
I don't see the if statement in .
return (store.indexOf(String.fromCharCode(83)) !-1);
Thank you,
Alexander
This is a condition that validates whether or not a character is allowed. It will return a boolean (the result of the comparison).
Let's break it down.
First, we get a string from a char code with String.fromCharCode. Presumably we've received this from an input event of some kind.
Next, we get the index of this resulting single-character string in AllowableCharacters using indexOf.
Finally, we test if that result is -1. A test evaluates to a boolean value, and it can be returned from a function just like any other value. A value of -1 indicates that the character is not allowed, so we use != to determine if the character is valid.
You got the order of execution wrong.
First this expression is evaluated: String.fromCharCode(k).
Lets assume that the result is the string "b". That is used in the expression: AllowableCharacters.indexOf("b").
Lets assume that the characer is found at the second character in the string, which has index 1, so the result is 1. That is used in the expression 1 != -1.
As the 1 is not equal to -1, the result is true, which is returned.
In short, the -1 is compared with the result from the indexOf method, as the methods returns -1 when it doesn't find anything.
It's the comparison operator != that causes the value to be true or false. It compares the values, and the result depends on whether they are equal or not. An if statement isn't needed to turn the result into true or false, that's already the value of the comparison expression.
Sometimes you see code like:
if (AllowableCharacters.indexOf(String.fromCharCode(k)) != -1) {
return true;
} else {
return false;
}
The if statement is superflous in cases like that. The expression in the if statement is already true or false, so it can be returned directly:
return AllowableCharacters.indexOf(String.fromCharCode(k)) != -1;

How to make shorter and readable comparison/logical lines to assign default values? in jQuery/JavaScript?

Consider the code at the bottom, inside a regular function, that checks if some argument was provided or not, and assigns a default value to a variable named message. If the argument is truthy or an empty string, It is simply converted to a string and is stored in the message variable, otherwise the type of argument will be stored in message.
I know it's possible to shorten if else statements to assign default values to variables, like:
var message = arguments[0] || jQuery.type(arguments[0]);
which if only the arguments[0] is truthy will be stored in message. But how to make an exception for an empty string which is a falsy value, without having to use a long if else statement?
if(arguments[0] || arguments[0] === '')
var message = arguments[0].toString();
else
var message = jQuery.type(arguments[0]);
var message = ((arguments[0] || arguments[0] === '') ? arguments[0].toString() : jQuery.type(arguments[0]));
It sounds like you're looking for a shorthand if/else. If so, you can find the answer to your question here. Basically what you need is a ternary operator.
Excerpt below:
var x = y !== undefined ? y : 1;

Not Equal To notation in Javascript to use in jQuery

Is this the notation to use for Not Equal To in JS, in jquery code
!== OR !=
None of them work
Here is the code I am using
var val = $('#xxx').val();
if (val!='') {
alert("jello");
}
Thanks
Jean
Equality testing in JQuery works no different from "standard" JavaScript.
!= means "not equal to", but !== makes sure that both values have the same type as well. As an example, 1 == '1' is true but not 1 === '1', because the LHS value is a number and the RHS value is a string.
Given your example, we cannot really tell you a lot about what is going on. We need a real example.
.val() is used to retrieve or set values from input in forms mostly, is that what you want to do? If not maybe you mean using .text() or .html().
If that is indeed what you want to do maybe you have your selector wrong and its returning null to you, and null does not equal '', or maybe you actually have data there, like whitespaces. :)
May be you have whitespace in your #xxx node, that why both !== and != failing, you could try following to test non whitespace characters
var val = $('#xxx').val();
if (/\S/.test(val)){
alert('jello');
}
Note: I assume jQuery's .val() won't return null because of this line in jQuery source
return (elem.value || "").replace(/\r/g, "");
If not, you need to do like this
if (val && /\S/.test(val)){
alert('jello');
}
It's both, but the latter is strict on type, see here:
https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Comparison_Operators
It is working with jquery and normal java script.
You should check (alert/debug) your val variable for its value and null.
You should also check $('#xxx').length whether you are getting elements or not otherwise you will get, hence your if condition will be false.

Categories