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!
All false , 0 , empty strings '' and "" , NaN , undefined , and null are always evaluated as false ; everything else is true .
There are only six falsey values in JavaScript: undefined , null , NaN , 0 , "" (empty string), and false of course.
Empty strings are "falsy" which means they are considered false in a Boolean context, so you can just use not string.
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.
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("")); // !!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With