Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when I pass an empty string into includes("") will it always return true?

So, I am testing the JS includes() method, so I created a search input field, where I can search through the notes I created with live rerendering. Now my question is: When I pass no searchtext at all, all the notes are shown, but when I enter a character or a word, the notes get filtered right away. Example code:

const filters = {
  searchText: ''
}

// Render application notes
const renderNotes = (notes, filters) => {
  const filteredNotes = notes.filter((note) => {

    return note.title.toLowerCase().includes(filters.searchText.toLowerCase())
  })
  document.querySelector('#notes').innerHTML = ''

  filteredNotes.forEach((note) => {
    const noteEl = generateNoteDOM(note)
    document.querySelector('#notes').appendChild(noteEl)
  })
}

I understand from this, that true is always returned in such a case.. Would appreciate any clarification to this subject!

Thanks!

like image 423
Michael Avatar asked Jul 30 '18 14:07

Michael


People also ask

Does an empty string return true?

All false , 0 , empty strings '' and "" , NaN , undefined , and null are always evaluated as false ; everything else is true .

Is empty string true or false in JS?

There are only six falsey values in JavaScript: undefined , null , NaN , 0 , "" (empty string), and false of course.

Why empty string is false?

Empty strings are "falsy" which means they are considered false in a Boolean context, so you can just use not string.

Is empty string valid?

The empty string is a legitimate string, upon which most string operations should work. Some languages treat some or all of the following in similar ways: empty strings, null references, the integer 0, the floating point number 0, the Boolean value false, the ASCII character NUL, or other such values.


1 Answers

The .includes() function has to match the functionality of .indexOf() for consistency, and .indexOf() always matches the empty string in any target string. From MDN:

An empty string searchValue will match at any index between 0 and str.length.

It's a little counter-intuitive, but consider this:

var str = "something";
console.log(str.includes("")); // Imagine this returns false ...
str += "";
console.log(str.includes("")); // !!
like image 120
Pointy Avatar answered Oct 16 '22 07:10

Pointy