Javascript

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

function retailPriceMaker(manufacturePrice) { return function(marketMultiplier) { return marketMultiplier * manufacturePrice; }; } const retailPriceForNine = retailPriceMaker(9); retailPriceForNine; // ƒ (marketMultiplier){ // return marketMultiplier * manufacturePrice; // } retailPriceForNine(2); // 18 explain this magic

Closure examples make attributes private as opposed to class objects

Define Undefined

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).

whenever you store a function in an object

it is called a method

using let and const helps you avoid hoisting issues

it will raise errors

Top Tip: If a variable or function is not declared inside a function or block

it's in the global execution context.

Be mindful of adding your scrip tag in the top

js load before html does and you can get an error

you don't have to name a function if you name it to a variable

let func = function () {};

arrow function you cannot reassign

let someVariable = () => {return this } this is an anonymous function

fetch ('url')

makes get request. and returns a promise {<pending>} you have resolved and rejected as well

all event bubble

meaning that all event will propagate to the root node

Scope chain (JS)

means that any variable or function on the outside is available on the inside

This is also called a Multi-dimensional Array is also called a (Show an example too)

nested array [["Bulls", 23], ["White Sox", 45]]

Variable names can consist of

numbers, letters, $ or _ no spaces and can't start with a number.

<p id="corgi">This paragraph is silly </p> change the text

pTag.textContent "This paragraph is silly" pTag.textContent = "It is not silly"

the digit selector explain and show an example

\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;

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.

ex1 if (num > 5) { if (num < 10) { return "Yes"; } } return "No"; ex2 if (num > 5 && num < 10) { return "Yes"; } return "No";

List of js web events

https://developer.mozilla.org/en-US/docs/Web/Events

Full explanation of the sort method

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

.length

is a property to find the amount of characters

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.

is that so?

show an example of event listener on a target

pokemonContainer.addEventListener('click' function(event){ if(event.target.tagName === "IMG") if(event.target.src === ) })

parseFloat()

preserves a decimal

Objects have their own attributes, called

properties, and their own functions, called methods.

booleans

true false

Use filter to create a new array with all the values from oldArray which are less than 6. The oldArray should not change.

var oldArray = [1,2,3,4,5,6,7,8,9,10]; var newArray = oldArray.filter(function(val){ return val < 6; });

.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.

var oneDown = [1, 4, 6].pop(); the variable oneDown now holds the value 6 and the array becomes [1, 4].

You can also access array using indexing (create and array and access a part of it?)

var ourArray = [1,2,3]; var ourData = ourArray[0];

Delete Properties from a JavaScript Object

var ourDog = { "name": "Camper", "legs": 4, "tails": 1, "friends": ["everything!"], "bark": "bow-wow" }; delete ourDog.bark;

Show an example of float division (Javascript)

var quotient = 4.4 / 2.0;

With JavaScript array variables, we can store several pieces of data in one place (show an example)

var sandwich = ["peanut butter", "jelly", "bread"]

You can have both global and local scope with the same names (show an example)

var someVar = "Hat"; function myFun() { var someVar = "Head"; return someVar; }

toUpperCase()

var str = "Hello World!"; var res = str.toUpperCase();

Else is statement in JS are written as

else if

Lexical scoping means

that functions will seek out variables from the parent first

select all p tags jQuery style

$("p");

Javascript template literal

${} will call upon javascript directly

function () {} // ERROR: Uncaught SyntaxError: Unexpected token ( needs a name. what to do you do if you dont want to put a name

(function namedFunctionExpression1 () {}) // => ƒ namedFunctionExpression1() {} const myFunc = function namedFunctionExpression2 () {}; myFunc; // => ƒ namedFunctionExpression2() {} //see no name!! (function () {}) // => ƒ () {} const myFunc = function () {}; myFunc; // => ƒ () {}

Compound Assignment With Augmented multiplication

*=

Compound Assignment With Augmented Addition (what is that?)

+=

Compound Assignment With Augmented Subtraction

-=

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.

...

replace method in JS (show us an example)

.replace(arg1, arg2)

Arrays are mutable (what does this mean and show an example)

// Setup var myArray = [1,2,3]; // Only change code below this line. myArray[0] = 3;

Compound Assignment With Augmented division

/=

THE KEY TO SCOPE To determine a variable's scope in JavaScript, ask yourself two questions:

1. Is it declared inside a function? 2. Is it declared with the `var` keyword?

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:

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.

A JavaScript engine

