JavaScript Methods
A background in C++ makes this a lot less complicated, but JS methods take the following form:
thing.method(arg);
Some methods accept arguments arg that modify their behavior. Think of them as inputs
that we can pass in. We pass these arguments inside of the parentheses. Here follows some examples of
the above:
There are a huge number of string methods, and we'll be looking at a very small subset of them below. To look for more examples, try here
indexOf()
.indexOf('arg') returns the first matching instance of the argument. If no argument is found within our string, then -1 is returned!
let tvShow = 'catdog';
tvShow.indexOf('cat'); //Returns 0
tvShow.indexOf('dog'); //Returns 3
tvShow.indexOf('X'); //Returns -1
slice()
.slice() is used to extract a section of a string, returning it as a new string, without modifying the original string. For example, look at the following:
let example = 'Murphy, you are an elf. Uncontrollably...';
example.slice(0,5); //Murphy
example.slice(8,10); //you
example.slice(-4,-1); //y...
Notice how using a negative number makes things wrap around to the back of the string :)
replace()
This uses a regular expression (regex) to match patterns and replace patterns, not just specific strings.
let example2 = 'haha that is so funny!';
example2.replace('haha', 'lolololol'); //Will give us 'lolololol that is so funny!';
Note, however, that the method .replaceAll() isn't necessarily included in all modern
browsers.
Template Literals
These are new and extremely useful! Thye are strings that allow embedded expressions, which will be evaluated and then turned into a resulting string. For example:
`I counted ${3 + 4} sheep`;
As you can see in the above, we don't need to declare specific numbers. Just use ${ } In the above instance, one must use the BACKTICK character, `. If we use the special sequence (i.e. including the $ sign with the braces), within a pair of backticks, the sequence within the braces will be evaluated and returned as a string!
let qty = 5;
let product = artichoke;
let price = 2.25;
`You bought ${qty} ${produce}.
The total is $${price*qty}.
The Math Object
There are numerous methods that can be used on an object of type Math. The most common being used in the course is the random number generator, such as that generated when using Math.random()
To generate a random number between 1-10 in JavaScript:
- Use Math.random();
- Multiply the result by 10: i.e. Math.random()*10;
- Use Math.floor() on that result
- Overall, we can use Math.floor(Math.random()*10);
The following shows us how to generate a random number on a dice via JS:
// NO TOUCHING! (please)
const die1 = Math.floor(Math.random() * 6) + 1; //random number from 1-6
const die2 = Math.floor(Math.random() * 6) + 1; //random number from 1-6
let roll = `You rolled a ${die1} and ${die2}. They sum to ${die1+die2}`;
Equality in JavaScript
- == and !=:
- Checks for equality of value, but not equality of type.
- Coerces both values to the same type, and then compares them
- So, 9=='9' returns TRUE!
- === and !==:
- Checks for both equality of value and TYPE!
Spread Syntax
The spread syntax (...) allows an iterable, like an array or string, to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected.
In an object literal (think of a player with a name and FIFA rating), the spread syntax enumerates the properties of an object, and adds the key-value pairs to the object being created.
Spread in function calls
To find the maximum value of an element in an array, you might think that we can simply call it using the function Math.max(nums); However, that's mistaken! .max expects separate arguments, which is where the spread syntax helps! It spreads the array into separate arguments. You can think of it as removing the brackets away from the array
let nums = [13,6,4,7,2,1,92,3,52,51,56,63];
Math.max(...nums)
Another great example of the above is to use console.log with it. When we use the spread syntax, each element is passed as a separate argument. What's more, if we pass a string into console.log using spread syntax, then we'll get a very spaced-out Hello World!
let nums = [13,6,4,7,2,1,92,3,52,51,56,63];
console.log(nums); //Prints out the array, along with square brackets in the console
console.log(...nums); //Prints out EACH element.
string standard = 'Hello World!';
console.log(standard); //Prints out the string
console.log(...standard);
//Each character is processed individually, and printed out separated by a space
Spread with Array Literals
Spread allows us to spread an iterable array (such as cats dogs below) into a new
array. The spread operator is a great way to quickly and easily combine these.
const dogs = ['Eric','Molly','Ceilidh'];
const cats = ['Clint','Baby'];
const allPets = [...dogs, ...cats];
Spread with Object Literals
In objects literals, spread allows us to copy properties from one object into another object literal!
So, we can spread properties from an object into a new object!
const feline = {legs:4, family: 'Felidae'};
const canine = {isFurry:true, family:'Caninae'};
To make a new object using one of the above, we can make use of spread! e.g. {...feline, color:'black'};
It's also possible to combine the properties above into a new object: const catdog = {...feline, ...canine}; However, in the event of any conflicts, the LAST property added will take precedence. The canine family will take precedence in the catdog object
Finally, if we spread an array into an object, {...[2,4,6,8]}, the indices will be used as the keys, while the element itself will be the value
Why spread into objects? We do it often when creating copies of an object - rather than mutating them. For example, let's say we have this:
const dataFromForm = {
email:'hjsimpson@gmail.com',
password:'marge',
username:'maxPower'
}
const newUser = {...dataFromForm, id:2345, isAdmin:false}
As you can see from above, we can take the object above, and manipulate the copy slightly to add our own information to it. This is often done using things like React
Rest Parameters and The Arguments Object
The rest operator (also ...) is used to help collect the rest of the parameters in some list of arguments, collecting them all into one array.
It works differently to the spread syntax, except rather than spreading arguments, it automatically holds all arguments held in a function.
function print(...nums){
console.log(nums);
}
print(13,5,3,6,225,31,565);
//This will print out each element
function sum(...nums){
return nums.reduce((total,el) => total+el);
}
sum(13,5,3,6,225,31,565);
arguments is available inside (almost) every function. It's not available inside arrow functions! It's an array-like object with a length property, but no methods like (push/shift/pop). It contains ALL arguments passed to the function
function sumAll(){
let total = 0;
for(let i = 0; i < arguments.length; i++){
total+=arguments[i];
}
return total;
}
sumAll(8,4,2,5) //19
sumAll(2,3) //5
Destructuring
This is simply a short, clean syntax used to 'unpack' arrays, objects or parameters. It can extract values from arrays, properties from objects...and convert them into distinct variables.
For example, given a set of names, in order of 1-8, we can place these names into specific variables! In the example below, you probably already know how to do const gold = sprinters[0] etc...
However, look at the use of const[gold,silver,bronze,...everyoneElse] = sprinters;
let sprinters = ['Usain Bolt', 'Jesse Owens', 'Maurice Greene',
'Old Yelloweyes Ben Johnson', 'Carl Lewis The Cheat',
'Justin Juicer Gatlin', 'Trevor the Tortoise', 'Asafa Chokejob Powell'];
const[gold,silver,bronze,...everyoneElse] = sprinters;
Objects are commonly destructured in JavaScript.
For example, let's say we want to get the first and last names from this object:
const youZer = {
email: 'harvey@gmail.com',
password: 'sCoTt1948sMiTh',
firstName: 'Harvey',
lastName: 'Milk',
born: 1930,
died: 1978,
bio: 'Harvey Bernard Milk was an American politician',
city: 'San Francisco',
state: 'California'
}
Singling out specific variables using const firstName = user.firstName; gets annoying!
Essentially, we can use this: const{firstName} = youZer
That gives us the firstName!
Here's 5 separate variables that are COPIED from the object without changing the object youZer
const { email, firstName, lastName, city, bio } = youZer;
Renaming Destructured Object Properties
In the example above, we might prefer to use the variable name 'birthYear' to 'born'
To do so, this will work: const{born:birthYear} = user;
The above gets the born property out of the object (copying it), and renames it as birthYear, using born:birthYear
Let's look at these player objects again: here's how to use destructuring to output a player name, their team, and a rating. We want the format: Riyah Mahrez (Man City) has a rating of 83
const players = [
{
name:'Lionel Messi',
team:'PSG',
rating: 95
},
{
name:'Bukayo Saka',
team: 'Arsenal',
rating: 92
},
{
name:'Pedri',
team: 'Barcelona',
rating: 90
}
]
const newPES = players.map(({name,team,rating}) =>{
return `${name} (${team}) has a rating of ${rating}`;
});
Originally, this was done like so:
const oldPESRating = players.map(function(player){
return `${player.name} ($player.team}) has a rating of ${player.rating/10}`;
})