JavaScript Fundamentals II
Table of Contents
Lesson Overview⌗
- Name the eight data types in JavaScript.
- number, for numbers of any kind integer or floating-point, integers are limited by ±(253-1).
- bigint, for integer numbers of arbitrary length.
- string, for strings.
- boolean, for true/false.
- null, for unkown values
- undefined, for unassigned values.
- symbol, for unique identifiers.
- object, for more complex data structures.
- Understand the difference between single, double and backtick quotes.
Not much difference between single and double quote, except when your string contains one of em, then you need to use the other
const sglDbl = 'Would you eat a "fish supper"?';
const dblSgl = "I'm feeling blue.";
console.log(sglDbl); // Would you eat a "fish supper"?
console.log(dblSgl); // I'm feeling blue.
// Using the same quote mark will confuse the browser and throw an error
// const bigmouth = 'I've got no right to take my place...';
As for backticks, it’s a newer way of creating strings is called a template literal. Template literals prevent the need for character escaping and allow for embedded expressions, also provide multi-line support.
- Embed a variable/expression in a string.
const poem = "The Wide Ocean";
const author = "Pablo Neruda";
const favePoem = `My favorite poem is ${poem} by ${author}.`;
- Understand what a method is.
Pre-built functionality into the language or into specific data types.
- Name the three logical operators.
&& (And), || (Or), ! (Not)
- Understand what the comparison operators are.
Operator that compares two values, returns (boolean) either true or false
- Understand what conditionals are.
A conditional is a statement you give to the computer, basically asking, ‘Do this if something’. Acting under a condition.
- Understand what nesting is.
Writting a conditional inside another conditional. It is perfectly OK to put one inside another one.
if (choice === 'sunny') {
if (temperature < 86) {
para.textContent = `It is ${temperature}
degrees outside -- nice and sunny. Let's go out to the beach,
or the park, and get an ice cream.`;
} else if (temperature >= 86) {
para.textContent = `It is ${temperature}
degrees outside -- REALLY HOT! If you want to go outside,
make sure to put some sunscreen on.`;
}
}
- Understand what thruthy and falsy values are.
truthy values are true, when something is truthy it means it isn’t falsy falsy values are false, when something is falsy it means it isn’t truthy
10 === 10; true; they are equal
10 === 100; false; they aren’t equal
String Manipulation⌗
Escaping characters in a string⌗
Escaping characters means that we do something to them to make sure they are recognized as text, not part of the code. In JavaScript, we do this by putting a backslash just before the character.
// const bigmouth = 'I've got no right to take my place...'; // wrong!
const bigmouth = 'I\'ve got no right to take my place...';
console.log(bigmouth);
Concatenating strings⌗
Concatenate just means “join together”. We can use a different type of string, called
template literal (string
)
const name = 'Chris';
const greeting = `Hello, ${name}`;
console.log(greeting); // "Hello, Chris"
You can also concatenate strings using the “+” operator:
const greeting = "Hello";
const name = "Chris";
console.log(greeting + ", " + name); // "Hello, Chris"
But template literals are more readable. When you concatenate numbers and strings together, the number will be converted into a string.
const name = "Front ";
const number = 242;
console.log(`${name}${number}`); // "Front 242"
Converting Strings into numbers⌗
- The “Number” object converts anything passed to it into a number, if it can.
const myString = '123';
const myNum = Number(myString);
console.log(typeof myNum);
- Conversely, every number has a method called “toString()” that converts it to the equivalent string.
const myNum2 = 123;
const myString2 = myNum2.toString();
console.log(typeof myString2);
Expressions in strings⌗
You can include JavaScript expressions in template literals, as well as simple variables, and then results will be included in the result:
const song = 'Fight the Youth';
const score = 9;
const highestScore = 10;
const ouput = `I like the song ${song}. I gave a score
of ${score/highestScore * 100}%.`;
console.log(output); // "I like the song Fight the Youth. I gave it a score of 90%."
Multi-line strings⌗
Template literals respect the line breaks in source code.
const output = `Ilike the song.
I gave it a score of 90%.`;
console.log(output); // I like the song.
// I gave it a score of 90%.
To have the equivalent using a normal string you’d have to include the line break (\n).
const ouput = 'I like the song. \nI gave it a score of 90%.';
console.log(output); // I like the song.
// I gave it a score of 90%.
Conditionals⌗
The “if” statement⌗
the if(…) statement evaluates a condition inside the parentheses and, if the result is true, executes a block of code.
let legs = prompt('How many legs does a dog have?');
if (legs == 4) alert( 'You are right!' );
// Optional, you can add something else to do if the if condition isn't satisfied
} else if (legs > 4) { // add else if, if you want another explicit condition
alert('Way too many legs')
} else { // only add else, if you want to do something else
alert( 'How can you be so wrong?' ); // anything but 4 and this will execute
}
Ternary operator⌗
“conditional” or “question mark” operator lets us do an if statement in a simpler way. The operator is represented by a question mark ‘?’. Sometimes called “ternary”, because the operator has three operands. It’s actually the only one in JavaScript which has that many.
let result = condition ? value1 : value2;
// the condition is evaluated if its truthy then value 1 is returned
// otherwise value2 is returned
let accessAllowed = (age > 18) ? true : false;
// Technically we can omit the parentheses around age > 18
// the question mark has a low precedence, so it executes after the comparison
// but parentheses make the code more readable.
Switch statement⌗
The switch statements works a lot like the if statement, it evaluates an expression against multiple cases and executes one or more blocks of code based on matching cases.
switch (expression) {
case x:
// execute case x code block
break;
case y:
// execute case y code block
break;
default:
// execute default code
}
This is the sequence of events:
- The expression is evaluated.
- The first case, x, will be tested against the expression. If it matches, the code will execute, and the break keyword will end the switch block.
- If it does not match, x will be skipped and the y case will be tested against the expression. If y matches the expression, the code will execute and exit out of the switch block.
- If none of the cases match, the default code block will run.
// Set the current day of the week to a variable, with 0 being Sunday and 6 being Saturday
const day = new Date().getDay();
switch (day) {
case 0:
console.log("It's Sunday, time to relax!");
break;
case 1:
console.log("Happy Monday!");
break;
case 2:
console.log("It's Tuesday. You got this!");
break;
case 3:
console.log("Hump day already!");
break;
case 4:
console.log("Just one more day 'til the weekend!");
break;
case 5:
console.log("Happy Friday!");
break;
case 6:
console.log("Have a wonderful Saturday!");
break;
default:
console.log("Something went horribly wrong...");
}
Switch Ranges⌗
If you need to evaluate a range of values in a switch block, as opposed to a single value as in the example above. We can do this by setting our expression to true and doing an operation within each case statement
// Set the student's grade
const grade = 87;
switch (true) {
// If score is 90 or greater
case grade >= 90:
console.log("A");
break;
// If score is 80 or greater
case grade >= 80:
console.log("B");
break;
// If score is 70 or greater
case grade >= 70:
console.log("C");
break;
// If score is 60 or greater
case grade >= 60:
console.log("D");
break;
// Anything 59 or below is failing
default:
console.log("F");
}
The expression in parentheses to be evaluated is true in this example. This means that any case that evaluates to true will be a match.
Multiple Cases⌗
If you need to have the same output for multiple cases, you can use more than one case for each block of code.
// Get number corresponding to the current month, with 0 being January and 11 being December
const month = new Date().getMonth();
switch (month) {
// January, February, March
case 0:
case 1:
case 2:
console.log("Winter");
break;
// April, May, June
case 3:
case 4:
case 5:
console.log("Spring");
break;
// July, August, September
case 6:
case 7:
case 8:
console.log("Summer");
break;
// October, November, December
case 9:
case 10:
case 11:
console.log("Autumn");
break;
default:
console.log("Something went wrong.");
}
Resources⌗
JavaScript String Method Lesson
Exhaustive List of Methods that can be used on Strings
Conditionals W3Schools tutorial