A program or interpreter that understands and executes JavaScript code. Synonyms: JavaScript interpreter, JavaScript implementation

Statements vs. expressions what is the difference?

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

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

Bar

Why does string[string.length - 1] give you the last letter of a string? (remember to put the variable on the outside as well)

Because with bracket notation, and index starts with 0 therefore when you take the length - 1 you will get that character

Slicing and Spreading

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"]

Returning Boolean Values from Functions (what does this mean? )

Don't tell the thing to return true or false just put the damn thing

Spread Operator (JS) what does it do

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"]

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?

Foo

Understand String Immutability (what does it mean?)

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";

In some other languages Arrays cannot be of multiple types.

In C, C++, Java, Swift, and others you cannot mix types. JavaScript, Python, Ruby, Lisp, and others permit this.

hasOwnProperty()

Is a method that checks at a certain property is contained

Adding a default option in Switch statements

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"; } }

JSON

JavaScript Object Notation

Object.assign()

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" }

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:

Math.ceil(0.5); //=> 1 Math.floor(0.5); //=> 0 Math.round(0.5); //=> 1 Math.round(0.49); //=> 0

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:

Math.floor(Math.random() * 10) + 1; //=> 8 Math.floor(Math.random() * 10) + 1; //=> 1 Math.floor(Math.random() * 10) + 1; //=> 6

Math.max() / Math.min()

Math.max(1, 2, 3, 4, 5); //=> 5 Math.min(1, 2, 3, 4, 5); //=> 1

Is foo global? function global(){ foo = "bar" }

Nope! It is tied to that scope.

Number.isFinite()

Number.isFinite(9001); //=> true Number.isFinite(Infinity); //=> false

Number.isNaN()

Number.isNaN(10); //=> false Number.isNaN(undefined); //=> false Number.isNaN(NaN); //=> true

Number.parseFloat()

Number.parseFloat() only accepts a single argument, the string that should be parsed into a floating-point number:

Accessing Nested Objects

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"];

document.querySelectorAll()

Returns all that is matching in the parentheses. Returns something like an array

document.getElementById()

Returns the element that has the ID attribute with the specified value

document.querySelector()

Returns the first Element within the document that matches the specified selector, or group of selectors, or null if no matches are found.

XMLHttpRequest

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

Comparison with the Less Than Operator

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.

Comparison with the Less Than Or Equal To Operator

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.

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.

The output will yield what's expected of these code outputs

Uncaught ReferenceError: _____ is not defined

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:

Uncaught TypeError: _____ is not a function

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

Sort Arrays with sort (sort will actually alter the array);

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; });

Join Strings with join (show an example)

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.

We can also create private properties and private methods, which

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();

When using the sort method especially with multiple digit number you need a comparison funtion

array.sort(function(a,b) { return b - a; });

The documentation shows three ways to use .splice():

array.splice(start) array.splice(start, deleteCount) array.splice(start, deleteCount, item1, item2, ...)

.splice with 2 arguments

array.splice(start, deleteCount)

to add a class to a tag in js

const = = document.createElement('p') p.className

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...

const alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']; // => undefined alphabet.length; // => 26 alphabet[alphabet.length - 1]; // => "z"

Storing functions in an array We can store functions as elements in an array:

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 ()

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:

const books = ['Bleak House', 'David Copperfield', 'Our Mutual Friend']; books.splice(2, 0, 'Great Expectations', 'Oliver Twist'); // => [] books; // => ["Bleak House", "David Copperfield", "Great Expectations", "Oliver Twist", "Our Mutual Friend"]

Add a Property to an Object To add properties to an Object, we can use either dot notation or bracket notation:

const circle = {}; circle.radius = 5; circle['diameter'] = 10; circle.circumference = circle.diameter * Math.PI; // => 31.41592653589793 circle['area'] = Math.PI * circle.radius ** 2; // => 78.53981633974483 circle; // => { radius: 5, diameter: 10, circumference: 31.41592653589793, area: 78.53981633974483 }

Show an example of you stopping an event propagation

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); }

const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']; use.splice on this JS

days.splice(2); // => ["Wed", "Thu", "Fri", "Sat", "Sun"] days; // => ["Mon", "Tue"]

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*

delete wednesdayMenu.salad; // => true wednesdayMenu; // => { cheesePlate: { soft: "Brie", semiSoft: "Fontina", hard: "Manchego" }, fries: "Sweet potato" }

Callback functions do not

