I was reviewing some source code and underscore/lodash was included just for the _.isBoolean function. The underscore source is below:
_.isBoolean = function(obj) {
return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
};
Looking at Function components in ng I see similar functions (angular.isObject, angular.isString, angular.isNumber, etc), but no angular.isBoolean function.
The angular.js source has this an internal function (source below), but an issue requesting to make public (feat: register isBoolean as a public member of global angular #5185) was closed saying "other libraries like underscore and lodash solve these problems well".
function isBoolean(value) {
return typeof value === 'boolean';
}
Questions:
My initial reaction was to copy isBoolean and make a named function in my code, but which implementation is more correct?
Do I use the underscore version in anticipation of compatibility with a future upgrade?
I assume it is a bad idea to "duck punch" my implementation into angular.isBoolean?
I was reviewing some source code and underscore/lodash was included just for the _.isBoolean function. […] My initial reaction was to convert isBoolean to a local function
Yes, good idea (if you emphasize the just). Maybe not even a function, but simply inline it.
but which implementation is more correct?
They behave differently when objects that are instances of the Boolean class are passed in. Will such ever occur in the app you are reviewing? Probably not. If they do, only you will know whether you want to consider them as booleans.
Apart from that, val === true || val === false has the same effect as typeof val == "boolean".
I assume it is a bad idea to "duck punch" my implementation into angular.isBoolean?
It's unlikely that angular will ever do this, so you hardly will provoke a collision. Still, ask yourself: Is it actually useful there? Will other code use it? For more discussion, have a look at Don't modify objects you don't own.
Related
I just saw a blog post with the code
if(Object.prototype.toString.call(callback) !== '[object Function]'){
return new TypeError(callback + ' is not a function');
};
In this specific situation it looks like over-engineering it since we could use typeof callback. I see no situation, for the purpose of this code, where typeof callback would not give the correct answer. Even more, the prototype could be overridden and start giving wrong answers while typeof can't.
Example would be:
Object.prototype.toString = function(){return '[Object String]';};
Object.prototype.toString.call([])
// logs "[Object String]"
Question: is there any situation (given the purpose of this line, which is to check if a variable is a function) where typeof would fail?
I think its more correct, semantic and not over-engineering to use:
if(typeof callback !== 'function'){
return new TypeError(callback + ' is not a function');
};
The Object.prototype.toString check is from the ES5 and earlier era, when the results of that method could not be forged through a custom Symbol.toStringTag implementation. However even then, if one wanted to be very strict about these tests, they would usually have had to grab a reference to the toString function at initial evaluation time, since Object.prototype.toString can itself be overwritten — as could Function.prototype.call.
Today it would never make sense to perform a type check this way, and you’re correct that even at the time, it wasn’t typically necessary. However in the past there were a number of platform objects in browsers that returned unique strings from typeof, and that was likely one of the motivations for performing a test this way. Today there is only one such weird case remaining: typeof document.all returns undefined, but it is actually a function.
Your instinct to prefer typeof is still correct, though. The case of document.all is probably not worth worrying about in almost any code, and even if it is, the toString check will not be reliable. An example of a real reliable (paranoid) check would be:
var _Object = Object;
function isObject(value) {
return _Object(value) === value;
}
function isFunction(value) {
return typeof value === 'function' || (isObject(value) && typeof value === 'undefined');
}
console.log(isFunction(function() {})); // true
console.log(isFunction(document.all)); // true
So the answer to the part you marked ‘question’ is yes, there is one situation where typeof n === 'function' returns a misleading string, and historically there were additional situations.
More meta, regarding the ‘overengineering’ question: Perhaps the author learned it as a ‘best practice’ at some time in the past and hasn’t reviewed it in a while because, hey, it’s what’s familiar to them and it works, etc. Although there are better options, I wouldn’t call an awkward if condition overengineering. To me at least, overengineering refers to stuff at a higher level than this — architectural choices, etc. Things that are hard to refactor.
Personally, I would suggest that if you’re writing code that performs early input validation a lot, eschewing direct use of typeof might still be a good idea. Testing ‘types’ in JS is often not so straightforward, so a collection of isSomething functions like those in the example above can help abstract away the quirkier implementation details and bring some consistency and readability back. As functions, they’re also more flexible (e.g. arr.filter(isFunction)). There are popular libs that provide such utils and if using them you typically won’t need to worry about how it’s being achieved.
Is it acceptable to use type coercion (== instead of ===) to check for undefined/null?
What are the downsides? Is there a better way to check for undefined/null?
Clarification: I am looking for a statement that will check for both undefined and null.
test(null);
test(undefined);
function test(myVar) {
if (myVar != undefined) {
alert('never gets called')
}
}
I'm going to attempt to address this question as objectively as possible, but it deals with some mushy "best practices" opinion stuff that can trigger people to forget that there's more than one way to do things.
Is it acceptable to use type coercion (== instead of ===) to check for undefined/null?
It's acceptable to write code however you see fit regardless of anyone who tells you otherwise. Including me.
That's not really helpful here, so let me expand on that a bit, and I'll let you decide how you feel about it.
Code is a tool that can be used to solve problems, and == is a tool within JavaScript code to solve a specific problem. It has a well-defined algorithm which it follows for checking a type of equality between two parameters.
===, on the other hand, is a different tool that solves a different, specific problem. It also has a well-defined algorithm which it follows for checking a type of equality between two parameters.
If one tool or the other is appropriate for your use-case, then you shouldn't hesitate to use the tool.
If you need a hammer, use a hammer.
But if all you have is a hammer, then everything looks like a nail, and this is the core issue with ==. Developers coming from other languages often aren't aware of how == works and use it when === would be appropriate.
In fact, most use cases are such that === should be preferred over ==, but as you've asked in your question: that's not true in this instance.
What are the downsides?
If you relax your standards for === and allow developers to use == you may very well get bitten by misuse of ==, which is why sticking religiously to === may be acceptable to some, and seem foolish to others.
if (val === null || val === undefined) {...
is not particularly difficult to write, and is very explicit about intent.
Alternatively,
if (val == null) {...
is much more concise, and not difficult to understand either.
Is there a better way to check for undefined/null?
"better" is subjective, but I'm going to say, "no" anyway because I'm not aware of any that improve the situation in any meaningful way.
At this point I will also note that there are other checks that could be performed instead of null/undefined. Truthy/falsey checks are common, but they are another tool used to solve yet another specific problem:
if (!val) {...
is much more concise than either of the previous options, however it comes with the baggage of swallowing other falsey values.
Additional notes on enforcement via linting:
If you follow the strictness of Crockford's JSLint, == is never tolerated, in the understanding that a tool that's "sometimes useful" but "mostly dangerous" isn't worth the risk.
ESLint, on the other hand, allows for a more liberal interpretation of the rule by providing an option to allow null as a specific exception.
== undefined and == null are both equivalent to checking if the value is either undefined or null, and nothing else.
As for "acceptable", it depends on who is looking at the code, and whether your linter is configured to ignore this special case.
I can tell you for sure that some minifiers already do this optimisation for you.
The ideal way to test for undefined is using typeof. Note you only need to test them separately if you care about a difference between undefined and null:
test(null);
test(undefined);
function test(myVar) {
if (typeof myVar === "undefined") {
// its undefined
}
if (myVar === null) {
// its null
}
}
If you don't care if its undefined/null, then just do:
test(null);
test(undefined);
function test(myVar) {
if (!myVar) {
// its undefined or null, dunno which, don't care!
}
}
I have a given function that takes, among other arguments, two optional arguments which may be functions. Both need to be optional, one will be a function, and one will either be a boolean or a function that returns a boolean.
// Obj.func(variable, String[, Object][, Boolean||Function][, Function]);
Obj.func = function(other, assorted, args, BoolOrFunc, SecondFunc) {
// execution
};
Obj.func(
[
'some',
'data'
],
'of varying types',
{
and: 'some optional arguments'
},
function() {
if(some condition) {
return true;
}
return false;
},
function() {
// do things without returning
}
);
It is my desire that both functions (and several of the other arguments, if it matters) be optional, which means I have code in the function to determine which arguments the user intended to use.
Unfortunately, as both may be functions, and may be specified directly in the function call, I cannot simply use typeof or instanceof conditionals. However, since the first function, if it exists, will always return a boolean (and the second function will not return at all), one idea I had would be to check its return value:
if(typeof BoolOrFunc === 'boolean'
|| (typeof BoolOrFunc === 'function' && typeof BoolOrFunc() === 'boolean')) {
// BoolOrFunc is either a boolean or a function that returns a boolean.
// Handle it as the intended argument.
} else {
// Otherwise, assume value passed as BoolOrFunc is actually SecondFunc,
// and BoolOrFunc is undefined.
}
This works in principle; however, running typeof BoolOrFunc() executes the function, which causes a problem if the function does more than just return a boolean: that is, if the function passed as BoolOrFunc is actually meant to be SecondFunc. SecondFunc, in this case, is something of a callback function, and may perform actions, including DOM modifications, that I don't want to execute immediately.
For this reason, my question is: Is there a way to check if a function returns without executing it?
One thing I had considered was to call BoolOrFunc.toString(), then perform a Regular Expression search for the return value, something along the lines of…
if(typeof BoolOrFunc === 'boolean'
|| (typeof BoolOrFunc === 'function'
&& BoolOrFunc.toString().search(/return (true|false);/) !== -1)) {
// BoolOrFunc is either a boolean or contains a return string with a boolean.
// Handle it as the intended argument.
}
Note that the above code may not work as written: I've not actually built a test case for it, because, well, it seems exceptionally inefficient and potentially unreliable, and I figured someone here might have a more elegant solution to my quandary. That having been said, I figured I'd include it for discussion purposes.
Meshaal made a prediction in the question:
"... one will either be a boolean or a function that returns a boolean."
"... first function, if it exists, will always return a boolean."
With this prediction the function is not a Turing Machine, because we know that it returns something. Surely it can't be done with a simple RegExp: just return !0 would break the example.
But if you parse the result of function.toString() with a parser being intelligent enough to find all possible return points, the problem should principally be solvable.
Interesting question, if I understand correctly. First, I'd probably warn against having such open-ended arguments. I'm curious as to the use case.
But that said, it's easy enough to get around the problems you mention (which may not wholly solve your problem).
This works in principle; however, running typeof BoolOrFunc() executes the function...
That's easy enough to fix, I think. At first, just check to see if BoolOrFunc is a boolean or a function (just typeof BoolOrFunc, natch). If it's a boolean, I assume we're fine. Either SecondFunc is missing (undefined) or a function -- or we're in an error state. That's all easy to handle in this first case.
So let's assume the second case, that we have BoolOrFunc-As-Function. We're going to have to execute it, whether it's "really" BoolOrFunc or SecondFunc, so, at the last moment possible in your code, do so.
This is obviously where things get complicated without more pseudo-code (or production code) from you. If the "possible BoolOrFunc" returns true or false, you know you have a function version of BoolOrFunc. If it returns undefined, you know you just called SecondFunc. Again, depending on what you're trying to do, you branch here. If you have a true or false, you have to process out "BoolOrFunc-as-function", else you've called SecondFunc and are likely done.
That doesn't answer the more generic question of how to tell if a function returns a specific type without calling it, but does solve your use case as presented here.
But this specific more generic case [sic] isn't too difficult, as long as we're dealing with real, constant booleans in the returns. In that case, the regexp route would work -- find all return\s+.*; and make sure what follows each return is true or false. Or just compare total return count is the same as that for return\s+(false|true);. Or something. And hope the javascript in the function is well formed. What a bear already.
If the function can return local variables (return MightBeBoolean; rather than return true;), you're nearly toast -- or if you accept truthiness or falsiness, you're nearly toast again, since undefined is falsey, and you can't tell the difference between BoolOrFunc or SecondFunc (which would always return "falsey"). It's possible, but not nearly worth writing the parser in any reasonable use case I can imagine. And if you're importing a lib to do that, sheesh. Good luck. Seems like overkill to have function that's slightly more defensive in its calling.
I do wonder if either functions passed as arguments are themselves passed arguments from your Obj.func, which would make things even more interesting.
Got more real code? ;^) But ultimately I'm recommending you don't do the "pass any jumble of arguments, as long as they're in order". I think you can likely do the BoolOrFunc/SecondFunc late evaluation. Otherwise, I hate to say it, but code a bit more offensively here.
I would like advice as to best practice in testing object existence for cross-browser compatibility.
There seem to be many ways of testing for object/function/attribute existence. I could use jquery or another library, but for now I want to stick as closely as possible to w3c rather than use what amounts to a whole new language.
What I'm trying to do
I'm trying to write a utility library that tries to stick to w3c methods so I can just call
xAddEventListener(elem, type, listener, useCapture)
for all browsers rather than
elem.AddEventListener(type, listener, useCapture)
just for w3c compliant browsers. If another library already does this, please let me know.
I saw this today:
if (typeof node.addEventListener == "function")
but will this ever yield a different result than plain
if (node.addEventListener)
Style documents?
A reference to a standards or styles document would also be useful. I've found https://developer.mozilla.org/en/Browser_Detection_and_Cross_Browser_Support
but that was last updated in 2003. It advocates simple
if (document.images)
tests for most existence tests and
if (typeof(window.innerHeight) == 'number')
only with numbers because if(0) would evaluate to false
Examples to inspire comment:
if (myObject)
Can an object or function ever fail this simple test?
if (myObject != undefined)
When is this better than the previous test?
if (typeof(myObject) == 'object')
This appears to be the original way of calling type of, but some people say that typeof is a keyword and not a function. Also, why not one of the simpler tests?
if ( typeof myObject.function !== undefined ) {
One post said to alway use === or !== as it differentiates between null and undefined. Is this ever important in practice?
Another possibility is:
try {
node.addEventListener(...)
}
catch(err) {
node.attachEvent(...)
}
Which in python appears to be becoming the favourite way of dealing with these type of things.
Using exceptions looks potentially much cleaner as you could write easy to understand w3c compliant code, and then deal with exceptions when they come.
Anyway, what do people think? Please can you list the pros and cons of methods you like/dislike, rather than simply advocating your favourite.
It all depends on how specific you want to be / how much you want to assert before calling a function.
if (myObject)
Can an object or function ever fail this simple test?
No, the only values that do not pass an if clause are false, 0, "", NaN, undefined and null. These are all primitives. Objects (including functions) will always pass an if clause.
if (myObject != undefined)
When is this better than the previous test?
If you want to check whether a value is "meaningful", i.e. not undefined or null. For example,
if(numberInputtedByUser) {
// do something with inputted number
}
will fail the if clause if the number is 0, while you probably want 0 to be allowed. In such case, != undefined is a slightly better check.
if (typeof(myObject) == 'object')
This appears to be the original way of calling type of, but some people say that typeof is a keyword and not a function. Also, why not one of the simpler tests?
It is a keyword. You can call it in a function-like fashion, though. In its most bare form you can use typeof like this:
typeof myObject
You can, however, add (extraneous) parens since they don't mean anything:
typeof (myObject)
Just like you can do:
(myObject).key
or even:
(((myObject))).key
And you can then remove the space after the typeof if you want, resulting in something that looks like a function call.
As to why to use typeof - you can be even more certain of the type of variable. With the if(...) test, the values that pass can be all kind of things - basically everything except the list I posted above. With if(... != undefined), you allow even more to be passed. With if(typeof ... == 'object'), you really only allow objects which might be necessary depending on what you're processing.
if ( typeof myObject.function !== undefined ) {
One post said to alway use === or !== as it differentiates between null and undefined. Is this ever important in practice?
=== is really preferred over ==. While differentiating between null and undefined is not always necessary, it is a very good practice to save yourself from the results of quirks like 0 == ''. If you want to check whether a number is 0, then === 0 is the way to go, since == 0 also allows for an empty string (which you might not expect and probably don't want). Even in cases == doesn't cause quirks, you'd be better off using === at all times for consistency and avoiding surprising bugs.
try {
node.addEventListener(...)
}
catch(err) {
node.attachEvent(...)
}
This is of course possible and very straight-forward. Note however that try catch is said to be slow. Moreover, you don't really account for why it fails. It's a bit simple-minded (but may work fine).
if (typeof node.addEventListener == "function")
but will this ever yield a different result than plain
if (node.addEventListener)
Yes, like I said above, the first only passes functions whilst the second allows anything except that list of "falsy" values. One could add Node.addEventListener = 123, and it will pass the if clause in the second case. But IE fails to give a correct typeof result:
typeof alert !== "function"
I bet the same goes for addEventListener so you'd still be avoiding that function even if it exists.
In the end, I would just use a simple if clause. Of course this will fail when you add weird things like Node.addEventListener = 123, but then again you're bound to expect weird things happen.
I'm currently in the creation of a javascript function library. Mainly for my own use, but you can never be sure if someone else ends up using it in their projects, I'm atleast creating it as if that could happen.
Most methods only work if the variables that are passed are of the correct datatype. Now my question is: What is the best way to alert users that the variable is not of the correct type? Should one throw an error like this?
function foo(thisShouldBeAString){ //just pretend that this is a method and not a global function
if(typeof(thisShouldBeAString) === 'string') {
throw('foo(var), var should be of type string');
}
#yadayada
}
I know that javascript does internal type conversion, but this can create very weird results (ie '234' + 5 = '2345' but '234' * 1 = 234) and this could make my methods do very weird things.
EDIT
To make things extra clear: I do not wish to do type conversion, the variables passed should be of the correct type. What is the best way to tell the user of my library that the passed variables are not of the correct type?
The problem with type checking is that its actually quite hard to do. For example:-
var s = new String("Hello World!");
alert(typeof s);
What gets alerted? Ans: "object". Its true its a daft way to initialise a string but I see it quite often none-the-less. I prefer to attempt conversions where necessary or just do nothing.
Having said that in a Javascript environment in which I have total control (which is not true if you are simply providing a library) I use this set of prototype tweaks:-
String.prototype.isString = true;
Number.prototype.isNumber = true;
Boolean.prototype.isBoolean = true;
Date.prototype.isDate = true;
Array.prototype.isArray = true;
Hence testing for the common types can be as simple as:-
if (x.isString)
although you still need to watch out for null/undefined:-
if (x != null && x.isString)
In addition to avoiding the new String("thing") gotcha, this approach particularly comes into its own on Dates and Arrays.
Some small remarks on type checking - it's actually not that complicated:
Use typeof to check for primitives and instanceof to check for specific object types.
Example: Check for strings with
typeof x === 'string'
or
typeof x === 'string' || x instanceof String
if you want to include string objects.
To check for arrays, just use
x instanceof Array
This should work reasonably well (there are a few known exceptions - eg Firefox 3.0.5 has a bug where window instanceof Object === false although window.__proto__ instanceof Object === true).
edit: There are some further problems with detection of function objects:
In principle, you could both use typeof func === 'function' and func instanceof Function.
The catch is that in an unnamed browser from a big corporation these checks return the wrong results for some predefined functions (their type is given as 'object'). I know of no workaround for this - the checks only work reliably for user-defined functions...
edit2: There are also problems with objects passed from other windows/frames, as they will inherit from different global objects - ie instanceof will fail. Workarounds for built-in objects exists: For example, you can check for arrays via Object.prototype.toString.call(x) === '[object Array]'.
Libraries like jQuery do not inform the user of the error.
If a function is expecting a number, and a user passes a string, the function just returns without doing anything.
That way, you will avoid JavaScript errors popping up on a live website.
PS. Just make sure to always type check your inputted parameters, to avoid JavaScript errors being thrown.
How about throw:
https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Statements/throw
Also type of does not distinguish between Array, Null, Object very well. Look at the funciton here: http://javascript.crockford.com/remedial.html, plus there are a few other ways to do it.
Personally I would not do the type checking since it is a step that will just add more processing time to the code. If you care about performance, you would want to chop off as many milliseconds of processing time as possible. Good Documentation will cure the need for the check.
What's about just to silently convert string to numeric datatype on function startup?
You always can determine the datatype of 'string'. Can't you?
You could check for some value like "debug=1" set. If there is - you could output errors like alerts. So in development mode user will see them, but on real site he will turn it off. Same way browser will not show you error message - you need to look at JS console.
Also there is FireBug. You could detect that and put FB debug Messages also.