Handling Strings, Numbers and Arrays in JavaScript

·

9 min read

JavaScript provides several methods to handle strings and arrays to make the development process seamless. In this article, you will find the methods and concepts that are frequently encountered while handling arrays and strings

Substrings in JavaScript

A substring is a part of the string. Like 'Java' is a substring of 'JavaScript'. We need to work with some portions of the string hence substring is an important topic.


const language = 'English';

const str = language.substring(1, 3)

str will be equal to 'ng'. In the substring method, the upper limit is excluded ie. .substring(idx1, idx2) will give the string from idx1 to idx2 - 1

However the idx2 parameter is optional and incase we don't pass it, the default value will be equal to the length of the original string.

Template strings

One drawback of writing the string using " " or ' ' is that we cannot use the variable in between them. Like

const num = 4;

const str = 'You have num digits';

str won't take the value of num. To tackle this we have the concept of template strings which encloses the string value between backticks

const nnum = 56;
const str = `Your memory has ${nnum}kb RAM`

Additional String methods

We are provided with few additional string methods which come in handy while DOM manipulation

.trim()

It removes the trailing white spaces if any are present in the string value

const str = "   Siddhant       ";
str.trim(); // "Siddhant"

.startsWith() .endsWith()

This method returns a boolean value that is true or false. We can check whether a string starts with a certain string value.

const sentence = "Hello there. Welcome!";

sentence.startsWith("H"); // true
sentence.startsWith("Hello"); // true
sentence.startsWith("Hey"); // false
sentence.startsWith("Sam"); // false

sentence.endsWith("."); // false
sentence.endsWith("!"); // true
sentence.endsWith("Welcome!"); // true
sentence.endsWith("Welcome"); // false

.includes()

This method also returns a boolean value. We can check whether a string is a substring of the input string or not.

const sentence = "Hello there. Welcome!";

sentence.includes("there"); // true
sentence.includes("W"); // true
sentence.includes("Hello"); // true
sentence.includes("Hey"); // false
sentence.includes("Sam"); // false
sentence.includes("."); // true
sentence.includes("!"); // true
sentence.includes("Welcome"); // true

.split()

.split() takes a value and converts the string into an array based on the argument we provide.

let elements = "Eggs, Flour, Rice, Sugar, Milk"
let elements_arr = elements.split(","); // ["Eggs", "Flour","Rice", "Sugar","Milk"]

This is useful when we have to separate elements for generating JWT or parsing CSV files

.replace()

.replace() takes two arguments. The first one is looks for the substring inside the string. If substring is present then it will be replaced by the second argument provided.

const message = "Return will be done in 50 days"
message.replace("50", "7"); // "Return will be done in 7 days"

.replaceAll()

It replaces all the occurrences present in the string and takes two arguments similar to .replace()

Numbers

In JavaScript to write long numbers we don't need to write commas, we can use the underscore 100000 -> 1_00_000 The underscore will be ignored and 10_000 will be read as 10000.

To convert a number to a string


const answer = 42;
answer.toString(); -> "42"

Converting string to number

We use the method Number.parseInt() and it takes two parameters. One parameter is the string_value and the other is the base of the number. The number can be decimal, binary, octal or hex. So here is how we use the Number.parseInt()

const str = "1234"
const str_to_num = Number.parseInt(str,2) -> will convert to binary

Number methods

Apart from the general arithmetic operators like /, +, - % we have .round(), .floor(), .ceil() methods for Numbers.

Math.round(2.6); // 3
Math.floor(2.6); // 2
Math.ceil(2.6); // 3

Math.round(2.5); // 3
Math.floor(2.5); // 2
Math.ceil(2.5); // 3

const benefits

const is used if we don't want to re-assign a variable. This means once we declare an array it will be an array and we can perform the array operations later without any worries.

const is that it does not create a Constant or an Immutable value. We can only use the equal sign once, but we can still change elements inside an array or object.

Variables defined by 'let' and 'const' are blocked scoped.

\== is not advised when comparing two values. Consider the following 2 == "2", JavaScript will return it as true because it will try to convert both the values to the same data type hence === is advised whenever we compare two values.

Array

We get the length of the array by .length property. Similarly, we can access the index by .at() and [] method

const arr = [1,2,3,4]
arr[3]
arr.at(-2)

Just like string .at() will take a -ve value as well

Adding an element in the array

.push() method adds a new element at the end of the array.

If we console.log() .push() method we will get the new length of the array. This is confusing as .push() will add a new element at the end of the array but it will also return the new length of the array


const numbers = [10, 8, 13, 15];
console.log(numbers.push(20)); // returns 5 (the new length of the array)
console.log(numbers); // [10, 8, 13, 15, 20];

.forEach()

Always start with a console.log() inside functions so we know the function is getting executed. .forEach() takes a callback function and iterates over every element of the array.

.forEach() does not return anything unlike .map() or .reduce()[explained later].

.filter()

filter() will take a callback function and will have a certain condition in the callback function based on which it will return values. One thing to note is JavaScript will take our callback and call it for every element of our array. So if our array has 5 items it .filter() will call the callback function 5 times.

