DEV Community

Ethan Goddard
Ethan Goddard

Posted on

Software Dev Weekly Update #11: Modern JavaScript Features

block of code

This past week I wrapped up the pure JavaScript sections and began moving onto the world of DOM. Let's highlight those topics covered!


Topics From Section 22

These next few are all about built-in array methods that require us to pass in functions. It's a crucial part of working with arrays in JavaScript and arrays are crucial to working with JavaScript, so the topic is important.

  • For Each: Accepts a callback function. Calls the function once per element in an array. They are also older and there are times you could substitute these for newer syntax.
const numbers = [9, 8, 7, 6, 5, 4, 3, 2, 1];

//We are passing an in-line function, though we could define a
//function outside of the forEach and instead plug in the 
//function name
numbers.forEach(function(n){
    console.log(n * n)
    //Prints: 81, 64, 49, 36, 25, 16, 9, 4, 1
});
Enter fullscreen mode Exit fullscreen mode
  • Map: Creates a new array with the results of calling a callback on every element in the array. Works very much like forEach but then generates a new array based on the result.
const movies = [
    {
        title: "\"Toy Story\","
        score: 92
    },
    {
        title: "\"Stand By Me\","
        score: 85
    },
    {
        title: "\"Soul\","
        score: 95
    },
    {
        title: "\"Avengers: End Game\","
        score: 94
    },
    {
        title: "\"Finding Nemo\","
        score: 86
    },
];

//Creates a new array called "titles" pulling from the movies array
const titles = movies.map(function(movie){
    return movie.title;
})
Enter fullscreen mode Exit fullscreen mode
  • Arrow Functions: Allows us to write functions without having to use the keyword "function".

  • setTimeout and setInterval: Two functions that expect you to pass a callback function in, but are not array methods. They delay/postpone code execution for a
    later time.

//setTimeout-----------------------------------------------
//runs and prints 1st
console.log("Hello!")

//This will run just one time, and will print 3rd
setTimeout(function(){
    console.log("I waited 3 seconds...");
}, 3000)

//this runs 3rd but will print out 2nd because setTimeout is on a
//3 second delay
console.log("Last coded console.log message!")


//setInterval-----------------------------------------------
//Using an arrow function this time, doesn't matter but is shorter
//Will run forever every two seconds
//We set this to a variable so we can call clearInterval(id)
const id = setInterval(() =>{
    console.log(Math.random());
}, 2000)
Enter fullscreen mode Exit fullscreen mode
  • Filter Method: Creates a new array with all elements that pass the test implemented by the provided function. Typically we pass in a function that needs to return true or false and for any element that returns true it gets added into the new filtered array that is created.
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
const odds = numbers.filter(n => {
    return n % 2 === 1;
    //Our callback returns true or false, if true n is added to the filtered array
})
//Will return [1, 3, 5, 7, 9]

const smallNumbers = numbers.filter(n => n < 5);
//will return [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode
  • Some and Every: Some returns true if any of the array elements pass the test function. Every tests whether all elements in the array pass the test function, and if so will return true.

  • Reduce: Executes a reducer method function on each element of the array, resulting in a single value. This could be via math, but also could be via comparison of values which could be in an array or part of an object.

[3, 5, 7, 9, 11].reduce((accumulator, currentValue) =>{
    return accumulator + currentValue;
});
//The final return value for this will be 35
Enter fullscreen mode Exit fullscreen mode

Topics From Section 23

  • Default Params: When creating a function, it can optional to have a user input a value, and if they don't we cab use a default value (parameter).
//We've set this function's default params so that if the user
//doesn't input a value when calling rollDie() then it will
//use 6 as the default for numSides
function rollDie(numSides = 6){
    return Math.floor(Math.random() * numSides) +1;
}
Enter fullscreen mode Exit fullscreen mode
  • "Spread" In Function Calls: It's kind of like the swiss army knife of JavaScript. We are taking something and expanding or spreading" it out (array, string, etc).
const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];

