Javascript - Codecademy course https://www.codecademy.com/courses/introduction-to-javascript/lessons/intro duction-to-javascript/exercises/console?action=resume_content_item

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

ternary operator to simplify an if...else statement.

** The condition is placed before the ? ** If the condition is true, the first expression before colon executes. ** If the condition is false, the second expression after the colon executes. ** This is functionally equivalent of doing an if...else statement, with if (isNightTime). Ex1: let isNightTime = true; isNightTime ? console.log('Turn on') : console.log('Turn off'); >> false Ex 2: let favoritePhrase = 'Whatever"; (favoritePhrase === 'Love That!') ? console.log('I love that!') : console.log("I don't love that!"); >> false

Increment operator in JS

++

math assignment operators

+= -= *= /=

Decrement operator in JS

--

If you're trying to decide between which keyword to use, let or const,

...think about whether you'll need to reassign the variable later on. If you do need to reassign the variable use let, otherwise, use const.

console.log()

.log() is the method that acts on the console object Whatever is inside (argument) will get printed or "logged" to the console (on a separate line): console.log(5); console.log(25); console.log('It was love at first sight.'); >> 5 >> 25 >> It was love at first sight.

// Use a string method to log the following string without whitespace at the beginning and end of it. console.log(' Remove whitespace '.trim());

.trim() // method is avail in JS docs // takes out whitespace!

console.log('hello'.toUpperCase());

// Prints 'HELLO'

Math.floor(Math.random() * 50);

// Prints random number, but a whole number

console.log('Hey'.startsWith('H'));

// Prints true

What 3 things can you do with variables:

1. Create a variable w/ a descriptive name 2. Store or update info stored in a variable 3. Reference or "get" info stored in a variable

7 fundamental data types in JS

1. Number: 4, 5, 3.5, 222.222 2. String: 'Blah' or "Blah blah" 3. Boolean true or false 4. Null - the absence of a value null 5. Undefined - the absence of a value, but a different use than null. undefined 6. Symbol - unique identifiers, useful in more complex coding. 7. Object - collections of related data (nonprimitive, the rest are primitive)

Check what happens when you try concatenating strings using variables of different data types

ReferenceError: contcat is not defined

Comments in JS

Same as java // Single line /* Multiline sdkflj */ You can also use this syntax to comment something out in the middle of a line of code: console.log(/*IGNORED!*/ 5); // Still just prints 5

What happens if you try to reassign a const variable?

TypeError: thrown b/c Assignment to constant variable

return statement

Used to pass information back from a function

short circuit evaluation

Using a truthy value to check left hand condition first, and if not, the variable will be assigned the actual varibale if it is truthy, and will be assigned 'Stranger' if username is falsy. let defaultName = username || 'Stranger';

truthy and falsy

Values that evaluate to boolean true or false but that aren't actually boolean values of true or false. Ex. a "String" exists, so it evaluates to true: let myString = "I exist";

falsy

Values that evaluate to not truthy: - 0 - " " or ' ' - null, which represents when there is no value at all. - undefined, which represents when a declared variable lacks a value - NaN "not a number"

with the let keyword, can we declare a variable without assigning the variable a value?

Yes the variable will then be initialized with a value of undefined.

var

a JS keyword that creates or declares a new varible var myName = 'Aya'; console.log(myName); >> Aya

React.js

a Javascript library for building user interfaces

variable

a container for a value they live in a computer's memory a way of labeling data with a descriptive name, so our programs can understand them

hoisting

a feature in JS that allows access to function declarations before they're defined. console.log(greetWorld()); function greetWorld() { // whatever } ** THis is weird and not possible in Python/Java! Only ok in JS. ** It's not good practice though.

interpolate

aka "insert" means you can interpolate variables into strings using "template literals"

typeof operator

checks the value to its right and returns a String of the datatype. ex. const unk = 10; console.log(typeof unk); >> number

How to evaluate expressions in JS? and log them to console?

