Strings and Math Object

Strings and Math Object

As we have discussed in the previous article about various methods in arrays. Some of them are used in strings too. Let's take a look.

Strings and their Properties

Strings have a number of built-in properties and some of them resemble the array properties. length, toUpperCase(), slice() and indexOf() works same as in arrays.

let name="nikita";
console.log(name.length);
-> 6

console.log(name.toUpperCase());
-> NIKITA

console.log(name.slice(0, 3));
-> nik

console.log(name.indexOf("i"));
-> 1

One difference in the string's indexOf() property from the array is that it can search for more than one character.

console.log("one two three".indexOf("ee"));
-> 11

trim() method removes whitespace from the start and end of the string.

console.log("  one two three      ".trim());
-> one two three

padStart() takes desired length and padding character as arguments.

console.log(String(6).padStart(4, "0"));
-> 0006

split() and join() are just opposite to each other. split() splits the string in the occurrence of another string while join() joins them again.

let counting = "one two three";
let words = counting.split(" ");
console.log(words);
-> ["one", "two", "three"]

words.join(".");
-> "one.two.three"

So, in the above example, in the case of split() whenever there is space encountered it splits and converts into an array. In the case of join(), it joins the array with "." dot character.

repeat() method repeats the string desired number of times.

console.log("nikita".repeat(2));
-> nikitanikita

The Math Object

You came across many times Math.min, Math.max functions. They are all part of the Math object which is like a container that contains all the Math-related functions.

Apart from Math.min and Math.max, here are other functions too like cos, sin, tan and their inverses. Since too many global bindings pollute the namespace. So, JavaScript provides a single namespace of all the math-related functions.
And we can access all the properties of Math using dot notation whenever need in any program.

There is one such function called random(). Math.random() generates a random number between 0(inclusive) and 1(exclusive) every time you call it.

let randomNumber = Math.random();
console.log(randomNumber);
let wholeNumber = Math.floor(randomNumber*6);
console.log(wholeNumber);

So, random() function always generates fractional numbers but we can convert them into whole numbers using floor() function.
So first, we are generating a random number then converting it into a whole number. But it will give always 0 since values are always between 0 and 1.

Now, imagine a scenario where you create some application where you want to generate random numbers between 0(inclusive) and 6(exclusive). How you can do that?
The answer is you need to multiply 6 with the random number before converting it into a whole number.
Math.floor(randomNumber*6)

Thanks for reading!