Optimization via the use of built-in functions in JavaScript

Let some programmer check if the array contains the number 3:

let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]; let exists = false; for (let elem of arr) { if (elem === 3) { exists = true; break; } } console.log(exists);

I claim that there is something wrong with this code. What is wrong, we exit the loop after we have found the number 3? The fact is that functions built into JavaScript always work faster than similar self-written code.

In our case, there is the includes function that solves the problem, and we need to use this particular function:

let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]; console.log(arr.includes(3));

Moral: Before solving a problem, be sure to check if there is a built-in JavaScript function to solve it.

The following code checks if a string starts with 'http'. Perform optimization:

let str = 'http://learn.itnots.ru'; if (str[0] + str[1] + str[2] + str[3] === 'http') { console.log('+++'); } else { console.log('---'); }

The following code populates an array with a given value. Perform optimization:

let arr = fillArr('x', 5); console.log(arr); function fillArr(val, amount) { let arr = []; for (let i = 1; i <= amount; i++) { arr.push(val); } return arr; }
enru