javascriptobjectif-statementmethods

Why can if statement works using an object (like Map) with ".has()" and no working with ".includes"?


That's my code to explain my idea better (I'm a non english speaker):

The ".includes()" method doesn't work in this case

const sentence = "hello world hello boy";

let words = sentence.split(" ");

const quantWords = new Map();

for (let word of words) {  
    if (quantWords.includes(word)) {
        quantWords.set(word, + 1);
    } else {
        quantWords.set(word, 1);
    }
}
console.log(quantWords);

Otherwise, using ".has()", it works

const sentence = "hello world hello boy";

let words = sentence.split(" ");

const quantWords = new Map();

for (let word of words) {  
    if (quantWords.has(word)) {
        quantWords.set(word, + 1);
    } else {
        quantWords.set(word, 1);
    }
}
console.log(quantWords);

Solution

  • The ".includes()" method doesn't work in this case

    .includes is available on array objects (searches if the array has the value).

    Otherwise, using ".has()", it works

    .has is available on Map objects (searches if the Map contains Key).

    Your object is of type 'Map'

    const quantWords = new Map();