do not get invoked

returns the URL of the document object in your console

document.URL;

return all the nodes in your browser console

document.all;

returns the type of content contained. Most web pages should return "text/html" in your console

document.contentType;

<div> <h5 id="greeting">Hello!</h5> </div> how would you access the greeting?

document.getElementById()

<!-- 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

document.getElementsByClassName()

returns all p tags on a page

document.getElementsByTagName("p");

Comparison with the Equality Operator (show and example)

function equalityTest(myVal) { if (myVal == 10) { return "Equal"; } return "Not Equal"; }

Passing Values to Functions with Arguments (Use parameters)

function functionWithArgs(a, b) { console.log(a + b);} functionWithArgs(5, 5);

fetch('url')

return response.json (you still need to go to another level)

console.warn()

same as console.log but yellow

What is the major difference btwn splice and slice

slice arguments are startinf index and ending index splice is starting index and how manf positions after that

The diffenece between ++i and i+++ is how

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.

You cannot compare arrays using the equality sign

they are objects. you need to convert them in order to do such a comaparison

In JavaScript, variables become global when they aren't declared with the

they aren't declared with the var keyword.

A constructor function is given a capitalized name

to make it clear that it is an constructor

In a constructor the this variable refers

to the new object being created by the constructor. So when we write, this.wheels = 4;

element.remove()

ul.remove();

removeChild()

ul.removeChild(ul.querySelector('li:nth-child(2)'));

What are the seven data types?

undefined, null, boolean, string, symbol, number, and object

innerText

will change the text only

Number.isInteger()

will check if a number is an integer Number.isInteger(42); //=> true Number.isInteger(0.42); //=> false

Ajax

Asynchronous JavaScript and XML

What will a return statement do within a function?

It will break out of the function. So

when should you use the var variable

NEVER

typeof keyword

can specify what type of datatype your variable will be.

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

cards; // => ["Ace of Spades", "Jack of Clubs", "Ace of Clubs", "Nine of Diamonds", "Three of Hearts"]

an example of a class inn JS

class Item { constructor(name, manufacturePrice) { this.name = name; this.manufacturePrice = manufacturePrice; } retailPrice(marketMultiplier) { return marketMultiplier * this.manufacturePrice; } }

const address = { street1: '11 Broadway', street2: '2nd Floor', city: 'New York', state: 'NY', zipCode: 10004 }; access in js using .notation

address.street1; // => "11 Broadway" address.street2; // => "2nd Floor" address.city; // => "New York" address.state; // => "NY" address.zipCode; // => 10004

Concatenate Arrays with concat

concat takes an array as an argument and returns a new array with the elements of this array concatenated onto the end.

preventDefault()

const input = document.querySelector('input') input.addEventListener('keydown', function(e) { if (e.which === 71) { return e.preventDefault() } else { console.log(e.which) } });

We can update or overwrite existing properties by assigning a new value to an existing key:

const mondayMenu = { cheesePlate: { soft: 'Chèvre', semiSoft: 'Gruyère', hard: 'Manchego' }, fries: 'Curly', salad: 'Cobb' }; mondayMenu.fries = 'Sweet potato'; mondayMenu; // => { cheesePlate: { soft: "Chèvre", semiSoft: "Gruyère", hard: "Manchego" }, fries: "Sweet potato", salad: "Cobb" }

show a js for of loop

const myArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g']; for (const element of myArray) { console.log(element); }

function nondestructivelyUpdateObject(obj, key, value) { return Object.assign({}, obj, { [key]: value }); } implement an example of this function

const recipe = { eggs: 3 }; const newRecipe = nondestructivelyUpdateObject(recipe, 'chocolate', '1 cup'); // => { eggs: 3, chocolate: "1 cup" } newRecipe; // => { eggs: 3, chocolate: "1 cup" } recipe; // => { eggs: 3 }

alert()

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.

document.querySelector

built in function that allows you to select HTML elements?

function expression are not hoitsed

but functions are

In JS Arrays are just objects

but key values are not easily accessible through index

We can select a specific piece of the DOM by using JavaScript, such as

document.querySelector('header'), and we can also use JavaScript to alter our DOM with document.querySelector('header').remove()

select all p tags

document.querySelectorAll('p');

#=== 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

explain this

how to deal with fetch responses