console.log(15 + 3.5); console.log(2018 - 1969); console.log(65 / 240); console.log(0.2708 * 100); console.log(4 % 1); // modulo 18.5 49 0.2708333333333333 27.08 0 // Interestingly, combining ints and floats is A-Okay

Math object in JS - has methods! https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math

console.log(Math.random()); // Prints random number between 0 and 1

template literals example note it uses backticks (`) instead of (')

const myPet = 'armadillo'; console.log(`I own a pet ${myPet}.`); >> I own a pet armadillo.

semicolon in JS

denotes the end of the line

It\'s

escape char

parameters

functions take inputs to do the task "placeholders" for information that will be passed to fxn when it is called Then, when you call a function with parameters, you can specify them in the function name as arguments.

and or not

he and operator (&&) the or operator (||) the not operator, otherwise known as the bang operator (!)

JS Number docs

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

JavaScript String documentation:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype

JS Keywords (reserved)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Keywords

MDN var documentation

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var

if statement in JS

if (true) { console.log("print"); // code block }

console (keyword)

in JS, "console" refers to an object (a collection of data and actions that we can use in the code)

let

keyword in JS that signals that the variable can be reassigned to a different value ex: let meal = 'Eng'; meal = 'Burritos'; console.log(meal); >> Burritos

const

keyword that makes a variable unmodifiable const myName = 'Olivia'; console.log(myName); // Output: Olivia

switch example

let athleteFinalPosition = 'first place'; switch (athleteFinalPosition) { case 'first place': console.log('You get the gold medal!'); break; case 'second place': console.log('You get the silver medal!'); break; case 'third place': console.log('You get the bronze medal!'); break; default: console.log('No medal awarded.'); break; }

Using truthy/falsy in short hand Ex. if you want to check if a username is defined, and assign it to a string if it is not?

let defaultName; if (username) { defaultName = username; } else { defaultName = "stringer"; }

switch keyword

let groceryItem = 'papaya'; // Checks for equality to groceryItem by listing all the cases, followed by respective blocks: 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; } // Prints 'Papayas are $1.29'

In JS, make sure you have a semicolon at the end of the statment

let hungerLevel = 7; if (hungerLevel > 7) { console.log('Time to eat!'); } else { console.log('We can eat later!'); };

I am confused when you're supposed to have a semicolon at the end.

let mood = 'sleepy'; let tirednessLevel = 6; if (mood === 'sleepy' && tirednessLevel > 8) { console.log('time to sleep'); } else { console.log('not bed time yet'); } // This one does not have a semicolon.

Race day project (practicing if-else statements) https://www.codecademy.com/courses/introduction-to-javascript/projects/race-day?action=resume_content_item

let raceNumber = Math.floor(Math.random() * 1000); let regEarly = false; let age = 20; if (regEarly && age >= 18) { raceNumber += 1000; } if (age >= 18) { if (regEarly) { console.log(`You will race at 9:30am. Your race number is ${raceNumber}`); } else { console.log(`You will race at 11:00am. Your race number is ${raceNumber}`); } } else { console.log(`You will race at 12:30pm. Your race number is ${raceNumber}`); }

Example of else if blocks

let season = 'summer'; if (season === 'spring') { console.log('It\'s spring! The trees are budding!'); } else if (season === 'winter') { console.log('It\'s winter! Everything is covered in snow.'); } else if (season === 'fall') { console.log('It\'s fall! Leaves are falling!'); } else if (season === 'summer') { console.log('It\'s sunny and warm because it\'s summer!'); } else { console.log('Invalid season.'); }

Use typeof to find the data type of the resulting value when you concatenate variables containing two different data types.

let string = 'Blah'; let num = 2; let concat = string + num; console.log(typeof contcat); >> undefined

short circuit evaluation example

let tool = ''; // Use short circuit evaluation to assign writingUtensil variable below: let writingUtensil = tool || 'pen'; console.log(`The ${writingUtensil} is mightier than the sword.`); /** Notice that text 'The pen is mightier than the sword' logged to the console. Which means the value of writingUtensil is 'pen'. What if we reassign the value of tool to 'marker'. Let's see what happens to the value of writingUtensil. */ let tool = 'marker'; // Use short circuit evaluation to assign writingUtensil variable below: let writingUtensil = tool || 'pen'; console.log(`The ${writingUtensil} is mightier than the sword.`);

My MagicEightBall program

let userName = 'Olivia'; let userQuestion = "What will happen"; let eightBall = ''; // Get new random int between 0 - 7: let randomNumber = Math.floor(Math.random() * 8); // Input validation: userName ? console.log(userName) : console.log('No userName entered.'); console.log(userQuestion + `, ${userName}?`); // Main logic: switch(randomNumber) { case 0: eightBall = 'It is certain'; break; case 1: eightBall = 'It is decidedly so'; break; case 2: eightBall = 'Reply hazy try again'; break; case 3: eightBall = 'Cannot predict now'; break; case 4: eightBall = 'Do not count on it'; break; case 5: eightBall = 'My sources say no'; break; case 6: eightBall = 'Outlook not so good'; break; case 7: eightBall = 'Signs point to yes'; break; } console.log(eightBall);

function keyword in JavaScript

lets us know when we are defining a function. function greet() { body }

Concatenation in JS

same

default:

the "else" block equivalent Tells the switch statement what to do if none of the cases are true.

Every instance of a string in JS has the property ' length '

this stores the number of chars in the string You can retrieve property info by using the "dot operator": console.log('Hello'.length);// Prints 5

variables that have not been initialized store the primitive data type ______.

undefined

Math is static why?

unlike other global objects, Math is not a constructor. All properties & methods of Math are static.

How to call a function?

use the identifier, followed by parentheses. name();

keywords

words that are recognized by the computer and treat specially

else if statements

you can add as many as you want in the flow of logic, it will halt after it finds the true statement and executes the block.

Math.ceil()

A method on the JavaScript Math object that returns the smallest integer greater than or equal to a decimal number. console.log(Math.ceil(43.8)); >> 44

default paramaters

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

JS (===) vs (==)

Functionally, they both check if two things are equal. However, the difference is between how the type conversion is done: - (===) will NOT do any type conversion. So if the values are not the same type, it will return false. So, (0 === ' ') is false and (0 === '0') is false but (0 === 0) is true. - (==) will do the type conversion. So, (0 == ' ') is true and (0 == '0') is true. ** THE PREFERRED METHOD IS === ** == is risky.

comparison operators

Less than: < Greater than: > Less than or equal to: <= Greater than or equal to: >= Is equal to: === Is NOT equal to: !==

Math.floor() and Math.random()

Math.random() returns a value between 0 (inclusive) and 1 (exclusive). In order to make this set of numbers range from 0 (inclusive) to 8 (exclusive) we can multiple the returned value by 8. Finally, to ensure we only have whole numbers from 0 to 7 we can round down using Math.floor(). const randomNumber = Math.floor(Math.random() * 8);

break keyword for switch statements

Must be used in a switch statement after each case. Otherwise, the logic will never break. ** Note this is why the logic is different than an if/ else if / else logic flow...

can a const variable be reassigned?

No, it is constant. You will get a TypeError.

Can you declare a const variable without a value?

No, you will get SyntaxError

Find a method on the built-in Number object that checks if a number is an integer. Put the number 2017 in the parentheses of the method and use console.log() to print the result.

Number.isInteger() console.log(Number.isInteger(2017)); >> true


Set pelajaran terkait

4.5 Overflow and Underflow: Knowledge Check

View Set

Preventive Dentistry & Nutrition

View Set

chapter 10 (the water-soluble vitamins) understanding nutrition

View Set

Pharmacology unit 2 IV formulas math problems, dosage calc verifying safe dose

View Set