# Optimization when converting to an array in JavaScript

You don't always need to convert a string into an array to do something with it. Let's look at an example. Let's say we have the following code:

`let num = 123456789; let arr = String(num).split(''); let sum = 0; for (let elem of arr) { sum += +elem; } console.log(sum);`

Why is splitting into an array bad here? Because, firstly, processor resources are spent on splitting into an array, and secondly, the resulting array will take up space in RAM (moreover, it will be more than the space occupied by the string itself).

But in fact, when using `for-of`, you can iterate not only arrays, but also strings:

`let num = 123456789; let str = String(num); let sum = 0; for (let char of str) { sum += +char; } console.log(sum);`

The following code looks for the sum of digits of the number entered into the input. Perform optimization:

`<input>` `let input = document.querySelector('input'); input.addEventListener('blur', function() { let digits = input.value.split(''); let sum = 0; for (let digit of digits) { sum += +digit; } console.log(sum); });`

The following code counts the number of letters in a string. Perform optimization:

`let str = 'abcaab'; let arr = str.split(''); let i = 0; for (let elem of arr) { if (elem == 'a') { i++; } } console.log(i);`

The following code checks for the presence of a character in a string. Perform optimization:

`let str = 'abcaab'; let arr = str.split(''); console.log(arr.includes('a'));`
← →
↑
en ru