fetch(url").then(function(response){})

The browser, not the JavaScript language provides an object called

firefox started with it but then changed it uo

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

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

use for of loop on "Hello World!"

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: !

Create a profile lookup Method uusing hasOwnProperty method

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";

another example of a Function COnstructor

function Artist (name, hairLength){ this.name = name this.hairLength = hairLength }

create a function that makes a new object in JS

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.

What method could you use to convert a string in to an integer in your DOM?

parseInt()

Create a ul using JS only

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);

Scoping what is it?

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.

To use a constructor function

we call it with the new keyword in front of it like: var myCar = new Car();

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.

// 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); }

Using Objects for Lookups (show and example and give a verbal explanation)

// 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

Invert Regular Expression Matches with JavaScript (show how )

// 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;

Find Whitespace with Regular Expressions

// 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;

Calling a function can make nonglobal variable global. show an example

//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

To add properties to an object

//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";

Important rules for array object properties

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.

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)

17 % 2 = 1 (17 is Odd) 48 % 2 = 0 (48 is Even)

Whats the difference between an equality operator and a strict equality operator?

3 === 3 // true 3 === '3' // false The strict equality operator also enforces the same datatype

Examples of root cascading (css)

:root { --penguin-skin: gray; --penguin-belly: pink; --penguin-beak: orange; }

Number.parseFloat()

Number.parseFloat() only accepts a single argument, the string that should be parsed into a floating-point number: Number.parseFloat('3.14159'); //=> 3.14159

Number.parseInt() wtf is a binary number?

Number.parseInt('100', 10); //=> 100 Number.parseInt('100', 2); //=> 4

Logical Order in If Else Statements (What is the importance?)

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.

Comparison with the Inequality Operator

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.

Comparison with the Greater Than Operator

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.

Comparison with the Greater Than Or Equal To Operator

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.

Variables declared with var are only available within that function's scope.

Variables declared without var attach themselves to the global object.

What does the split method do?

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');

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:

appendChild() \https://learn.co/tracks/web-development-immersive-2-0-module-three/javascript-foundations/the-dom/creating-and-inserting-nodes

Regular expressions (what are they and show you how it's done)

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;

Immediately-invoked function expressions IFFE

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!

Convert a string into an array

done

Show multiple examples of the .slice() method

done

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)

done

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:

done

What does the chartAt method do in JS?

done

There are three different ways the && operator can be evaluated:

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

Case switches (use an example of case switches) (Make sure the syntax is always correct)

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);

Create a JS ITEM class

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}

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:

function functionName() { console.log("Hello World"); }

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)

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

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 )

function lastCharacter(val1, val2){ if (val1.slice(-1) === val2.slice(-1)){ return true; } else { return false;} }

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)

function myTest() { var loc = "foo"; console.log(loc); } myTest(); // "foo" console.log(loc); // "undefined"

Then, with the ES2015 spread operator, we can copy all of the old menu Object's properties into a new Object:

function nondestructivelyUpdateObject(obj, key, value) { const newObj = { ...obj }; // Code to return new, updated menu object }

Generate random numbers within a range

function ourRandomRange(ourMin, ourMax) { return Math.floor(Math.random() * (ourMax - ourMin + 1)) + ourMin; }

We can pass values into a function with arguments. You can use a return statement to send a value back out of a function.

function plusThree(num) { return num + 3; } var answer = plusThree(5); // 8

Multiple Identical Options in Switch Statements (show an example)

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"; }

Show an example fo a global variable. That is within a function

function speaker() { sentence = 'Bird is the word.'; } speaker(); console.log(sentence);

Show an example of an if statement

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"

Math.random() //javascript (test out an example)

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

'Hello, world!' // => "Hello, world!" [] // => [] {} // => {} (function () {}) // => ƒ () {}

functions are statements. you can save them

use a dom content loaded event listener

if you put your script tags at the top

MULTI-LINE VARIABLE ASSIGNMENT is allowed

i didnt know that var a = 1 b=2 c=3

The logical or operator (||) returns true if either of the operands is true. Otherwise, it returns false (accomplish this without the operator)

if (num > 10 || num < 5) { return "No"; } return "Yes";

const and let are block-scoped:

if (true) { const myVar = 42; let myOtherVar = 9001; } myVar; // Uncaught ReferenceError: myVar is not defined myOtherVar; // Uncaught ReferenceError: myOtherVar is not defined

Variables declared with var are not block-scoped:

if (true) { var myVar = 42; } myVar; // => 42

When variables are declared, they have an initial value of undefined

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".

Asynchronous

is good for getting data from somewhere else

console.error()

is like console.log but is styled differently

NaN

is like undefined for numbers

Define Null

is the absence of a value. It is an assignment value that can be assigned to a variable as a representation of 'no-value'.

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"

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

You can append string using the +=

operator

slice method descibe what it does.

slice method will take an specific index and cut froma beginnig to end. (two parameters may be needed at times) is -1 indexed also

In JS negative indices only work in

splice and slice

in JS

strings are falsy

How to get access to the dom

type document in the console

Tracing is

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...

Show an example of the strict inequality operator

val !== val2

Make Unique Objects by Passing Parameters to our Constructor (java script)

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);

