I am hoping that I can get some help with my learning and find out what it is about my function that is not working correctly:
function contains() {
var substr = 'bar';
var str = 'foobar';
if (str.indexOf(substr)) {
// Return true if substr is a substring of str
return true;
} else {
// and false if substr is not a substring of str
return false;
};
}
Thank you in advance for anyone who can help me get over this bump in learning.
Rob
indexOfreturns-1if it’s not found, and~-1 === 0is falsy. Every other number returns truthy with~(since all numbers other than0are truthy).~is the bitwise NOT which has an interesting property that~-1 === 0.!!converts to a boolean (truthy becomestrue, falsy becomesfalse).So you could do:
You’re currently returning
trueif it’s not found (-1is thruthy), andfalseif it’s at position0(0is falsy).