rbi-learning / Today-I-Learned

1 stars 0 forks source link

10/21 Week 2 Day 3: JS Review #184

Open ajlee12 opened 4 years ago

ajlee12 commented 4 years ago

.forEach() method

This method works almost like a for loop and iterates over an element and visits every element once.

The method takes in a callback function as a required argument.

One parameter is required for the callback function, and it represents each element of the array that .forEach is processing.

Note that .forEach returns undefined, and it does not mutate (i.e. modify) the array that it was called upon.

const array1 = [0, 1, 2, 3, 4];

array1.forEach(function(elem) {
  console.log(elem * 2);
});

// We'll see '0, 2, 4, 6, 8' logged to the console.

// We can write the callback func. in the form of an arrow func. This will work exactly the same as above.
array1.forEach((elem) => {
  console.log(elem * 2);
});

.filter() method

The method takes in a callback function as a required argument.

One parameter is required for the callback function, and it represents each element of the array that .forEach is processing.

.filter returns a new array (you may want to save this new array in another variable/constant), and it does not mutate (i.e. modify) the array that it was called upon.

The returned array will have elements from the original that passed the conditional check you supplied in the callback function.

Let's say we're interested in only keeping the even numbers from this array.

const someArray = [1, 2, 3, 4, 5];

const evenNumArray = someArray.filter((number) => {
  return number % 2 === 0;
});

console.log(evenNumArray); // [2, 4]

Note that the conditional check is number % 2 === 0.

This means that only numbers from someArray that pass this check will remain in the new array that comes out of calling .filter on someArray.

.slice() method

Extracts the elements in an array from a start index and up to an end index, and output those elements in a new array.

The 2nd argument (the end index) is optional. If you don't supply a 2nd arg., .slice will extract to the end of the array by default.

Its output is a new array, so you may want to save the output in another variable/constant if you want to access it later.

Note that .slice does not mutate the original array it was called upon.

const referenceArray = [0, 1, 2, 3, 4];

// Extract elements from the 0th position up to (NOT including) the 3rd position.
const myArray1 = referenceArray.slice(0, 2);

// The method outputs a new array with the extracted elements.
// myArray1 => [0, 1]

// And note that the original array remains the same.
// referenceArray => [0, 1, 2, 3, 4]

// This basically copies the entire array.
const myArray2 = referenceArray.slice(0);

// myArray2 => [0, 1, 2, 3, 4] 

String.replace() method

You can replace a segment (or the entirety) of a string with another set of characters using this method.

Note that .replace return a new string; the original string isn't mutated.

const word1 = 'color';

// Look for any 'or' in 'color' and replace with 'our'.
const word2 = word1.replace('or', 'our');

console.log(word1); // 'color'
console.log(word2); // 'colour'

Implicit Return in Arrow Functions

This function...

const americanize = word => {
  return word.replace('our', 'or');
}

...can be re-written to...

const americanize = word => word.replace('our', 'or');

And they work exactly the same.

The 2nd one is a one-liner, so you can skip the return key word. Whatever that's to the to the right of the arrow will be returned.

Also note that you don't need the curly brackets in the 2nd example.

Emojis

An emoji has to be inside quotation marks. (They're treated as strings.)

Note that here we're returning a conditional check. Therefore, the output is either true or false.

function isChicken(emoji) {
  return emoji === '🐔' || emoji === '🍗';
}

Square Root of a Number

Check out the Math.sqrt() function.

Math.sqrt(3); // 9

return vs. console.log

A function returns undefined by default if you don't use the return keyword anywhere in it.

function noOutputs(num) {
  console.log(num + 1);
}

function hasAnOutput(num) {
  return num + 1;
}

noOutputs(3); // Output is `undefined`. But you'll see 4 printed to the console.
hasAnOutput(3); // Output is 4. But you won't see anything printed to the console.

console.log(noOutputs(3)); // 4 printed to the console, and `undefined`
console.log(hasAnOutput(3)); // 4 printed to the console

return lets you output a value from a function call, but it doesn't print that output by default.

console.logs are great for debugging, because they let you see the values/results.

Building a map/dictionary object

We can build a dict. object that allows us quick and easy look up of a corresponding value.

const cook = (emoji) => {
  const emojiMap = {
    '🐓': '🍗',
    '🥔': '🍟',
    '🌽': '🍿',
  };

  return emojiMap[emoji] || '🤷‍♀️';
}

For example, if the input is '🐓', we look up the value that corresponds to the key '🐓', and we get the value '🍗', which would be returned out.

console.log(cook('🥔')); // '🍟'

If the input doesn't exist in the object as a key, the lookup will evaluate to a falsy value, and '🤷‍♀️' will be returned instead.

return emojiMap[emoji] || '🤷‍♀️';

Accessing deeply nested data

Let's say we have this narly object:

const LukeData = {
  name: 'Luke Skywalker',
  height: 172,
  mass: 77,
  hair_color: 'blond',
  skin_color: 'fair',
  eye_color: 'blue',
  birth_year: '19BBY',
  gender: 'male',
  homeworld: {
    climate: "Arid",
    created: "2014-12-09T13:50:49.641000Z",
    diameter: "10465",
    edited: "2014-12-15T13:48:16.167217Z",
    films: [
        "https://swapi.dev/api/films/1/",
    ],
    gravity: "1",
    name: "Tatooine"
  },
  created: '2014-12-09T13:50:51.644000Z',
  edited: '2014-12-20T21:17:56.891000Z',
  url: 'https://swapi.dev/api/people/1/'
};

To get the name of the homeworld of Luke:

LukeData.homeworld.name; // "Tatooine"

To get the 1st element of the films array under homeworld:

LukeData.homeworld.films[0]; // "https://swapi.dev/api/films/1/"