MIT Callback JavaScript Assignment

Corgis ate my MIT JavaScript Assignment.🍦

JavaScript Assignment on Callbacks for MIT MERN Nerds πŸŸ¨πŸ¦πŸ€“

Code with Corgis
Code with Corgis
Published in
6 min readMay 13, 2021

--

Dear πŸ‘‹πŸ’» MERN Nerds,

MAKING LEARNING HOW TO CODE

βœ§γƒ»οΎŸ:* CUTE(β—•β€Ώβ—•βœΏ) and INFORMATIVEα•™(⇀‸↼•)α•—!!!

What is a callback in JS? πŸ“ž πŸ”™

A callback is a function passed as an argument to another function. This technique allows a function to call another function, thus the name Callback.

Why do we have to use callback?

CallbacksπŸ“ž πŸ”™ ensure that a function will not run before a task is completed but will run right after completing the task βœ….

Activity 1: Using For Each Loop ➰

Now, it’s your turn to use forEach

Goal πŸ₯…

This activity is to implement a function called createParagraph that takes an array of strings and returns a single string containing all the items in the array separated by a space.

Code Given

let words = ['Loops', 'are', 'a', 'great', 'way', 'to', 'find', 'elements', 'in', 'an', 'array'];function createParagraph(words) {
let paragraph = '';
// TODO: Write a foreach function
return paragraph;
}
console.log(createParagraph(words));

Output

Loops are a great way to find elements in an array

Step 1. Get array data from the parameter in the create paragraph function called words. Because it is an array, we will attach the forEach method.

words.forEach((word) => {  });

Step 2. Get the empty string variable called paragraph and concatenate the word and space from the forEarch.

Code Solution πŸ–₯️ βœ…

let words = ['Loops', 'are', 'a', 'great', 'way', 'to', 'find', 'elements', 'in', 'an', 'array'];function createParagraph(words) {
let paragraph = '';

words.forEach((word) => { //
paragraph += word + ' '; // Solution
}); //
return paragraph;
}
console.log(createParagraph(words));

Activity 2: Let’s practice callbacks πŸ“ž πŸ”™

Goal πŸ₯…

Your task in this activity is to create a function called filterArray that take 2 arguments:

  • myArray: An array of numbers.
  • isEvenCallBack: A function that returns the Boolean true if a number is even, and returns false if it's odd.

Your task is to implement the isEvenCallBack function and then pass it callback function into filterArray. The function filterArray should then return an array containing only even numbers.

Hint: There are comments in the callbacks.js file to help you through this task

Check the results in your console. If your code works, it should print [2, 6, 12]

Code:

// This is the array that contains numbers for you to work with
var myArray = [1, 2, 5, 6, 12, 23, 15, 31];
// This array should only contain even numbers
var
evenArray = [];
// This code will call your function when the page loads u
// Don't edit this function!
window.onload = () => {
console.log(filterArray(myArray, isEvenCallBack));
};
function filterArray(myArray, isEvenCallBack) { // TODO: use filterArray to determine if a number is even or odd.
// If the number is even, add it to the array 'evenArray'

return evenArray;
}// This function should return 'true' if a number is even and 'false' if a number is oddfunction isEvenCallBack(number) { // TODO: use the mod operator (%) to determine if number is even or odd}

Code Solution πŸ–₯️ βœ…

// This is the array that contains numbers for you to work with
var myArray = [1, 2, 5, 6, 12, 23, 15, 31];
// This array should only contain even numbers
var
evenArray = [];
function filterArray(myArray, isEvenCallBack) { // TODO: use filterArray to determine if a number is even or odd.
// If the number is even, add it to the array 'evenArray'
for (let index = 0; index < myArray.length; index++) {
if (isEvenCallBack(myArray[index])) {

evenArray.push(myArray[index]);
}
}
return evenArray;}// This function should return 'true' if a number is even and 'false' if a number is oddfunction isEvenCallBack(number) {// TODO: use the mod operator (%) to determine if number is even or odd
if (
number % 2 == 0) return true;
else return false;
}// This code will call your function when the page loads up
// Don't edit this function!
window.onload = () => { console.log(filterArray(myArray, isEven));};

Activity 3: Find The Most Common Words

Goal πŸ₯…

The starter code already has some of this functionality implemented.

Please go through the code in the wordcount.js file and read the comments to understand how this logic will work.

Your task is to print to console the first three most common words that appear in a given text.

Notes:

  • In the starter code, some comments start with the words β€œTO DO.” This is where you could add your lines of codes to solve this assignment.
  • The words will need to be scrubbed of any punctuation. To do so, you may choose to use regex and β€œreplace”, or you may choose to get rid of any punctuation marks another way. It is up to you!
  • Watch out for casing. The JavaScript compiler does not think a lowercase and an uppercase letter are the same letter the way humans do. To avoid this, set the entire string to be in lowercase.

Code Solution πŸ–₯️ βœ…

// Count words in text and then order with
// most common first
window.onload = () => { let result = countWords(); console.log(result);};function countWords() {
let
text = "Some of the biggest and most expensive transportation projects in the world have involved building bridges. Bridges are crucial links that carry cars, trucks and trains across bodies of water, mountain gorges or other roads. As a result, they are one of the most important aspects of civil engineering and are subject to intense scrutiny, especially when they collapse. Bridge collapses can be tragic events, leading to loss of life and serious property damage. That is why bridge engineers, designers and builders must always take their jobs very seriously. The best way for them to prevent these accidents is to understand why bridges collapse in the first place. Understanding bridge collapses can lead to major changes in the design, construction and safety of future building projects. The following are main reasons why bridges fall.";
// Remove the periods and commas and make all lowercase letters
text = text.replace(/[.,]/g, "");
text = text.toLocaleLowerCase(); const wordArray = text.split(" "); console.log(wordArray); // Create object and make keys the "words" and the value the "word count" const wordCount = {}; wordArray.forEach((item) => { if (wordCount[item] == null) wordCount[item] = 1; else { wordCount[item] += 1; } }); // Turn objects into an array of arrays
let myArray = Object.entries(wordCount);
// Now sort the arrays based on the count number let bArray = myArray.sort((a, b) => (a[1] < b[1] ? 1 : a[1] > b[1] ? -1 : 0)).slice(0, 3); // print out first three most commons words. return bArray;}

Thank you for reading my Coding Journey ❀ ,

Kody the Coding Corgi & Bits the Adorable A.I.

P.S.

If you enjoyed this comic strip and could help you in any way, sign up for our newsletter, or buy me a coffee, which means a lot, and send your thoughts and feelings about this work.

Are you interested in collaborating? Follow us on LinkedIn.

D.M. us on Instagram or tweet us on Twitter or connect us on LinkedIn.

Please share this with your data friends, corgis friends, and coding corgis friends so we can make more comics in the future with your support. Thank You!

REFERENCES

MIT X PRO Professional Certificate in Coding: Full Stack Development with MERN

--

--

Code with Corgis
Code with Corgis

πŸ‘ We make CODING CUTE(β—•β€Ώβ—•βœΏ) and INFORMATIVEα•™(⇀‸↼•)α•—!