Javascript

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

element

content item inside an array

|| operator

only one condition needs to be true to execute else will execute only if all conditions are false if (day === 'Saturday' || day === 'Sunday') { console.log('Enjoy the weekend!'); } else { console.log('Do some work.');

Arrow Functions

shorter way to write functions by using the special "fat arrow" () => notation first include the parameters inside the ( ) and then add an arrow => that points to the function body surrounded in { } const plantNeedsWater = function (day) { } Becomes → const plantNeedsWater = (day) => { }

typeof operator

shows you the type of value

const

Make a variable unmodifiable; must be assigned a variable when declared (if you don't, you'll get a SyntaxError);

Arithmetic Operators

+, -, *, /, % console.log(# + #);

arithmetic (+ - * /)

+= -+ . *= /=

multiple line comment

/* */

inline/ single line comment

//

The list of falsy values includes::

0 Empty strings like "" or '' null which represents when there is no value at all undefined which represent when a declared variable lacks a value NaN, or Not a Number

default statement

If none of the cases are true, then the code in the default statement will run. default: console.log('Invalid item'); break; }

string

Any grouping of characters on your keyboard (letters, numbers, spaces, symbols, etc.) surrounded by single quotes: ' ... ' or double quotes " ... "

arrays and fuctions

So when you pass an array into a function, if the array is mutated inside the function, that change will be maintained outside the function as well. You might also see this concept explained as pass-by-reference since what we're actually passing the function is a reference to where the variable memory is stored and changing the memory.

If...Else Statements

Uses if statement, then else statement to run a block of code when the condition evaluates to false. if (false) { console.log('The code in this block will not run.'); } else { console.log('But the code in this block will!'); } if...else statements allow us to automate solutions to yes-or-no questions, also known as binary decisions.

Truthy and Falsy

Values that evaluate to boolean true or false but that aren't actually boolean values of true or false. let myVariable = 'I Exist!'; if (myVariable) { console.log(myVariable) } else { console.log('The variable does not exist.') } let numberOfApples = 0; if (numberOfApples){ console.log('Let us eat apples!'); } else { console.log('No apples left!'); } // Prints 'No apples left!'

local variables

Variables that are declared with block scope; they are only available to the code that is part of the same block. A better (best?) practice is to rename the variables inside the block.

Helper Functions

We can also use the return value of a function inside another function. These functions being called within another function are often referred to as helper functions. Since each function is carrying out a specific task, it makes our code easier to read and debug if necessary. function multiplyByNineFifths(number) { return number * (9/5); }; function getFahrenheit(celsius) { return multiplyByNineFifths(celsius) + 32; }; getFahrenheit(15); // Returns 59

Length property

built-in array property; returns the number of items in the array const newYearsResolutions = ['Keep a journal', 'Take a falconry class']; console.log(newYearsResolutions.length); // Output: 2

Calling a function

executes the function body, or all of the statements between the curly braces in the function declaration. the function name followed by parentheses. We can call the same function as many times as needed. greetWorld();

global scope

Contains global variables declared outside of blocks. it's best practice to not define variables in the global scope.

length property

Every string instance has a property called length that stores the number of characters in that string. You can retrieve property information by appending the string with a period and the property name: console.log('Hello'.length); // Prints 5

null

intentional absence of a value, and is represented by the keyword null (without quotes).

binary decision

is a yes-or-no decision with two possible outcomes

Update Elements

let seasons = ['Winter', 'Spring', 'Summer', 'Fall']; seasons[3] = 'Autumn'; console.log(seasons); //Output: ['Winter', 'Spring', 'Summer', 'Autumn']

index

numbered position of each element in an array, starting at 0

logical operators

operators that work with boolean values; use logical operators to add more sophisticated logic to our conditionals. There are three logical operators: the and operator (&&) the or operator (||) the not operator, otherwise known as the bang operator (!)

Comparison Operators

operators to compare values on the left with the value on the right Less than: < Greater than: > Less than or equal to: <= Greater than or equal to: >= Is equal to: === Is NOT equal to: !== 10 < 12 // Evaluates to true 'apples' === 'oranges' // false

Concise Body Arrow Functions

refactor arrow function syntax to make it more condense single line - does not need () {} or return EXAMPLE const plantNeedsWater = (day) => { return day === 'Wednesday' ? true : false; }; BECOMES: const plantNeedsWater = day => day === 'Wednesday' ? true : false;

The .pop() Method

removes the last item of an array. mutates the array. const newItemTracker = ['item 0', 'item 1', 'item 2']; const removed = newItemTracker.pop(); console.log(newItemTracker); // Output: [ 'item 0', 'item 1' ] console.log(removed); // Output: item 2 .pop() returns the value of the last element. In the example, we store the returned value in a variable removed to be used for later. this is optional

data types

string, numbers, booleans, null, undefined, symbol, object (object is the only one that's not a primitive data type)

interpolate

to insert; change by adding new words or material

boolean

true/false

declared variables without values

undefined variables

Template literals

used to log strings together; wrapped by backticks ` One of the biggest benefits to using template literals is the readability of the code. Using template literals, you can more easily tell what the new string will be. You also don't have to worry about escaping double quotes or single quotes. const myPet = 'armadillo'; console.log(`I own a pet ${myPet}.`); // Output: I own a pet armadillo.

var vs let

var was the only keyword for declaring variables until 2015. let is the preferred over var. it's for variables that can change. the variable can be reassigned a different value. Var can also change.

increment

variable++

decrement

variable--

global variables

variables declared outside of blocks. Because global variables are not bound inside a block, they can be accessed by any code in the program, including code in blocks.

ternary operator

we can use a ternary operator to simplify an if...else statement. let isNightTime = true; if (isNightTime) { console.log('Turn on the lights!'); } else { console.log('Turn off the lights!'); } --> isNightTime ? console.log('Turn on the lights!') : console.log('Turn off the lights!'); let favoritePhrase = 'Love That!'; favoritePhrase === 'Love That!' ? console.log('I love that!') : console.log("I don't love that!");

scope pollution

when we have too many global variables that exist in the global namespace, or when we reuse variables across different scopes. Having too many global variables can cause problems in a program. Scope pollution makes it difficult to keep track of our different variables and sets us up for potential accidents.

string concatenation

works like excel concatenate

Blocks

A block is the code found inside a set of curly braces {}. Blocks help us group one or more statements together and serve as an important structural marker for our code.

conditional operator

A conditional statement checks specific condition(s) and performs a task based on the condition(s). if, else if, and else statements

For Loop

A for loop contains three expressions separated by ; inside the parentheses: 1. an initialization starts the loop and can also be used to declare the iterator variable. 2. a stopping condition is the condition that the iterator variable is evaluated against— if the condition evaluates to true the code block will run, and if it evaluates to false the code will stop. 3. an iteration statement is used to update the iterator variable on each loop. https://www.codecademy.com/courses/introduction-to-javascript/lessons/loops/exercises/for-loop

Symbol

A newer feature to the language, symbols are unique identifiers, useful in more complex coding. No need to worry about these for now.

Switch keyword

A switch statement provides an alternative syntax that is easier to read and write than else if statements let groceryItem = 'papaya'; switch (groceryItem) { case 'tomato': console.log('Tomatoes are $0.49'); break; case 'lime': console.log('Limes are $1.49'); break; case 'papaya': console.log('Papayas are $1.29'); break; default: console.log('Invalid item'); break; }

! operator

The ! not operator reverses, or negates, the value of a boolean: Essentially, the ! operator will either take a true value and pass back false, or it will take a false value and pass back true. let excited = true; console.log(!excited); // Prints false let sleepy = false; console.log(!sleepy); // Prints true

break keyword

The break keyword tells the computer to exit the block and not execute any more code or check any other cases inside the code block. Note: Without the break keyword at the end of each case, the program would execute the code for all matching cases and the default code as well. This behavior is different from if/else conditional statements which execute only one block of code. break;

Else If Statements

The else if statements allow you to have multiple possible outcomes. if/else if/else statements are read from top to bottom, so the first condition that evaluates to true from the top to bottom is the block that gets executed. The else if statement always comes after the if statement and before the else statement. let stopLight = 'yellow'; if (stopLight === 'red') { console.log('Stop!'); } else if (stopLight === 'yellow') { console.log('Slow down.'); } else if (stopLight === 'green') { console.log('Go!'); } else { console.log('Caution, unknown!'); }

if keyword

The if keyword followed by a set of parentheses () which is followed by a code block, or block statement, indicated by a set of curly braces {}. Inside the parentheses (), a condition is provided that evaluates to true or false. If the condition evaluates to true, the code inside the curly braces {} runs, or executes. If the condition evaluates to false, the block won't execute. let sale=true if (sale){ console.log('Time to buy!'); } // Prints "Time to buy!"

remainder operator

The percent sign; returns the number that remains after the right-hand number divides into the left-hand number as many times as it evenly can: 11 % 3 equals 2 because 3 fits into 11 three times, leaving 2 as the remainder.

Arguments

The values that are passed to the function when it is called. Arguments can be passed to the function as values or variables. the order in which arguments are passed and assigned follows the order that the parameters are declared.

Return keyword

To pass back information from the function call, we use a return statement. To create a return statement, we use the return keyword followed by the value that we wish to return. Like we saw above, if the value is omitted, undefined is returned instead. When a return statement is used in a function body, the execution of the function is stopped and the code that follows it will not be executed. Example 1: function rectangleArea(width, height) { if (width < 0 || height < 0) { return 'You need positive integers to calculate area!'; } return width * height; } The second return statement width * height will not run. The return keyword is powerful because it allows functions to produce an output. We can then save the output to a variable for later use. Example 2: function monitorCount(rows, columns) { return rows*columns; } const numOfMonitors=monitorCount(5,4); console.log(numOfMonitors)

Looping For Loops in Reverse

To run a backward for loop, we must: 1. Set the iterator variable to the highest desired value in the initialization expression. 2. Set the stopping condition for when the iterator variable is less than the desired amount. 3. The iterator should decrease in intervals after each iteration. for (let counter = 3; counter >= 0; counter--){ console.log(counter); } //prints: 3,2,1,0

short-circuit evaluation.

When a boolean expression is evaluated the evaluation starts at the left hand expression and proceeds to the right, stopping when it is no longer necessary to evaluate any further to determine the final outcome. let tool = ''; let writingUtensil= tool || 'pen'; console.log(`The ${writingUtensil} is mightier than the sword.`);

Block Scope

When a variable is defined inside a block, it is only accessible to the code within the curly braces {}. contains local variables. allows us to define variables with precision, and not pollute the global namespace. If a variable does not need to exist outside a block— it shouldn't!

Nested Loops

When we have a loop running inside another loop; can be used to compare the elements in two arrays For each round of the outer for loop, the inner for loop will run completely. let bobsFollowers = ['Joe', 'Marta', 'Sam', 'Erin']; let tinasFollowers = ['Sam', 'Marta', 'Elle']; let mutualFollowers = []; for (let i = 0; i < bobsFollowers.length; i++) { for (let j = 0; j < tinasFollowers.length; j++) { if (bobsFollowers[i] === tinasFollowers[j]) { mutualFollowers.push(bobsFollowers[i]); } } }; console.log(mutualFollowers)

&& operator

When we use the && operator, we are checking that two things are true: all conditions must evaluate to true for the entire condition to evaluate to true and execute. Otherwise, if either condition is false, the && condition will evaluate to false and the else block will execute. if (stopLight === 'green' && pedestrians === 0) { console.log('Go!'); } else { console.log('Stop'); }

global namespace

When you declare global variables, they go to the global namespace. The global namespace allows the variables to be accessible from anywhere in the program. These variables remain there until the program finishes which means our global namespace can fill up really quickly.

looping through arrays:

a for loop should use the array's .length property in its condition. const animals = ['Grizzly Bear', 'Sloth', 'Sea Lion']; for (let i = 0; i < animals.length; i++) { console.log(animals[i]); } prints Grizzly Bear Sloth Sea Lion we've named our iterator variable i short-hand for the word index.

loop

a programming tool that repeats a set of instructions until a specified condition, called a stopping condition is reached. When the condition is met, the loop stops and the computer moves on to the next part of the program. You'll hear the generic term iterate when referring to loops; iterate simply means "to repeat". Loops allow us to create efficient code that automates processes to make scalable, manageable programs.

Methods

actions we can perform We call, or use, these methods by appending an instance with a period (the dot operator), the name of the method, and opening and closing parentheses: e.g. 'example string'.methodName().

Parameters

allow functions to accept input(s) and perform a task using the input(s). We use parameters as placeholders for information that will be passed to the function when it is called. treated like variables within a function When calling a function that has parameters, we specify the values in the parentheses that follow the function name. function sayThanks(name) { console.log('Thank you for your purchase '+ name + '! We appreciate your business.'); } sayThanks('Cole') //Thank you for your purchase Cole! We appreciate your business.

Default Parameters

allow parameters to have a predetermined value in case there is no argument passed into the function or if the argument is undefined when called. function greeting (name = 'stranger') { console.log(`Hello, ${name}!`) } greeting('Nick') // Output: Hello, Nick! greeting() // Output: Hello, stranger! we used the = operator to assign the parameter name a default value of 'stranger'.

hoisting feature

allows access to function declarations before they're defined; isn't considered good practice console.log(greetWorld()); // Output: Hello, World! function greetWorld() { console.log('Hello, World!'); }

The .push() Method

allows us to add items to the end of an array; access w/dot notation; Then we call it like a function. That's because .push() is a function and one that JavaScript allows us to use right on an array. Warning: .push() changes/ mutates an item const itemTracker = ['item 0', 'item 1', 'item 2']; itemTracker.push('item 3', 'item 4'); console.log(itemTracker); // Output: ['item 0', 'item 1', 'item 2', 'item 3', 'item 4'];

Nested Arrays

an array that contains another array const nestedArr = [[1], [2, 3]]; To access the nested arrays we can use bracket notation with the index value, just like we did to access any other element: console.log(nestedArr[1]); // Output: [2, 3] Then, if we wanted to access the elements within the nested array we can chain, or add on, more bracket notation with index values. console.log(nestedArr[1][0]); // Output: 2

Function Expressions

another way to define a function 1. declare a variable (identifier) using const 2. Assign as that variable's value an anonymous function created by using the function keyword followed by a set of parentheses with possible parameters. Then a set of curly braces that contain the function body. const calculateArea = function (width, height) { const area = width*height; return area; } Unlike function declarations, function expressions are not hoisted so they cannot be called before they are defined.

accessing an element by index #

arrayName[#] index # is the position in the array

=

assignment operator/ initializer

Function Declarations

binds a function to a name, or an identifier; like declaring variables function= greetWorld () { console.log('Hello World!"); } 1. The function keyword. 2. The name of the function, or its identifier, followed by parentheses. 3. A function body, or the block of statements required to perform a specific task, enclosed in the function's curly brackets, { }.

Let arrays

can reassign variables & entire arrays

Arrays with const

cannot re-assign the entire array, but can re-assign the contents within them. I believe you can also change the data type const utensils = ['Fork', 'Knife', 'Chopsticks', 'Spork']; utensils[3]='Spoon'; console.log(utensils); // 'Fork', 'Knife', 'Chopsticks', Spoon

object

collection of related data

built-in objects

collections of methods and properties that JavaScript provides.

logging in the console

console.log(definedVariable)

accessing element by character letter

const hello = 'Hello World'; console.log(hello[6]); // Output: W

array literal

creates an array by wrapping items in square brackets [] can store any data type we can have an array that holds all the same data types or an array that holds different data types. We can also save an array to a variable.

scope

defines where variables can be accessed or referenced. While some variables can be accessed from anywhere within a program, other variables may only be available in a specific context.

Undefined

denoted by the keyword undefined (without quotes). It also represents the absence of a value though it has a different use than null.


Set pelajaran terkait

APUSH CHAPTER 5 QUIZ AMERICAN PAGENT

View Set

Muscles of the Lower Limb (Name, Action, Origin, Insertion)

View Set

Reading Quiz: Chapter 9. Businesses and the Costs of Production

View Set

Equity Securities - Practice Exam

View Set