<script src="https://cdn.jsdelivr.net/lodash/4.16.0/lodash.min.js"></script>
var person = {name: 'Frederick', lastName: 'Corcino Alejo'};
_.get(person, 'name');
person?.name
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash get | |
Native |
Test name | Executions per second |
---|---|
Lodash get | 40952368.0 Ops/sec |
Native | 154695408.0 Ops/sec |
Let's break down the benchmark and its components.
Benchmark Overview
The benchmark compares two approaches to access a nested property in an object: Lodash's _.get
method and native JavaScript syntax using optional chaining (?.
).
Options Compared
_.get
method: This is a utility function provided by the Lodash library, which helps with accessing nested properties in objects..property ?
): This approach uses the optional chaining operator (?.
) to access the nested property.Pros and Cons
_.get
method:Special JavaScript Feature
The benchmark uses the optional chaining operator (?.
), which is a relatively recent feature introduced in ECMAScript 2020 (ES12). This operator allows you to access nested properties without throwing an error if they don't exist. The syntax person?.name
is used to check if person
has a name
property before trying to access it.
Library Used
The benchmark uses the Lodash library, which provides various utility functions for working with objects, arrays, and other data structures. In this specific case, the _.get
method is used to access nested properties.
Other Considerations
When deciding between these two approaches, consider the following factors:
_.get
method can provide more explicit code for accessing nested properties, making it easier to read and understand.Alternatives
Other alternatives for accessing nested properties include:
[]
) notation: person['name']
is a more traditional way of accessing properties in JavaScript.person.name
in
operator: if ('name' in person)
can be used to check if an object has a property.However, these alternatives might not provide the same level of readability or explicitness as Lodash's _.get
method or native JavaScript syntax with optional chaining.