Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Benefit of using Lodash's has-method over Vanilla-JS?

Tags:

javascript

After having a look at this example from the Lodash-documentation of the has-method:

var object = { 'a': { 'b': 2 } };

_.has(object, 'a.b');
// => true

I asked myself: What's the actual purpose of using this method?

Wouldn't be ...

if (object.a.b) {
    ...
}

the same and isn't more code too?

like image 753
cluster1 Avatar asked Oct 28 '25 09:10

cluster1


1 Answers

In vanilla JS, your code will throw an error if object, or object.a is undefined:

const object = {};
if (object.a.b) {
}

Thus the lodash method.

console.log(_.has({}, 'a.b'));
console.log(_.has(undefined, 'a.b'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.core.min.js"></script>
like image 165
CertainPerformance Avatar answered Oct 29 '25 22:10

CertainPerformance