This will be needed later on: elementStr = 'hello'
.
So I am working on an javascript app. In one of my function I have a following if statement:
if (elementStr.indexOf('#') !== 0) {
//true
}
But I don't like the !==
part it doesn't look nice to me. So I tried this:
if (!elementStr.indexOf('#')) {
//false
}
But indexOf() does not return undefinied but it always returns a number. So the first if statement returns true because elementStr
does not have a '#' in the first place of the string. But the second if statement returns false because indexOf returns -1 and thats not 'undefined', but we want it to return true of course like the first example. Because we don't want to change the statement, we just want to make it look better. So by accident I did this:
if (!~elementStr.indexOf('#')) {
//true
}
And gues what, it worked. I tried to find something about that sign, what it does in javascript. But i couldn't find anything. I was playing with it and I got following results:
if (!~~elementStr.indexOf('#')) {
//false
}
if (!~~~elementStr.indexOf('#')) {
//true
}
You can go on and add ~ everytime, and the statement boolean will change all the time.
Now can someone explain me what it does in this example, and if I am safe to use that sign?