Logic accounts as the most significant factor affecting the speed and performance of any given algorithm. On the other hand, simplified syntax comes in as an important feature in reducing syntax noise and clarifying the intent of code, and generally helps us reduce the amount of code we have to write. Our JavaScript algorithms could be made more performant by using the following tips (as a few possible tools in a much bigger bag).


(1) Tilde (~) operator in search functions.

The tilde operator is a useful bitwise operator that flips all _bits _in its operand. Any digit that is a 1 in the expression becomes a 0 in the result whereas any digit that is a 0 in the expression becomes a 1 in the result.

On its own, _indexOf()_returns the index number of a String object passed in or otherwise returns -1 when the query is not found. Using ~ on -1 converts it to 0. The number 0 is a falsy value, meaning that it will evaluate to false when converted to a Boolean. Anything that is not falsy is truthy.

const searchPhrase,str;
if (~searchPhrase.indexOf(str)) {
    // searchPhrase in str
} else {
    // searchPhrase not in str
}

**Note: **As of ES7 released in 2016, JavaScript has Array.prototype.includes() and String.prototype.includes(). These return a boolean value (note that the alternative ~searchPhrase.indexOf(str) returns either 0 or a truthy value). If your target platform(s) support it, you should prefer these for testing for the existence of a value in a string or an array.

let foo = "hello world";
foo.includes("w"); // true
foo.includes("z"); // false

#javascript #es6 #algorithms #web-development

8 Tips to help you better optimize your JavaScript algorithms
200.85 GEEK