The _.get()
method in Lodash retrieves the object’s value at a specific path.
If the value is not present at the object’s specific path, it will be resolved as undefined
. This method will return the default value if specified in such a case.
_.get(object, path, defaultValue)
This method accepts the following parameters:
object
: The object in which the given path will be queried.path
: The path used to retrieve the value from the object.defaultValue
: The default value that will be returned for resolved values that are undefined.This method will return the value at the specified path if found. Otherwise, it will return the default value if specified.
Let’s look at an example of the _.get()
method in the code snippet below:
In the HTML tab:
lodash
script.In the JavaScript tab:
collegeYopPath
to get the value._.get()
method and pass the object
, collegeYopPath
, and a default value as parameters.falsyPath
to get the value._.get()
method and pass the object
, falsyPath
and a default value
as parameters._.get()
method at line 19 contains a valid path, and therefore the expression is resolved, and 2021
is printed on the console._.get()
method at Line 23 contains an invalid path, and therefore the expression is resolved as undefined
.The
_.get()
method is from Lodash which is a third-party dependency. Using a third-party utility could increase the bundle size. Another solution for this could be using built-in features, such as, nullish coalescing. It is a native feature of javascript which can replace.
Free Resources