What is an "authoritative" way to detect if the _
variable is loaded with lodash or underscore?
I am using lodash for a project in an environment where underscore may sometimes also be loaded.
Currently, I've come up with this:
/**
* lodash defines a variable PLACEHOLDER = '__lodash_placeholder__'
* so check if that is defined / contains the string "lodash"
*/
if ( typeof( _.PLACEHOLDER ) == 'undefined' || _.PLACEHOLDER.indexOf( 'lodash' ) < 0 ) {
// _ is underscore, do what I need to access lodash
}
Important update: The above code does NOT work!
Is there an "authoritative" way to detect if _
is lodash or underscore?
Notes:
This is a specific request to find a way to determine if lodash or underscore is loaded in the _
variable:
1. It is outside of my control whether underscore is loaded or not. (lodash is within my control, and will always be loaded).
2. The load order of lodash / underscore can not be relied upon.
3. The version of underscore that is loaded is likely to change (it's part of a CMS framework that may be updated).
4. Lodash 4.17.x has 300+ functions. My code utilizes many of the functions in lodash.
5. Lodash contains many functions that underscore does not provide.
6. Some of the functions that do exist in both libraries have different implementations.
Lodash and Underscore are great modern JavaScript utility libraries, and they are widely used by Front-end developers.
Lodash helps in working with arrays, strings, objects, numbers, etc. The _. isNil() method is used to check if the value is null or undefined. If the value is nullish then returns true otherwise it returns false.
isUndefined() method is used to find whether the given value is undefined or not. It returns True if the given value is undefined. Otherwise, it returns false.
Going along similar lines as @bhantol already noted, there is a Migrating doc with a list of differences between lodash and underscore that were not compatibilized with. Can't those be used? For example,
if ( typeof( _.invoke ) !== 'undefined' ){
// it's lodash
}
But yeah, amplifying comments by @felix-kling and @tadman and others, if possible, it might be more reliable to restrict the question to the feature (e.g.: specific method) level rather than the whole library.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With