//To use Math.max we need to "spread" the array of numbers into individual values so the function can find the maximum value
//We use ... before calling the nums array to "spread" the values inside the nums array
//Spread creates the seperate arguments (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15) from the nums array and then 
//executes the .max() function with those arguments
console.log(`The maximum number is: ${Math.max(...nums)}`);
Enter fullscreen mode Exit fullscreen mode
const cats = ["Ella", "Tommy", "Buddy"];
const dogs = ["Daisy", "Piston"];

//We are spreading the two arrays into a new array
const allPets = [...cats, ...dogs];
console.log(allPets);
Enter fullscreen mode Exit fullscreen mode
//A real world example, a user signs up for our website and we want to copy their input and add data of our own
const dataFromform = {
    email: "fake@gmail.com",
    username: "SirFaketon",
    password: "fakepassword123"
}

//Now lets add data to their input
const newUser = {...dataFromform, id: 12345, isAdmin: false}
Enter fullscreen mode Exit fullscreen mode
  • Rest Params: The syntax looks like spread but it's not, we're not spreading things out we are collecting them into a single parameter. Collects all remaining arguments not specifically called out into an actual array of their own.
function raceResults(gold, silver, ...everyoneElse){
    console.log(`Gold medal goes to: ${gold}`);
    console.log(`Silver medal goes to: ${silver}`);
    console.log(`And thanks to everyone else for participating: ${everyoneElse}`);

console.log(raceResults("Ethan", "Dan", "Tim", "Ashley"));
}
Enter fullscreen mode Exit fullscreen mode
  • Destructuring Arrays: A short, clean syntax to "unpack" values from arrays and properties from objects into distinct variables.
const pinballScores = [984537, 912385, 872357, 817490, 817245, 726349, 613279];

//With this we are making 3 variables (gold, silver, and bronze)
//and the order of the array determines what values they are
//Gold will be index 0, silver will be index 1, and bronze will be index 2
//The [] indicate we are destructing from an array
//Also we are using the ... or "rest" parameter to define the rest of the scores
const [gold, silver, bronze, ...everyoneElse] = pinballScores;

console.log(`Gold score is: ${gold}`);
console.log(`Silver score is: ${silver}`);
console.log(`Bronze score is: ${bronze}`);
console.log(`Runner up scores are: ${everyoneElse}`);
Enter fullscreen mode Exit fullscreen mode
  • Destructing Objects: Destructing is more commonly used with an object because it's not all about the order of the elements, but instead looks at their key value property. Example: {name: Ethan} instead of look for index 0 of an array. This doesn't change the original object in any way.
//An exmaple of destructing an object
const runner = {
    firstName: "Eliud",
    lastName: "Kipchoge",
    country: "Kenya",
    title: "Elder of the Order of the Golden Heart of Kenya"
}
const {firstName, lastName, country} = runner;

console.log(`The winner of the race is ${firstName} ${lastName} from ${country}!`);
Enter fullscreen mode Exit fullscreen mode
  • Destructing Params: Most frequently used with objects, we can destructure values that are being passed into the function.
const user1 = {
    email: "stacy@gmail.com",
    firstName: "Stacy",
    lastName: "LaPreaze",
    born: 1975,
    city: "Morley",
    state: "Michigan"
}

const user2 = {
    email: "george@gmail.com",
    firstName: "George",
    lastName: "Windfall",
    born: 1935,
    died: 1987,
    city: "Morley",
    state: "Michigan",
    occupation: "Systems Engineer"
}

//Destructure and only grab firstName and lastName. Also setting a
//default value (param) in case there's no info, but this is
//totally optional
function fullName({firstName = "Missing Value", lastName = "Missing Value"}){
    return `${firstName} ${lastName}`;
}
Enter fullscreen mode Exit fullscreen mode

Week In Review

car driving through desert
Well that was a lot of ground to cover in a week but I made great progress and am excited to finally begin to combine HTML/CSS/JavaScript into something usable. Next up is the world of the DOM!

Bootcamp lessons completed: 244/579


I hope you enjoyed the read!

Feel free to follow me on GitHub, LinkedIn and DEV for more!

Top comments (0)