Show an example of a constructor function

var MotorBike = function() { this.wheels = 2; this.engines = 1; this.seats= 2; };

Show an example of a shadowy variable

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"

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.

var arr = [ [1,2,3], [4,5,6], [7,8,9], [[10,11,12], 13, 14] ]; arr[3]; // equals [[10,11,12], 13, 14] arr[3][0]; // equals [10,11,12] arr[3][0][1]; // equals 11

.push() takes one or more parameters and "pushes" them onto the end of the array.

var arr = [1,2,3]; arr.push(4); // arr is now [1,2,3,4]

Condense arrays with reduce (show an example)

var array = [4,5,6,7,8]; var singleVal = 0; var singleVal = array.reduce(function(previousVal, currentVal) { return previousVal + currentVal; }, 0);

Create an example of a JavaScript cat object

var cat = { "name": "Whiskers", "legs": 4, "tails": 1, "enemies": ["Water", "Dogs"] };

Create a reassignment with a returned value using a function.

var changed = 0; function change(num) { return (num + 5) / 3; } changed = change(10);

document.createElement()

var element = document.createElement('div');

How would you access another js file in your current js file?

var index = require("./index.js")

Create an array from 1 to 4 using a while loop

var myArray = []; var i = 0; while (i < 5) { myArray.push(i); i++; }

Create a variable and assign it to a float

var myDecimal = 7.5;

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.

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

Show an example of updating a property of a variable.

var myDog = { "name": "Coder", "legs": 4, "tails": 1, "friends": ["Free Code Camp Campers"] }; // Only change code below this line. myDog.name = "Happy Coder";

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

var myObj = { "Space Name": "Kirk", "More Space": "Spock" }; myObj["Space Name"]; // Kirk myObj['More Space']; // Spock

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

var myObj = { prop1: "val1", prop2: "val2" }; var prop1val = myObj.prop1; // val1 var prop2val = myObj.prop2; // val2

The map method is a convenient way to iterate through arrays. Here's an example usage:

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]

Block statements are commonly used with control flow statements (e.g. if, for, while).

while (x < 10) { x++; }

const morningMeal = 'breakfast'; const middayMeal = 'lunch'; const eveningMeal = 'dinner'; const meals = { [morningMeal]: 'French toast', [middayMeal]: 'Personal pizza', [eveningMeal]: 'Fish and chips' }; meals; // => { breakfast: "French toast", lunch: "Personal pizza", dinner: "Fish and chips" }

wildKeys["$ $ bill, y'all!"]; // => "Ever" dot notation does not work when strings are keys

js debugger

will pause your loading and access variables

Reverse Method.

will revese and modify an array

Math.floor() JS

will round down to the nearest whole number

stopPropagation()

will stop other events from occuring

map function

will take a whole array and give you the ability to create and manipulate a new array.

The window object has a large number of properties that return information about the object. Below are a few examples

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.

console.table

works well with a js object to show data better

is foo global? function global(){ var foo = "bar" }

yep

.slice method (JS) will copy and array unless

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*

with const

you cannot reassign or redeclare

add event listener and add it to the target

you do it by adding to the container


संबंधित स्टडी सेट्स

Chapter 21: Respiratory Care Modalities

View Set

ch. 9 data privacy and confidentiality

View Set

2.4) Quantitative vs. Qualitative Research

View Set

England Part 2The Canterbury tales, English 12 Unit 4 Test, Quiz 3 11-14, Nun's Priest Tale, Medieval literature 1-9, 11-14, 17, English 4 Unit 5, Canterbury Tales, Canterbury Tales Test, Medieval England, English Exam Characters, Final Test, English...

View Set

Elements for Chemistry (name elements and element symbol)

View Set

Automate the Boring Stuff with Python by Al Sweigart - Ch 8-11

View Set

Lesson 13 - Politics, power and violence

View Set