Syntax, Parameter and Return Value
Syntax:
_.eq(value, other)
Parameters:
-
value: The value to compare.
- other: The other value to compare.
Return Value:
(boolean) - Returns true if the values are equivalent, else false.
Examples
Comparing Primitive Values:
JavaScript
var _ = require('lodash');
console.log(_.eq(1, 1));
console.log(_.eq(1, '1'));
You can also try this code with Online Javascript Compiler
Run Code
Output:
true
false
Demonstrates the comparison of primitive values, emphasizing type equality.
Comparing Different Types:
JavaScript
console.log(_.eq('hello', 'hello'));
console.log(_.eq('hello', ['hello']));
You can also try this code with Online Javascript Compiler
Run Code
Output:
true
false
Shows that values of different types are not considered equal.
Checking Equality of Objects:
JavaScript
var object = { 'a': 1 };
var other = { 'a': 1 };
console.log(_.eq(object, object));
console.log(_.eq(object, other));
You can also try this code with Online Javascript Compiler
Run Code
Output:
true
false
An example of object comparison, highlighting that different instances are not equal, even with identical properties.
Equality Check with Arrays:
JavaScript
var array = [1, 2, 3];
var otherArray = [1, 2, 3];
console.log(_.eq(array, array));
console.log(_.eq(array, otherArray));
You can also try this code with Online Javascript Compiler
Run Code
Output:
true
false
Demonstrates that only the same array instance is considered equal, not arrays with identical elements.
Frequently Asked Questions
How is _.eq() different from JavaScript's === operator?
_.eq() and the === operator function similarly in terms of strict equality checking. The primary difference is that _.eq() can handle certain edge cases and is consistent across different JavaScript environments.
Does _.eq() work with complex objects like Date or RegExp?
Yes, _.eq() works with complex objects. However, for these objects, the equality is based on the reference, not the content. Two different instances with the same content are not considered equal.
Can _.eq() be used for deep equality checks?
No, _.eq() performs a strict equality check, which is not suitable for deep equality. For deep equality checks, Lodash provides the _.isEqual() method.
Conclusion
Lodash's _.eq() method offers a reliable and consistent way to perform strict equality checks in JavaScript. It ensures precise comparison of values, making it a useful tool for situations where exact equivalence is necessary.
You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSA, DBMS, Competitive Programming, Python, Java, JavaScript, etc.
Also, check out some of the Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.