The logical or operator (||) returns true if either of the operands is true. Otherwise, it returns false (accomplish this without the operator)
Front
if (num > 10 || num < 5) {
return "No";
}
return "Yes";
Back
With JavaScript array variables, we can store several pieces of data in one place (show an example)
Front
var sandwich = ["peanut butter", "jelly", "bread"]
Back
Case switches (use an example of case switches) (Make sure the syntax is always correct)
Front
function caseInSwitch(val) {
var answer = "";
// Only change code below this line
switch (val) {
case 1:
return "alpha";
break;
case 2:
return "beta";
break;
case 3:
return "gamma";
break;
case 4:
return "delta"
break; }
// Only change code above this line
return answer;
}
// Change this value to test
caseInSwitch(1);
Back
Use bracket notation to find the first letter off "doody"
Front
Back
Comparison with the Less Than Or Equal To Operator
Front
The less than or equal to operator (<=) compares the values of two numbers. If the number to the left is less than or equal the number to the right, it returns true. If the number on the left is greater than the number on the right, it returns false. Like the equality operator, less than or equal to converts data types.
Back
Multiple Identical Options in Switch Statements (show an example)
Front
function sequentialSizes(val) {
var answer = "";
// Only change code below this line
switch (val) {
case 1:
case 2:
case 3:
return "Low";
break;
case 4:
case 5:
case 6:
return "Mid";
break;
case 7:
case 8:
case 9:
return "High";
}
Back
Logical Order in If Else Statements (What is the importance?)
Front
Order is important in if, else if statements.
The loop is executed from top to bottom so you will want to be careful of what statement comes first.
Back
Show an example of the strict inequality operator
Front
val !== val2
Back
Adding a default option in Switch statements
Front
It's like an else statement but just for switches.
function switchOfStuff(val) {
var answer = "";
// Only change code below this line
switch (val) {
case "a":
return "apple";
break;
case "b":
return "bird";
break;
case "c":
return "cat";
break;
default:
// Only change code above this line
return "stuff"; }
}
Back
.pop() is used to "pop" a value off of the end of an array. We can store this "popped off" value by assigning it to a variable.
Front
var oneDown = [1, 4, 6].pop();
the variable oneDown now holds the value 6 and the array becomes [1, 4].
Back
Arrays are mutable (what does this mean and show an example)
Front
// Setup
var myArray = [1,2,3];
// Only change code below this line.
myArray[0] = 3;
Back
Variables which are declared within a function, as well as the function parameters have local scope. That means, they are only visible within that function. (create a local scope example)
Front
function myTest() {
var loc = "foo";
console.log(loc);
}
myTest(); // "foo"
console.log(loc); // "undefined"
Back
Comparison with the Greater Than Operator
Front
The greater than operator (>) compares the values of two numbers. If the number to the left is greater than the number to the right, it returns true. Otherwise, it returns false.
Back
Comparison with the Inequality Operator
Front
The inequality operator (!=) is the opposite of the equality operator. It means "Not Equal" and returns false where equality would return true and vice versa. Like the equality operator, the inequality operator will convert data types of values while comparing.
Back
The value in using one or the other has to do with the need to escape quotes of the same type. Unless they are escaped, you cannot have more than one pair of whichever quote type begins a string.
Front
The output will yield what's expected of these code outputs
Back
Create a reassignment with a returned value using a function.
Front
var changed = 0;
function change(num) {
return (num + 5) / 3;
}
changed = change(10);
Back
What are the seven data types?
Front
undefined, null, boolean, string, symbol, number, and object
Back
This is also called a Multi-dimensional Array is also called a (Show an example too)
Front
nested array [["Bulls", 23], ["White Sox", 45]]
Back
Else is statement in JS are written as
Front
else if
Back
Passing Values to Functions with Arguments (Use parameters)
Front
function functionWithArgs(a, b) { console.log(a + b);}
functionWithArgs(5, 5);
Back
We can pass values into a function with arguments. You can use a return statement to send a value back out of a function.
Front
function plusThree(num) {
return num + 3;
}
var answer = plusThree(5); // 8
Back
Why does string[string.length - 1] give you the last letter of a string? (remember to put the variable on the outside as well)
Front
Because with bracket notation, and index starts with 0 therefore when you take the length - 1 you will get that character
Back
Show an example of float division (Javascript)
Front
var quotient = 4.4 / 2.0;
Back
Compound Assignment With Augmented Addition (what is that?)
Front
+=
Back
You can append string using the +=
Front
operator
Back
Whats the difference between an equality operator and a strict equality operator?
Front
3 === 3 // true
3 === '3' // false
The strict equality operator also enforces the same datatype
Back
A JavaScript engine
Front
A program or interpreter that understands and executes JavaScript code.
Synonyms: JavaScript interpreter, JavaScript implementation
Back
Understand String Immutability (what does it mean?)
Front
For example, the following code:
var myStr = "Bob";
myStr[0] = "J";
cannot change the value of myStr to "Job", because the contents of myStr cannot be altered. Note that this does not mean that myStr cannot be changed, just that the individual characters of a string literal cannot be changed. The only way to change myStr would be to assign it with a new string, like this:
var myStr = "Bob";
myStr = "Job";
Back
Compound Assignment With Augmented multiplication
Front
*=
Back
Compound Assignment With Augmented division
Front
/=
Back
In JavaScript, scope refers to the visibility of variables. Variables which are defined outside of a function block have Global scope. This means, they can be seen everywhere in your JavaScript code.
Variables which are used without the var keyword are automatically created in the global scope. This can create unintended consequences elsewhere in your code or when running a function again. You should always declare your variables with var.
Front
// Declare your variable here
var myGlobal = 10;
function fun1() {
// Assign 5 to oopsGlobal Here
oopsGlobal = 5;
}
// Only change code above this line
function fun2() {
var output = "";
if (typeof myGlobal != "undefined") {
output += "myGlobal: " + myGlobal;
}
if (typeof oopsGlobal != "undefined") {
output += " oopsGlobal: " + oopsGlobal;
}
console.log(output);
}
Back
.shift() what does it do? (show an example)
Front
Back
When variables are declared, they have an initial value of undefined
Front
if you do a mathematical operation on an undefined variable your result will be NaN which means "Not a Number". If you concatenate a string with an undefined variable, you will get a literal string of "undefined".
Back
You can have both global and local scope with the same names (show an example)
Front
var someVar = "Hat";
function myFun() {
var someVar = "Head";
return someVar;
}
Back
.push() takes one or more parameters and "pushes" them onto the end of the array.
Front
var arr = [1,2,3];
arr.push(4);
// arr is now [1,2,3,4]
Back
One way to think of a multi-dimensional array, is as an array of arrays. When you use brackets to access your array, the first set of brackets refers to the entries in the outer-most (the first level) array, and each additional pair of brackets refers to the next level of entries inside.
numbers, letters, $ or _
no spaces and can't start with a number.
Back
You can also access array using indexing (create and array and access a part of it?)
Front
var ourArray = [1,2,3];
var ourData = ourArray[0];
Back
Comparison with the Equality Operator (show and example)
Front
function equalityTest(myVal) {
if (myVal == 10) {
return "Equal";
}
return "Not Equal";
}
Back
.unshift() works exactly like .push(), but instead of adding the element at the end of the array, unshift() adds the element at the beginning of the array.
Front
Back
Compound Assignment With Augmented Subtraction
Front
-=
Back
The remainder operator % gives the remainder of the division of two numbers. (remainder is not modulus in this case) (modulus acts funny with negative numbers)
Front
17 % 2 = 1 (17 is Odd)
48 % 2 = 0 (48 is Even)
Back
.length
Front
is a property to find the amount of characters
Back
Sometimes you will need to test more than one thing at a time. The logical and operator (&&) returns true if and only if the operands to the left and right of it are true.
Front
ex1
if (num > 5) {
if (num < 10) {
return "Yes";
}
}
return "No";
ex2
if (num > 5 && num < 10) {
return "Yes";
}
return "No";
Back
Show an example of an if statement
Front
function test (myCondition) {
if (myCondition) {
return "It was true";
}
return "It was false";
}
test(true); // returns "It was true"
test(false); // returns "It was false"
Back
Comparison with the Greater Than Or Equal To Operator
Front
The greater than or equal to operator (>=) compares the values of two numbers. If the number to the left is greater than or equal to the number to the right, it returns true. Otherwise, it returns false.
Back
Comparison with the Less Than Operator
Front
The less than operator (<) compares the values of two numbers. If the number to the left is less than the number to the right, it returns true. Otherwise, it returns false. Like the equality operator, less than operator converts data types while comparing.
Back
In JavaScript, we can divide up our code into reusable parts called functions. You can call or invoke this function by using its name followed by parentheses, like this:
Front
function functionName() {
console.log("Hello World");
}
Back
booleans
Front
true false
Back
Section 2
(50 cards)
Define Null
Front
is the absence of a value. It is an assignment value that can be assigned to a variable as a representation of 'no-value'.
Back
To add properties to an object
Front
//you've got to pretend it's there
var myDog = {
"name": "Happy Coder",
"legs": 4,
"tails": 1,
"friends": ["Free Code Camp Campers"]
};
// Only change code below this line.
myDog.bark = "woof";
Sort Arrays with sort (sort will actually alter the array);
Front
Unlike the previous array methods we have been looking at, sort actually alters the array in place. However, it also returns this sorted array.
sort can be passed a compare function as a callback. The compare function should return a negative number if a should be before b, a positive number if a should be after b, or 0 if they are equal.
If no compare (callback) function is passed in, it will convert the values to strings and sort alphabetically.
Here is an example of using sort with a compare function that will sort the elements from smallest to largest number:
var array = [1, 12, 21, 2];
array.sort(function(a, b) {
return a - b;
});
Back
Greeting
Define a function greeting that accepts an optional string argument called name. greeting should return a personalized string if the name is present. (Show three ways to solve this)
Front
function greeting(name){
if(typeof name === 'string' ) {console.log("Hello " + name); }
else{
console.log("Hello!");
}
}
greeting("Rico");
// solve using a truthy value
https://www.youtube.com/watch?time_continue=160&v=FWpUbEjMubk
Back
Math.floor() JS
Front
will round down to the nearest whole number
Back
hasOwnProperty()
Front
Is a method that checks at a certain property is contained
Back
We can also create private properties and private methods, which
Front
aren't accessible from outside the object.
To do this, we create the variable inside the constructor using the var keyword we're familiar with, instead of creating it as a property of this.var Car = function() {
// this is a private variable
var speed = 10;
// these are public methods
this.accelerate = function(change) {
speed += change;
};
this.decelerate = function() {
speed -= 5;
};
this.getSpeed = function() {
return speed;
};
};
var myCar = new Car();
Back
Create a profile lookup Method uusing hasOwnProperty method
Front
for (var x = 0; x < contacts.length; x++){
if (contacts[x].firstName === firstName) {
if (contacts[x].hasOwnProperty(prop)) {
return contacts[x][prop];
} else {
return "No such property";
}
}
}
return "No such contact";
Back
Last Character
Define a function lastCharacter that accepts two strings as arguments. lastCharacter should return true if both strings end with the same character. Otherwise, lastCharacter should return false. (solve using the slice method and the .length method )
Front
function lastCharacter(val1, val2){
if (val1.slice(-1) === val2.slice(-1)){
return true; }
else { return false;}
}
\d which is used to retrieve one digit (e.g. numbers 0 to 9) in a string.
In JavaScript, it is used like this: /\d/g.
Appending a plus sign (+) after the selector, e.g. /\d+/g, allows this regular expression to match one or more digits.
The trailing g is short for 'global', which allows this regular expression to find all matches rather than stop at the first match.
// Setup
var testString = "There are 3 cats but 4 dogs.";
// Only change code below this line.
var expression = /\d+/g; // Change this line
// Only change code above this line
// This code counts the matches of expression in testString
var digitCount = testString.match(expression).length;
Back
slice method descibe what it does.
Front
slice method will take an specific index and cut froma beginnig to end. (two parameters may be needed at times) is -1 indexed also
There are two ways to access the properties of an object: the dot operator (.) and bracket notation ([]), similar to an array.
The dot operator is what you use when you know the name of the property you're trying to access ahead of time. (create an object and access some shit using the dot operator
Front
var myObj = {
prop1: "val1",
prop2: "val2"
};
var prop1val = myObj.prop1; // val1
var prop2val = myObj.prop2; // val2
Back
What does the split method do?
Front
You can use the split method to split a string into an array.
split uses the argument you pass in as a delimiter to determine which points the string should be split at.
Here is an example of split being used to split a string at every s character:
var array = string.split('s');
Returning Boolean Values from Functions (what does this mean? )
Front
Don't tell the thing to return true or false just put the damn thing
Back
Find Whitespace with Regular Expressions
Front
// Setup
var testString = "How many spaces are there in this sentence?";
// Only change code below this line.
var expression = /\s+/g; // Change this line
// Only change code above this line
// This code counts the matches of expression in testString
var spaceCount = testString.match(expression).length;
Back
Math.random() //javascript (test out an example)
Front
function that generates a random decimal number between 0 (inclusive) and not quite up to 1 (exclusive). Thus Math.random() can return a 0 but never quite return a 1
Back
Make Unique Objects by Passing Parameters to our Constructor (java script)
Front
var Car = function(wheels, seats, engines) {
//Change this constructor
this.wheels = wheels;
this.seats = seats;
this.engines = engines;
};
//Try it out here
var myCar = new Car(7, 1, 8);
Back
alert()
Front
built in function makes a pop-up box appear inside the browser window, but we need to give it a string as an argument to tell the function what to write in the pop-up box.
Back
A constructor function is given a capitalized name
Front
to make it clear that it is an constructor
Back
JSON
Front
JavaScript Object Notation
Back
Regular expressions (what are they and show you how it's done)
Front
are used to find certain words or patterns inside of strings.
// Setup
var testString = "Ada Lovelace and Charles Babbage designed the first computer and the software that would have run on it.";
// Example
var expressionToGetSoftware = /software/gi;
var softwareCount = testString.match(expressionToGetSoftware).length;
Back
The map method is a convenient way to iterate through arrays. Here's an example usage:
Front
var oldArray = [1, 2, 3];
var timesFour = oldArray.map(function(val){
return val * 4;
});
console.log(timesFour); // returns [4, 8, 12]
console.log(oldArray); // returns [1, 2, 3]
Back
Accessing Objects Properties with Variables (JS)
Another use of bracket notation on objects is to use a variable to access a property. This can be very useful for iterating through lists of the object properties or for doing the lookup.
Front
var myDog = "Hunter";
var dogs = {
Fido: "Mutt",
Hunter: "Doberman",
Snoopie: "Beagle"
}
var breed = dogs[myDog];
console.log(breed);// "Doberman"
Note that we do not use quotes around the variable name when using it to access the property because we are using the value of the variable, not the name
Back
To use a constructor function
Front
we call it with the new keyword in front of it like: var myCar = new Car();
Back
Using Objects for Lookups (show and example and give a verbal explanation)
Front
// Setup
function phoneticLookup(val) {
var result = "";
// Only change code below this line
var lookup = {
"alpha":"Adams",
"bravo":"Boston",
"charlie":"Chicago",
"delta":"Denver",
"echo":"Easy",
"foxtrot":"Frank"
};
return lookup[val];
// Only change code above this line
return result;
}
// Change this value to test
phoneticLookup("charlie");
//Explanation The function phoneticLookup is set where val will be your input variable.
2. you declare result as an empty string.
3. Create your object
4. set val as an index for object. and set to result
Return result
Back
Concatenate Arrays with concat
Front
concat takes an array as an argument and returns a new array with the elements of this array concatenated onto the end.
Back
Invert Regular Expression Matches with JavaScript
(show how )
Front
// Setup
var testString = "How many non-space characters are there in this sentence?";
// Only change code below this line.
var expression = /\S/g; // Change this line
// Only change code above this line
// This code counts the matches of expression in testString
var nonSpaceCount = testString.match(expression).length;
Back
The second way to access the properties of an object is bracket notation ([]). If the property of the object you are trying to access has a space in it, you will need to use bracket notation.
Here is a sample of using bracket notation to read an object property
will take a whole array and give you the ability to create and manipulate a new array.
Back
Create an array from 1 to 4 using a while loop
Front
var myArray = [];
var i = 0;
while (i < 5) {
myArray.push(i);
i++;
}
Back
Use filter to create a new array with all the values from oldArray which are less than 6. The oldArray should not change.
Front
var oldArray = [1,2,3,4,5,6,7,8,9,10];
var newArray = oldArray.filter(function(val){
return val < 6;
});
Back
document.querySelector
Front
built in function that allows you to select HTML elements?
Back
Define Undefined
Front
is the absence of a definition. It is used as the default value for uninitialized variables, function arguments that were not provided and missing properties of objects. Functions return undefined when nothing has been explicitly returned. (It means that whatever you program returns nothing).
Back
Scoping what is it?
Front
variables will reset inside a function. If you don't put return, when you call upon that function you will not get the desired result.
When using the sort method especially with multiple digit number you need a comparison funtion
Front
array.sort(function(a,b) {
return b - a;
});
Back
Reverse Method.
Front
will revese and modify an array
Back
In a constructor the this variable refers
Front
to the new object being created by the constructor. So when we write,
this.wheels = 4;
Back
Objects have their own attributes, called
Front
properties, and their own functions, called methods.
Back
Block statements are commonly used with control flow statements (e.g. if, for, while).
Front
while (x < 10) {
x++;
}
Back
typeof keyword
Front
can specify what type of datatype your variable will be.
Back
Accessing Nested Objects
Front
Remember when accessing nested objects, you can use dot notation but if a key has a space in between to use bracket notation.
ie. myStorage.car.inside["glove box"];
Back
Javascript template literal
Front
${} will call upon javascript directly
Back
Show an example of updating a property of a variable.
Front
var myDog = {
"name": "Coder",
"legs": 4,
"tails": 1,
"friends": ["Free Code Camp Campers"]
};
// Only change code below this line.
myDog.name = "Happy Coder";
Back
Condense arrays with reduce (show an example)
Front
var array = [4,5,6,7,8];
var singleVal = 0;
var singleVal = array.reduce(function(previousVal, currentVal) {
return previousVal + currentVal; }, 0);
Back
The array method reduce is used to iterate through an array and condense it into one value.
It will work with the previous value and current value and at the end will render a result based on what your function is.
The browser, not the JavaScript language provides an object called
Front
firefox started with it but then changed it uo
Back
in JS
Front
strings are falsy
Back
You cannot compare arrays using the equality sign
Front
they are objects. you need to convert them in order to do such a comaparison
Back
What does the chartAt method do in JS?
Front
done
Back
when should you use the var variable
Front
NEVER
Back
In JavaScript, variables become global when they aren't declared with the
Front
they aren't declared with the var keyword.
Back
let pi = 3.14159;
//=> undefined
pi = "the ratio between a circle's circumference and diameter";
//=> "the ratio between a circle's circumference and diameter"
typeof pi;
//=> "string"
Front
let pi = 3.14159;
//=> undefined
let pi = "the ratio between a circle's circumference and diameter";
//=> Uncaught SyntaxError: Identifier 'pi' has already been declared
let variable will let you reassign but nit re declare
Back
Uncaught ReferenceError: _____ is not defined
Front
This is one of the simplest and most common errors, and it's pretty explicitly telling us what went wrong. We tried to reference a variable or function that doesn't exist in the current scope (or in the scope chain)! For example:
Back
Is foo global?
function global(){
foo = "bar"
}
Front
Nope! It is tied to that scope.
Back
Top Tip: If a variable or function is not declared inside a function or block
Front
it's in the global execution context.
Back
Variables declared with var are not block-scoped:
Front
if (true) {
var myVar = 42;
}
myVar;
// => 42
Back
What will a return statement do within a function?
Front
It will break out of the function. So
Back
Variables created without a const, let, or var keyword are always globally-scoped, regardless of where they sit in your code. If you create one inside of a block, it's still available globally:
Front
done
Back
Show an example of a shadowy variable
Front
var animal = 'dog';
function makeZoo() {
var animal = 'cat';
console.log(`I think I'll put this ${animal} in the zoo.`);
}
makeZoo(); // "I think I'll put this cat in the zoo."
animal // "dog"
Back
Join Strings with join (show an example)
Front
We can use the join method to join each element of an array into a string separated by whatever delimiter you provide as an argument.
Back
There are three different ways the && operator can be evaluated:
Front
eft side Right side Return value Truthiness of return value
Falsy Doesn't matter Left side Falsy
Truthy Falsy Right side Falsy
Truthy Truthy Right side Truthy
Calling a function can make nonglobal variable global. show an example
Front
//Example 1
var x = 1;
function myFunction(){
y = 2;
console.log(x);
}
console.log(y); // Error!
console.log(x); // 1
//Example 2
var x = 1;
function myFunction(){
y = 2;
console.log(x);
}
myFunction(); // 1
console.log(y); // 2
console.log(x); // 1
Back
parseFloat()
Front
preserves a decimal
Back
const myVar = 'Foo';
function first () {
console.log('Inside first()');
console.log('myVar is currently equal to:', myVar);
}
function second () {
const myVar = 'Bar';
first();
}
which myVar will be called?
Front
Foo
Back
MULTI-LINE VARIABLE ASSIGNMENT is allowed
Front
i didnt know that
var a = 1
b=2
c=3
Back
What method could you use to convert a string in to an integer in your DOM?
Front
parseInt()
Back
#===
function add(first, second){
return first + second;
}
function calculate(number1, number2, calculationFunction){
return calculationFunction(number1, number2)
}
calculate(5, 5, add); // 10
#===
function calculate(number1, number2, calculationFunction){
return calculationFunction(number1, number2)
}
calculate(5, 5, function(first, second){
return first + second;
}); // 10
Front
explain this
Back
Scope chain (JS)
Front
means that any variable or function on the outside is available on the inside
Back
THE KEY TO SCOPE
To determine a variable's scope in JavaScript, ask yourself two questions:
Front
1. Is it declared inside a function?
2. Is it declared with the `var` keyword?
Back
The diffenece between ++i and i+++ is how
Front
they are evaluation after.
So they both will increment a value, but they key difference is at what point that increment applied.
With ++i, the value is incremented, then evaluated. So if i was 1, it would be evaluated as 2. With i++, if i was 1, it would be evaluated as 1, but then stored as 2. These statements both seem to mean the same thing, well, they do, if the expressions are used in a standalone fashion as above. However, it's when they're used as part of a larger statement, do the differences shine through.
Back
Show multiple examples of the .slice() method
Front
done
Back
is foo global?
function global(){
var foo = "bar"
}
Front
yep
Back
replace method in JS (show us an example)
Front
.replace(arg1, arg2)
Back
JavaScript evaluates compound arithmetic operations by following the familiar order of operations that's taught in grade school math classes. Anything in parentheses has highest priority; exponentiation is second; then multiplication, division, and remainder; and, finally, addition and subtraction.
Front
is that so?
Back
How would you access another js file in your current js file?
Front
var index = require("./index.js")
Back
Uncaught TypeError: _____ is not a function
Front
This one usually indicates that you tried to invoke something that isn't actually a function. For example:
const myVar = 'Hello, world!';
myVar();
// ERROR: Uncaught TypeError: myVar is not a function
Back
Tracing is
Front
using output statements (like console.log()) to provide feedback about "what the machine is thinking." Oftentimes we request our code to behave like a machine, or like a process...
const myVar = 'Foo';
function second () {
function first () {
console.log('Inside first()');
console.log('myVar is currently equal to:', myVar);
}
const myVar = 'Bar';
first();
}
which mvVar will be called
will check if a number is an integer
Number.isInteger(42);
//=> true
Number.isInteger(0.42);
//=> false
Back
Variables declared with var are only available within that function's scope.
Front
Variables declared without var attach themselves to the global object.
Back
NaN
Front
is like undefined for numbers
Back
Number.parseFloat()
Front
Number.parseFloat() only accepts a single argument, the string that should be parsed into a floating-point number:
Back
Show an example fo a global variable. That is within a function
Front
function speaker() {
sentence = 'Bird is the word.';
}
speaker();
console.log(sentence);
Back
const and let are block-scoped:
Front
if (true) {
const myVar = 42;
let myOtherVar = 9001;
}
myVar;
// Uncaught ReferenceError: myVar is not defined
myOtherVar;
// Uncaught ReferenceError: myOtherVar is not defined
Back
Convert a string into an array
Front
done
Back
Lexical scoping means
Front
that functions will seek out variables from the parent first
Back
The Number object comes with a collection of handy methods that we can use for checking and converting numbers in JavaScript.
(show a couple of examples)
Front
done
Back
console.warn()
Front
same as console.log but yellow
Back
with const
Front
you cannot reassign or redeclare
Back
Section 4
(50 cards)
What is the major difference btwn splice and slice
Front
slice arguments are startinf index and ending index
splice is starting index and how manf positions after that
Back
document.querySelector()
Front
Returns the first Element within the document that matches the specified selector, or group of selectors, or null if no matches are found.
Back
return all the nodes in your browser console
Front
document.all;
Back
How to get access to the dom
Front
type document in the console
Back
returns the type of content contained. Most web pages should return "text/html" in your console
Front
document.contentType;
Back
We can update or overwrite existing properties by assigning a new value to an existing key:
With Nonstandard Keys
const wildKeys = {
'Cash rules everything around me.': 'Wu',
'C.R.E.A.M.': 'Tang',
'Get the money.': 'For',
"$ $ bill, y'all!": 'Ever'
};
Front
Back
Storing functions in an array
We can store functions as elements in an array:
Front
const arrayOfObjects = [
{ name: 'Sandi Metz' },
{ name: 'Anita Borg' },
{ name: 'Ada Lovelace' }
];
const arrayOfFunctions = [
function () { console.log('Functions'); },
function () { console.log('are'); },
function () { console.log('so'); },
function () { console.log('cool!'); }
];
you can invoke an function by calling the index with the invocation operator ()
Back
In JS Arrays are just objects
Front
but key values are not easily accessible through index
Back
select all p tags
Front
document.querySelectorAll('p');
Back
We can select a specific piece of the DOM by using JavaScript, such as
Front
document.querySelector('header'), and we can also use JavaScript to alter our DOM with document.querySelector('header').remove()
wildKeys["$ $ bill, y'all!"];
// => "Ever"
dot notation does not work when strings are keys
Back
We aren't required to remove anything with .splice() — we can use it to insert elements anywhere within an Array. Here we're adding new books to our library in alphabetical order:
you add arguments to it
With Arguments
We can provide two arguments to .slice(), the index where the slice should begin and the index before which it should end:
const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
days.slice(2, 5);
// => ["Wed", "Thu", "Fri"]
IT WILL NEVER MUTATE THE ARRAY
Back
using let and const helps you avoid hoisting issues
Front
it will raise errors
Back
Slicing and Spreading
Front
Combining .slice() and the spread operator allows us to replace elements nondestructively, leaving the original Array unharmed:
const menu = ['Jalapeno Poppers', 'Cheeseburger', 'Fish and Chips', 'French Fries', 'Onion Rings'];
const newMenu = [...menu.slice(0, 1), 'Veggie Burger', 'House Salad', 'Teriyaki Tofu', ...menu.slice(3)];
menu;
// => ["Jalapeno Poppers", "Cheeseburger", "Fish and Chips", "French Fries", "Onion Rings"]
newMenu;
// => ["Jalapeno Poppers", "Veggie Burger", "House Salad", "Teriyaki Tofu", "French Fries", "Onion Rings"]
Back
whenever you store a function in an object
Front
it is called a method
Back
const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
use.splice on this JS
Functions are objects
In JavaScript, functions are what's known as first-class citizens of the language. That means functions have the following four abilities:
Front
A function can be assigned to a variable.
A function can be stored in a data structure.
A function can be the return value of another function.
A function can be passed as an argument to another function.
Back
innerText
Front
will change the text only
Back
<p id="corgi">This paragraph is silly </p>
change the text
Front
pTag.textContent
"This paragraph is silly"
pTag.textContent = "It is not silly"
Back
you don't have to name a function if you name it to a variable
Front
let func = function () {};
Back
Remove a Property from an Object
Uh oh, we ran out of Southwestern dressing, so we have to take the salad off the menu. In JavaScript, that's as easy as:
const wednesdayMenu = {
cheesePlate: {
soft: 'Brie',
semiSoft: 'Fontina',
hard: 'Manchego'
},
fries: 'Sweet potato',
salad: 'Southwestern'
};
show how its done
ES2015 introduced the spread operator, which looks like an ellipsis: .... The spread operator allows us to spread out the contents of an existing Array into a new Array, adding new elements but preserving the original:
const coolCities = ['New York', 'San Francisco'];
const allCities = ['Los Angeles', ...coolCities];
coolCities;
// => ["New York", "San Francisco"]
allCities;
// => ["Los Angeles", "New York", "San Francisco"]
Back
const cards = ['Ace of Spades', 'Jack of Clubs', 'Nine of Clubs', 'Nine of Diamonds', 'Three of Hearts'];
cards.splice(2, 1, 'Ace of Clubs');
what happens here
Front
cards;
// => ["Ace of Spades", "Jack of Clubs", "Ace of Clubs", "Nine of Diamonds", "Three of Hearts"]
The window object has a large number of properties that return information about the object. Below are a few examples
Front
window.document;
//returns the entire HTML document
window.innerWidth;
// returns the inner width of the browser window. Open a console in the browser and enter this. Then shrink the browser window and run it again. You should get a different value.
window.innerHeight;
// returns the inner height of the browser window.
Back
document.querySelectorAll()
Front
Returns all that is matching in the parentheses. Returns something like an array
Back
In JS negative indices only work in
Front
splice and slice
Back
returns the URL of the document object in your console
Front
document.URL;
Back
Add a Property to an Object
To add properties to an Object, we can use either dot notation or bracket notation:
<div>
<h5 id="greeting">Hello!</h5>
</div>
how would you access the greeting?
Front
document.getElementById()
Back
Important rules for array object properties
Front
1 For accessing elements in an Array, always use integers.
2 Be wary of setting Object-style properties on an Array. There's rarely any reason to, and it's usually more trouble than it's worth.
3 Remember that all Object keys, including Array indexes, are strings. This will really come into play when we learn how to iterate over Objects, so keep it in the back of your mind.
Back
<!-- the `className` attribute is called `class` in HTML -- it's a bummer -->
<div>
<div class="banner">
<h1>Hello!</h1>
</div>
<div class="banner">
<h1>Sup?</h1>
</div>
<div class="banner">
<h5>Tinier heading</h5>
</div>
</div>
access these classes
Front
document.getElementsByClassName()
Back
if myArray contains 10 elements, the final element will be at myArray[9]. If myArray contains 15000 elements, the final element will be at myArray[14999]. So the index of the final element is always one less than the number of elements in the Array. If only we had an easy way to figure out how many elements are in the Array...
JavaScript provides us access to a global Object Object that has a bunch of helpful methods we can use. One of those methods is Object.assign(), which allows us to combine properties from multiple Objects into a single Object. The first argument passed to Object.assign() is the initial Object in which all of the properties are merged. Every additional argument is an Object whose properties we want to merge into the first Object:
1. Object.assign(initialObject, additionalObject, additionalObject, ...);
//
Object.assign({ eggs: 3 }, { flour: '1 cup' });
// => { eggs: 3, flour: "1 cup" }
Object.assign({ eggs: 3 }, { chocolateChips: '1 cup', flour: '2 cups' }, { flour: '1/2 cup' });
// { eggs: 3, chocolateChips: "1 cup", flour: "1/2 cup" }
Back
Statements vs. expressions
what is the difference?
Front
A statement is a unit of code that accomplishes something but does not produce a value. An expression is a unit of code that produces a value
Back
Then, with the ES2015 spread operator, we can copy all of the old menu Object's properties into a new Object:
Front
function nondestructivelyUpdateObject(obj, key, value) {
const newObj = { ...obj };
// Code to return new, updated menu object
}
Back
document.getElementById()
Front
Returns the element that has the ID attribute with the specified value
Back
Section 5
(39 cards)
Number.parseFloat()
Front
Number.parseFloat() only accepts a single argument, the string that should be parsed into a floating-point number:
Number.parseFloat('3.14159');
//=> 3.14159
The XMLHttpRequest object, or XHR, is a JavaScript API that allows us to transfer data between a client and a server.
It was named at a time when XML was all the rage, but it can be used with any type of data, including JSON, which is the current de facto standard.
XHR helps us write dynamic programs by allowing us to fetch data from a server based on user events, and update parts of pages without requiring a full-page refresh. This provides users with a smooth, engaging experience that doesn't require them to stop what they're doing to get new information.
in other words, you retrieve what you want. Instead of retrieving all that bs
var ul = document.createElement('ul');
for (let i = 0; i < 3; i++) {
let li = document.createElement('li');
li.innerHTML = (i + 1).toString();
ul.appendChild(li);
}
element.appendChild(ul);
Back
JavaScript provides three methods for rounding numbers. Math.ceil() rounds the number up, Math.floor() rounds the number down, and Math.round() rounds the number either up or down, whichever is nearest:
The for...in statement has been around for a long time, and it's usually used for iterating over the properties in an object. The statement follows this syntax:
show an example
Front
for (const <KEY> in <OBJECT>) {
// Code in the statement body
}
const address = {
street1: '11 Broadway',
street2: '2nd Floor',
city: 'New York',
state: 'NY',
zipCode: 10004
};
for (const key in address) {
console.log(key);
}
// LOG: street1
// LOG: street2
// LOG: city
// LOG: state
// LOG: zipCode
for (const key in address) {
console.log(address[key]);
}
// LOG: 11 Broadway
// LOG: 2nd Floor
// LOG: New York
// LOG: NY
// LOG: 10004
Closure examples make attributes private as opposed to class objects
Back
In combination with some simple arithmetic and one of the rounding methods, we can generate random integers within a specific range. For example, to generate a random integer between 1 and 10:
Show an example of you stopping an event propagation
Front
const divs = document.querySelectorAll('div');
function bubble(e) {
// stop! that! propagation!
e.stopPropagation();
console.log(this.firstChild.nodeValue.trim() + ' bubbled');
}
for (let i = 0; i < divs.length; i++) {
divs[i].addEventListener('click', bubble);
}
Back
use for of loop on "Hello World!"
Front
for (const char of 'Hello, world!') {
console.log(char);
}
// LOG: H
// LOG: e
// LOG: l
// LOG: l
// LOG: o
// LOG: ,
// LOG:
// LOG: w
// LOG: o
// LOG: r
// LOG: l
// LOG: d
// LOG: !
Back
create a function that makes a new object in JS
Front
function User(name, age, hometown) {
this.name = name
this.age = age
this.hometown = hometown
}
let bobby = new User('bobby', 20, 'Philadelphia')
// {name: 'bobby', age: 20, hometown: 'Philadelphia'}
let fidoDido = new User('sally', 28, 'Boston')
// {name: 'sally', age: 28, hometown: 'Boston'}
the this keyword makes a new function.
Back
Callback functions do not
Front
do not get invoked
Back
all event bubble
Front
meaning that all event will propagate to the root node
Back
arrow function you cannot reassign
Front
let someVariable = () => {return this }
this is an anonymous function
Back
toUpperCase()
Front
var str = "Hello World!";
var res = str.toUpperCase();
Back
fetch('url')
Front
return response.json (you still need to go to another level)
Back
Create a JS ITEM class
Front
function createItem() {
let ItemId = 0;
// return the class
return class {
constructor(name, manufacturePrice) {
this.name = name;
this.manufacturePrice = manufacturePrice;
this.id = ++ItemId;
}
retailPrice(marketMultiplier) {
return marketMultiplier * this.manufacturePrice;
}
};
}
const Item = createItem();
// Execute createItem and assign the returned class to equal Item.
// We only need to call createItem() one time in our codebase.
let tennisShoe = new Item("tennis shoe", 15);
// {id: 1, name: 'tennis shoe', manufacturePrice: 15}
let tshirt = new Item("t shirt", 8);
// {id: 2, name: 't shirt', manufacturePrice: 8}
Back
how to deal with fetch responses
Front
fetch(url").then(function(response){})
Back
To get an element to appear in the DOM, we have to append it to an existing DOM node. We can start as high up on the tree as document.body, or we can find a more specific element using any of the techniques we've learned for traversing the DOM. Let's append element to body to start:
doesn't even have to be declared
(function (name, year, claimToFame) {
console.log(`Hi, I'm ${name}, I was born in ${year}, and I ${claimToFame}!`);
})('Ada Lovelace', 1815, 'was the first computer programmer');
// LOG: Hi, I'm Ada Lovelace, and I was the first computer programmer!
(function (name, year, claimToFame) {
console.log(`Hi, I'm ${name}, I was born in ${year}, and I ${claimToFame}!`);
})('Grace Hopper', 1906, 'invented one of the first compilers');
// LOG: Hi, I'm Grace Hopper, and I invented one of the first compilers!
Back
Notice that the target node is the _last node to capture the event_, whereas
it's the _first node to bubble the event up_. This is the most important
takeaway.
Front
Back
fetch ('url')
Front
makes get request. and returns a promise
{<pending>}
you have resolved and rejected as well