.find()

.find() will take a callback function and will return the first element which matches the condition of the callback function. If no items are found you will get undefined as the answer.


let numbers = [9, 5, 14, 3, 11];

let firstNumberAboveTen = numbers.find(function(number) {
    return number > 10;
});
console.log(firstNumberAboveTen); // 14

Notice how we will get 14 as the answer and 11 will be left out because the first encounter stops the further execution of the method. .filter() will return an array even if no item matches the condition it will return an empty array. .find() will return a single value and will return undefined if no item matches the callback function condition

.map()

.map() will take a callback function that will transform every element of the array into another element. .map() will return the same size of the array and will perform the same callback operation on every element.

const nums = [1,2,3,4];
const another_num = nums.map(num => {
    return num%2;
    });

There is a difference between .forEach() and .map(). .forEach() is just an operation and it will not return anything. .map() on the other hand will return the array of exact size but with some change in the elements of the array as per the logic passed in the callback function. In case we have to return an array, .map() should be used.

.includes()

.includes() does not take any callback back rather it takes a value and then returns a boolean value based on whether the array contains the value passed in .includes() or not.

const nums = [-1,5,6,0];
nums.includes(0); // true

.toString()

This method joins the elements of the array separated by a comma ','. .toString() does not take any parameter

const groceries = ["Apple", "Peach", "Tomato"];
groceries.toString(); // "Apple,Peach,Tomato"

.join()

.join() also joins the array element but it provides us the choice to choose the character between the array items. .join() takes a string value that is kept between while joining the two items of an array.

const groceries = ["Apple", "Peach", "Tomato"];
groceries.join("; "); // "Apple; Peach; Tomato"
groceries.join(" . "); // "Apple . Peach . Tomato"

.every()

.every() takes a callback function and returns a boolean value ie true or false when every element of the array fulfills the callback condition provided

const numbers = [15, 10, 20];

const allAbove10 = numbers.every(number => number >= 10); // true
const allAbove15 = numbers.every(number => number >= 15); // false

.some()

It works similar to .every() method but it will return if the array satisfies the callback condition even once.

const nums = [10, 15, 20];
const someUnder10 = nums.some( num => num <10) ; // false
const someAbove19 = nums.some(num => num > 19); // true

.splice()

.splice() takes two arguments where the second argument is optional. The first argument specifies the index and the second argument specifies the number of elements to be removed.

const arr = [1,2,4,56,9];
const deletedItems = arr.splice(1,3) // [2,4,56]
console.log(arr) // [1,9]

Notice deletedItems was returned on using the arr.splice() . If we don't specify the second argument, all the elements starting from the first argument provided will be removed

const arr = [1,2,4,56,9];
const deletedItems = arr.splice(1) // [2,4,56,9]
console.log(arr) // [1]

Empty an array

To empty an array we need to specify the length of the array equal to zero. That's it.

const arr = [1,2,34,566,7,8767,90];
arr.length =0;
console.log(arr) // []

This will not throw an error as we are not re-assigning the array but only performing operations on it. Another way of doing it is using the splice() method

const arr = [1,2,34,566,7,8767,90];
arr.splice(0);
console.log(arr) // arr;

.reduce() method

.reduce() method is a bit complicated at first. In simplest words .reduce() method is used to get a single value from the array. That is once we apply the .reduce() method we will get only one value after the callback operation.

For example, we can get the sum of all elements of an array and multiply all the elements of the array.

.reduce() will take two arguments. One is a callback function and second is the initial value.

const arr = [1,2,3,4];
const sum = arr.reduce((total,current)=> {
    return total + current;
    }, 0);
console.log(sum) // 10

Let's understand what is total and current in the callback function. The 'total' is the computed value till that point. Consider the .reduce() is at index 2. SO 'total' WILL BE EQUAL TO 1 + 2 because we are adding the total and current value. The 'current' will be the current element. SO AT INDEX 2, 'current' WILL BE 3. This is how reduce function will go total current 0 1 1 2 3 3 6 4 10 NA -> execution will stop Initially total is zero because .reduce() takes the second argument which we provided as zero. Had we specified some other initial value(say x) the total initially would have been equal to x. Common Mistakes in .reduce()

  1. Syntax error

  2. Forgetting return statement

  3. Wrong initial value.

Array de-structuring

We are already familiar with array destructuring in JavaScript if we have used useState() in react. Consider we are having an array with length and width.

const arr = [10,20];
const length = arr[0];
const width = arr[1];

OR we can use array de-structuring like this

const arr = [10,20];
const [length, width] = arr;
console.log(length); // 10
console.log(width);// 20

In React we use useState() like this

const [counter, setCounter] = useState(0);

Array concatenation

The easiest way is to use the spread operator. This is how we do it

const num1 = [1,2,3];
const num2 = [4,5,6];
const num3 = [...num1, ...num2];
console.log(num3) // [1,2,3,4,5,6]

Thanks for reading this far, please comment if any methods have been missed that you think is a good to know thing while using JavaScript