Software Dev Weekly Update #11: Modern JavaScript Features
Tags: javascript, webdev, beginners
Published: 2022-04-12 21:31:09

![block of code](https://i.imgur.com/LbdNyly.jpg)

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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach): 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.
```javascript
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
});
```

- [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/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.
```javascript
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;
})
```

- [Arrow Functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions): Allows us to write functions without having to use the keyword "function".

- [setTimeout](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout) and [setInterval](https://developer.mozilla.org/en-US/docs/Web/API/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.
```javascript
//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)
```

- [Filter Method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter): 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.
```javascript
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]
```

- [Some](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some) and [Every](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/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.
```javascript
[3, 5, 7, 9, 11].reduce((accumulator, currentValue) =>{
    return accumulator + currentValue;
});
//The final return value for this will be 35
```
---
##Topics From Section 23##

- [Default Params](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters): 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).
```javascript
//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;
}
```

- ["Spread" In Function Calls](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax): It's kind of like the swiss army knife of JavaScript. We are taking something and expanding or spreading" it out (array, string, etc).
```javascript
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)}`);
```

- ["Spread" With Array Literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax): Create a new array using an existing array. Spreads the elements from one array into another.
```javascript
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);
``` 

- ["Spread With Object Literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax): Copies properties from one object into another object. Often used when copying objects.
```javascript
//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}
```

- [Rest Params](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters): 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.
```javascript
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"));
}
```

- [Destructuring Arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment): A short, clean syntax to "unpack" values from arrays and properties from objects into distinct variables.
```javascript
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}`);
```

- [Destructing Objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment): 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.
```javascript
//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}!`);
```

- [Destructing Params](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment): Most frequently used with objects, we can destructure values that are being passed into the function.
```javascript
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}`;
}
```


##Week In Review##
![car driving through desert](https://i.imgur.com/FrqmiEa.jpg)
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](https://www.udemy.com/course/the-web-developer-bootcamp/) lessons completed: 244/579

---
I hope you enjoyed the read!

Feel free to follow me on [GitHub](https://github.com/RealNerdEthan), [LinkedIn](https://www.linkedin.com/in/ethan-goddard-a4376952/) and [DEV](https://dev.to/realnerdethan) for more!