Trying to decipher a snippet of code that is tasked with generating random tweets has left me puzzled. Specifically, I find myself stumped when it comes to understanding the line:
Math.floor(Math.random() * arr.length)
I believe this line selects a random array element by taking a random array length multiplied by a decimal between 0 and 1, then converting it to the nearest integer which is used as the index for randArrayEl[].
However, my confusion deepens when trying to comprehend how it picks random first and last names with:
return randArrayEl(fakeFirsts) + " " + randArrayEl(fakeLasts);
If anyone could breakdown the logic behind each line in this code snippet, I would greatly appreciate it.
var randArrayEl = function(arr)
{
return arr[Math.floor(Math.random() * arr.length)];
};
var getFakeName = function()
{
var fakeFirsts = ['Nimit', 'Dave', 'Will', 'Charlotte', 'Jacob','Ethan','Sophia','Emma','Madison'];
var fakeLasts = ["Alley", 'Stacky', 'Fullstackerson', 'Nerd', 'Ashby', 'Gatsby', 'Hazelnut', 'Cookie', 'Tilde', 'Dash'];
return randArrayEl(fakeFirsts) + " " + randArrayEl(fakeLasts);
};
var getFakeTweet = function()
{
var awesome_adj = ['awesome','breathtaking','amazing','sexy','sweet','cool','wonderful','mindblowing'];
return "Fullstack Academy is " + randArrayEl(awesome_adj) + "! The instructors are just so " + randArrayEl(awesome_adj) + ". #fullstacklove #codedreams";
};
for(var i=0; i<10; i++)
{
store.push(getFakeName(), getFakeTweet());
}
Furthermore, could someone explain the purpose of the for loop at the end?