checking for invalid javascript function parameters - javascript

If i need to check a parameter i do this.
if ((typeof param == 'undefined') || (param == null)){
param = ''; //or param = false;
}
And if it's meant to be a number i might throw in a isNaN check too. I was just wondering if there were any other things i should check for or what you do if you need to check your parameters. I know javascript has a lot of quirks that could affect something like this. What is good practice to check for?
Thanks

Any object evaluates to false in a boolean expression if it is false, undefined, null, NaN, 0, "0", "false", or "" (the empty string).
To check for all of these at once concisely, you can just do it like this:
if(!param)

I would simply pull a cliché and say that "it depends on what you want to do"..
If you just want to make sure the value is defined and sent to the function, the code you used should be fine.
You can of course also check for elements within the arguments array, like
if (typeof arguments[0] != "string") {
alert("Has to be string");
}
// or even
if (arguments.length < 1) {
// there aren't any parameters
}
etc...
the arguments array is very helpful in many ways. You can also use it to overload functions - to provide different functionality or arguments depending on the number of arguments provided, etc..
But other than that, I don't know what you need.

Related

In ES2015 is there a way to directly access object properties without checking for undefined?

In ES5 whenever I want to get some property I need to first check that it exists like this:
if (typeof floob.flib !== 'undefined') {
// do something
}
even worse is that for nested properties you have to manually check for the existence of every property down the dotted path.
Is there a better way to do this in ES2015?
If it is just a single depth property name - you don't need typeof, you may just compare the value with undefined.
Your solution is prone to false negatives: it may think there is no a property with a given name, while there is one. Example: var o = { foo: undefined };
If you need to check if the path exists in the nested objects - you still need to implement recursion/loop/or use any library that does either for you.
ES2015 did not bring anything new to solve this problem easier.
If you have lodash available, you can use _.get(obj, path, defaultValue) (https://lodash.com/docs#get)
By using typeof,
typeof floob.flib === 'undefined'
equals to,
floob.flib === undefined
I assume you want to check whether floob.flib has a value, and if it does, you want to perform an operation with it.
However, in JS, there's almost simpler way to achieve this.
E.g.
if (floob.flib) {
// 'floob.flib' is NOT 'null', 'empty string', '0', false or 'undefined'
}
This also works well if you want to assign variable with ternary ( ?: ) operators.
var str = floob.flib ? 'exists' : 'does not exist';
Or even using logical OR ( || )
var str = floob.flib || '<= either null, empty, false, 0 or undefined';
Note that unless floob.flib does not produce ReferenceError exception, the code above should work just fine.

How to check if javascript variable exist, empty, array, (array but empty), undefined, object and so on

How to check if javascript variable exist, empty, array, (array but empty), undefined, object and so on
As mentioned in the title, I need a general overview how to check javascript variables in several cases without returning any error causing the browser to stop processing the pageload.
(now I have several issues in this topic.
For example IE stops with error in case _os is undefined, other browsers doesnt:
var _os = fbuser.orders;
var o =0;
var _ret = false;
for (var i = 0; i < _os.length; i++){
...
Furthermore i also need a guide of the proper using operators like == , ===.
As mentioned in the title, I need a general overview how to check
javascript variables in several cases without returning any error
causing the browser to stop processing the pageload.
To check whether or not variables is there, you can simply use typeof:
if (typeof _os != 'undefined'){
// your code
}
The typeof will also help you avoid var undefined error when checking that way.
Furthermore i also need a guide of the proper using operators like ==
, ===.
Both are equality operators. First one does loose comparison to check for values while latter not only checks value but also type of operands being compared.
Here is an example:
4 == "4" // true
4 === "4" // false because types are different eg number and string
With == javascript does type cohersion automatically. When you are sure about type and value of both operands, always use strict equality operator eg ===.
Generally, using typeof is problematic, you should ONLY use it to check whether or not a variables is present.
Read More at MDN:
https://developer.mozilla.org/en/JavaScript/Reference/Operators/typeof
The typeof operator is very helpful here:
typeof asdf
// "undefined"
Perhaps you want something like this in your case:
// Handle cases where `fbuser.orders` is not an array:
var _os = fbuser.orders || []

jquery check if json var exist

How can I with jquery check to see if a key/value exist in the resulting json after a getJSON?
function myPush(){
$.getJSON("client.php?action=listen",function(d){
d.chat_msg = d.chat_msg.replace(/\\\"/g, "\"");
$('#display').prepend(d.chat_msg+'<br />');
if(d.failed != 'true'){ myPush(); }
});
}
Basically I need a way to see if d.failed exist and if it = 'true' then do not continue looping pushes.
You don't need jQuery for this, just JavaScript. You can do it a few ways:
typeof d.failed- returns the type ('undefined', 'Number', etc)
d.hasOwnProperty('failed')- just in case it's inherited
'failed' in d- check if it was ever set (even to undefined)
You can also do a check on d.failed: if (d.failed), but this will return false if d.failed is undefined, null, false, or zero. To keep it simple, why not do if (d.failed === 'true')? Why check if it exists? If it's true, just return or set some kind of boolean.
Reference:
http://www.nczonline.net/blog/2010/07/27/determining-if-an-object-property-exists/
Found this yesterday. CSS like selectors for JSON
http://jsonselect.org/
You can use a javascript idiom for if-statements like this:
if (d.failed) {
// code in here will execute if not undefined or null
}
Simple as that. In your case it should be:
if (d.failed && d.failed != 'true') {
myPush();
}
Ironically this reads out as "if d.failed exists and is set to 'true'" as the OP wrote in the question.

When to check for undefined and when to check for null

[Bounty Edit]
I'm looking for a good explanation when you should set/use null or undefined and where you need to check for it. Basically what are common practices for these two and is really possible to treat them separately in generic maintainable codee?
When can I safely check for === null, safely check for === undefined and when do I need to check for both with == null
When should you use the keyword undefined and when should one use the keyword null
I have various checks in the format of
if (someObj == null) or if (someObj != null) which check for both null and undefined. I would like to change all these to either === undefined or === null but I'm not sure how to guarantee that it will only ever be one of the two but not both.
Where should you use checks for null and where should you use checks for undefined
A concrete example:
var List = []; // ordered list contains data at odd indexes.
var getObject = function(id) {
for (var i = 0; i < List.length; i++) {
if (List[i] == null) continue;
if (id === List[i].getId()) {
return List[i];
}
}
return null;
}
var deleteObject = function(id) {
var index = getIndex(id) // pretty obvouis function
// List[index] = null; // should I set it to null?
delete List[index]; // should I set it to undefined?
}
This is just one example of where I can use both null or undefined and I don't know which is correct.
Are there any cases where you must check for both null and undefined because you have no choice?
Functions implicitly return undefined. Undefined keys in arrays are undefined. Undefined attributes in objects are undefined.
function foo () {
};
var bar = [];
var baz = {};
//foo() === undefined && bar[100] === undefined && baz.something === undefined
document.getElementById returns null if no elements are found.
var el = document.getElementById("foo");
// el === null || el instanceof HTMLElement
You should never have to check for undefined or null (unless you're aggregating data from both a source that may return null, and a source which may return undefined).
I recommend you avoid null; use undefined.
Some DOM methods return null. All properties of an object that have not been set return undefined when you attempt to access them, including properties of an Array. A function with no return statement implicitly returns undefined.
I would suggest making sure you know exactly what values are possible for the variable or property you're testing and testing for these values explicitly and with confidence. For testing null, use foo === null. For testing for undefined, I would recommend using typeof foo == "undefined" in most situations, because undefined (unlike null) is not a reserved word and is instead a simple property of the global object that may be altered, and also for other reasons I wrote about recently here: variable === undefined vs. typeof variable === "undefined"
The difference between null and undefined is that null is itself a value and has to be assigned. It's not the default. A brand new variable with no value assigned to it is undefined.
var x;
// value undefined - NOT null.
x = null;
// value null - NOT undefined.
I think it's interesting to note that, when Windows was first written, it didn't do a lot of checks for invalid/NULL pointers. Afterall, no programmer would be dumb enough to pass NULL where a valid string was needed. And testing for NULL just makes the code larger and slower.
The result was that many UAEs were due to errors in client programs, but all the heat went to Microsoft. Since then, Microsoft has changed Windows to pretty much check every argument for NULL.
I think the lesson is that, unless you are really sure an argument will always be valid, it's probably worth verifying that it is. Of course, Windows is used by a lot of programmers while your function may only be used by you. So that certainly factors in regarding how likely an invalid argument is.
In languages like C and C++, you can use ASSERTs and I use them ALL the time when using these languages. These are statements that verify certain conditions that you never expect to happen. During debugging, you can test that, in fact, they never do. Then when you do a release build these statements are not included in the compiled code. In some ways, this seems like the best of both worlds to me.
If you call a function with no explicit return then it implicitly returns undefined. So if I have a function that needs to say that it did its task and there is nothing result, e.g. a XMLHTTPRequest that returned nothing when you normally expect that there would be something (like a database call), then I would explicitly return null.
Undefined is different from null when using !== but not when using the weaker != because JavaScript does some implicit casting in this case.
The main difference between null and undefined is that undefined can also mean something which has not been assigned to.
undefined false
(SomeObject.foo) false false
(SomeObject.foo != null) false true
(SomeObject.foo !== null) true true
(SomeObject.foo != false) true false
(SomeObject.foo !== false) true false
This is taken from this weblog
The problem is that you claim to see the difference, but you don't. Take your example. It should really be:
var List = []; // ordered list contains data at odd indexes.
var getObject = function(id) {
for (var i = 1; i < List.length; i+=2) {
if (id === List[i].getId()) {
return List[i];
}
}
// returns undefined by default
}
Your algorithm is flawed because you check even indexes (even though you know there's nothing there), and you also misuse null as a return value.
These kind of functions should really return undefined because it means: there's no such data
And there you are in the heart of the problem. If you don't fully understand null and undefined and may use them wrongly sometimes, how can you be so sure that others will use it correctly? You can't.
Then there are Host objects with their nasty behavior, if you ask me, you better off checking for both. It doesn't hurt, in fact, it saves you some headaches dealing with third party code, or the aformentioned non-native objects.
Except for these two cases, in your own code, you can do what #bobince said:
Keep undefined as a special value for signalling when other languages might throw an exception instead.
When to set/use them...
Note that a method without a return statement returns undefined, you shouldn't force this as an expected response, if you use it in a method that should always return a value, then it should represent an error state internally.
Use null for an intentional or non-match response.
As for how/when to check...
undefined, null, 0, an empty string, NaN and false will be FALSE via coercion. These are known as "falsy" values... everything else is true.
Your best bet is coercion then testing for valid exception values...
var something; //undefined
something = !!something; //something coerced into a boolean
//true if false, null, NaN or undefined
function isFalsish(value) {
return (!value && value !== "" && value !== 0);
}
//get number or default
function getNumber(val, defaultVal) {
defaultVal = isFalsish(defaultVal) ? 0 : defaultVal;
return (isFalsish(val) || isNaN(val)) ? defaultVal : +val;
}
Numeric testing is the real bugger, since true, false and null can be coerced into a number, and 0 coerces to false.
I would treat them as 2 completely different values, and check for the one you know might occur.
If you're checking to see if something has been given a value yet, check against undefined.
If you're checking to see if the value is 'nothing,' check against 'null'
A slightly contrived example:
Say you have a series of ajax requests, and you're morally opposed to using callbacks so you have a timeout running that checks for their completion.
Your check would look something like this:
if (result !== undefined){
//The ajax requests have completed
doOnCompleteStuff();
if (result !== null){
//There is actually data to process
doSomething(result);
}
}
tldr; They are two different values, undefined means no value has been given, null means a value has been given, but the value is 'nothing'.

How to check if a variable is not null?

I know that below are the two ways in JavaScript to check whether a variable is not null, but I’m confused which is the best practice to use.
Should I do:
if (myVar) {...}
or
if (myVar !== null) {...}
They are not equivalent. The first will execute the block following the if statement if myVar is truthy (i.e. evaluates to true in a conditional), while the second will execute the block if myVar is any value other than null.
The only values that are not truthy in JavaScript are the following (a.k.a. falsy values):
null
undefined
0
"" (the empty string)
false
NaN
Here is how you can test if a variable is not NULL:
if (myVar !== null) {...}
the block will be executed if myVar is not null.. it will be executed if myVar is undefined or false or 0 or NaN or anything else..
code inside your if(myVar) { code } will be NOT executed only when myVar is equal to: false, 0, "", null, undefined, NaN or you never defined variable myVar (then additionally code stop execution and throw exception).
code inside your if(myVar !== null) {code} will be NOT executed only when myVar is equal to null or you never defined it (throws exception).
Here you have all (src)
if
== (its negation !=)
=== (its negation !==)
Have a read at this post: http://enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-2/
It has some nice tips for JavaScript in general but one thing it does mention is that you should check for null like:
if(myvar) { }
It also mentions what's considered 'falsey' that you might not realise.
There is another possible scenario I have just come across.
I did an ajax call and got data back as null, in a string format. I had to check it like this:
if(value != 'null'){}
So, null was a string which read "null" rather than really being null.
EDIT: It should be understood that I'm not selling this as the way it should be done. I had a scenario where this was the only way it could be done. I'm not sure why... perhaps the guy who wrote the back-end was presenting the data incorrectly, but regardless, this is real life. It's frustrating to see this down-voted by someone who understands that it's not quite right, and then up-voted by someone it actually helps.
Sometimes if it was not even defined is better to be prepared.
For this I used typeof
if(typeof(variable) !== "undefined") {
//it exist
if(variable !== null) {
//and is not null
}
else {
//but is null
}
}
else {
//it doesn't
}
if (0) means false, if (-1, or any other number than 0) means true. following value are not truthy, null, undefined, 0, "" (empty string), false, NaN
never use number type like id as
if (id) {}
for id type with possible value 0, we can not use if (id) {}, because if (0) will means false, invalid, which we want it means valid as true id number.
So for id type, we must use following:
if ((Id !== undefined) && (Id !== null) && (Id !== "")) {
} else {
}
for other string type, we can use if (string) {}, because null, undefined, empty string all will evaluate at false, which is correct.
if (string_type_variable) { }
if myVar is null then if block not execute other-wise it will execute.
if (myVar != null) {...}
Rather than using multiple condition statements you can use below solution.
if(![false, 0, "", null, undefined, NaN].includes(myVar)){
// It's not a null value
}
The two conditional statements you list here are not better than one another. Your usage depends on the situation. You have a typo by the way in the 2nd example. There should be only one equals sign after the exclamation mark.
The 1st example determines if the value in myVar is true and executes the code inside of the {...}
The 2nd example evaluates if myVar does not equal null and if that case is true it will execute your code inside of the {...}
I suggest taking a look into conditional statements for more techniques. Once you are familiar with them, you can decide when you need them.

Categories