Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

374
Views
Why is includes() not working in javascript

const myArray = [
  [2, 4], "cat", "hamster", 9
]
console.log(myArray.includes("cat"))
console.log(myArray.includes([2, 4]))

output is true, false. does includes() not work for arrays inside of arrays? thanks

about 4 years ago · Santiago Gelvez
2 answers
Answer question

0

Because Array in js is a specific object, the [2,4] inside myArray is object and [2,4] that you switch to includes is anther object. If you want that includes return true you must do this:

var array = [2, 4]

const myArray = [array, "cat", "hamster", 9]

console.log(myArray.includes(array))
about 4 years ago · Santiago Gelvez Report

0

A string is a value type, so a comparison between two strings will compare the value of those strings. In your case the value cat. However, an array is an object with reference comparison, not value comparison. So when comparing two arrays the reference will be compared. That is if you compare the same object to itself the result will be true. However, as is the case in your example, if you compare two different objects even with all the properties set to the same value, the result will be false.

let a = [1,2];
let b = 2;
let c = "string";
let d = [1,2];

a === a; //true reference comparison comparing an object to itself
b === 2; //true value comparison
c === "string"; //true again value comparison, even though it's two different objects
a === d; //false the values are the same but it's reference  comparison

Array.includes iterates through the array and makes a comparison between the argument and the individual elements using the above comparison types depending on the types.

It's also important to note that includes uses strict comparison. That is if a comparison with === results in true then so would includes. It's not enough that == would result in true. "2" == 2is an example of a comparison that returns true where ["2"].includes(2) returns false

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!