To Infinity and beyond ๐Ÿš€๐Ÿš€

ยท

2 min read

More like, what happens when you see something strange in Javascript and refuse to just Google it?

So I sort of refreshed my JavaScript journey with the book Eloquent JavaScript.

While studying the chapter on Data structures: objects and arrays, I came upon this function that fishes out the highest number in an array.

The function sort of imitates the Math.max object.

function max(...numbers) {
let result = -Infinity;
for (let number of numbers){
If(number > result) 
result = number; } 
return result;
} console.log(max(4,1,9,-2));

uhh back up. Who on earth is -Infinity and what do they want?

Turns out it goes by negative infinity out in the streets.

Negative Infinity basically is the polar opposite of Infinity.

Since infinity represents the highest possible number, negative infinity reps the lowest possible number.

Result is declared as -infinity so that it stands no chances of being higher than any number in the array we're searching through.

...what? and for let who?

Dot dot aka rest parameters.

for (let number of numbers){
If(number > result) 
result = number; } 
return result;

In the snippet above, for let basically stores each item in the array under the keyword number.

So it loops through the array aka ...numbers in this case, finds an item higher than -Infinity, and returns it as result .

Voila

Now the funny part

It took me almost an hour to figure out the role of -infinity because I refused to do one thing.

I refused to use Google.com. ๐Ÿคฆ

And what's worse, is that I still didn't figure it out until I used Google.

I guess the moral of this whole story is use google fellas!

Just Google it.