Javascript Codecadamey

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

Which of the following is an example of a single line comment?

// Is this a comment? Correct // creates a single line comment

What will the code block log to the console? see picture let weather = "spring";let clothingChoice = ""; if (weather === "spring") { clothingChoice = "Put on rain boots.";} else if (weather === "summer") { clothingChoice = "Make sure to take your sunscreen.";} else if (weather === "fall") { clothingChoice = "Wear a light jacket.";} else if (weather === 'winter') { clothingChoice = "Wear a heavy coat.";} else { console.log('Invalid weather type.');};console.log(clothingChoice);

Put on rain boots dropped the ball on this one.

Conditional Statements Review

Review Way to go! Here are some of the major concepts for conditionals: An if statement checks a condition and will execute a task if that condition evaluates to true. if...else statements make binary decisions and execute different code blocks based on a provided condition. We can add more conditions using else if statements. Comparison operators, including <, >, <=, >=, ===, and !== can compare two values. The logical and operator, &&, or "and", checks if both provided expressions are truthy. The logical operator ||, or "or", checks if either provided expression is truthy. The bang operator, !, switches the truthiness and falsiness of a value. The ternary operator is shorthand to simplify concise if...else statements. A switch statement can be used to simplify the process of writing multiple else if statements. The break keyword stops the remaining cases from being checked and executed in a switch statement.

Truthy and Falsy

Sometimes, you'll want to check if a variable exists and you won't necessarily want it to equal a specific value — you'll only check to see if the variable has been assigned a value. The code block in the if statement will run because myVariable has a truthy value; even though the value of myVariable is not explicitly the value true, when used in a boolean or conditional context, it evaluates to true because it has been assigned a non-falsy value. So which values are falsy— or evaluate to false when checked as a condition? The list of falsy values includes: 0 Empty strings like "" or '' null which represent when there is no value at all undefined which represent when a declared variable lacks a value NaN, or Not a Number The condition evaluates to false because the value of the numberOfApples is 0. Since 0 is a falsy value, the code block in the else statement will run.

Truthy and Falsy Assignment

Truthy and falsy evaluations open a world of short-hand possibilities! Say you have a website and want to take a user's username to make a personalized greeting. Sometimes, the user does not have an account, making the username variable falsy. The code below checks if username is defined and assigns a default string if it is not:

What is string interpolation?

Using template literals to embed variables into strings. Correct! String interpolation is when we insert, or interpolate, variables into strings using template literals.

Return

When a function is called, the computer will run through the function's code and evaluate the result of calling the function. By default that resulting value is undefined.

Comparison Operators

When writing conditional statements, sometimes we need to use different types of operators to compare values. These operators are called comparison operators. Here is a list of some handy comparison operators and their syntax: Less than: < Greater than: > Less than or equal to: <= Greater than or equal to: >= Is equal to: === Is not equal to: !== Comparison operators compare the value on the left with the value on the right. For instance: All comparison statements evaluate to either true or false and are made up of: Two values that will be compared. An operator that separates the values and compares them accordingly (>, <, <=,>=,===,!==).

To make this statement valid, what operator belongs in the ___ space below?

Yes! The === opeartor is used to compare values.

What are variables used for in JavaScript?

Yes! Variables hold data.

Helper Functions

You create one function whose purpose is to calculate a value and return it so that another function can use that information.

What will the code block log to the console?

correct since groceryitem = apple. it does not match any of the cases so the default block will run.

function

function syntax functionName() {} The function keyword. The name of the function, or its identifier, followed by parentheses. A function body, or the block of statements required to perform a specific task, enclosed in the function's curly brackets, { }.

if statement with multiple conditions.

if (condition && condition) { console.log('statement');} else if (condition && !condition) { console.log('other statement');}

If...Else Statements

if (true/false/expression) { console.log(" "); };

What are Conditional Statements?

if, else if, and else statements comparison operators logical operators truthy vs falsy values ternary operators switch statement

If isHungry equals true, which of the following expressions evaluates to true?

isHungry !== false Correct! In this case, isHungry does not equal false.

What is the correct way to declare a new variable that you can change?

let myName = 'Sloan'

Which of the following variables contains a truthy value?

let varOne = 'false;

Which variables possess block scope?

number, phase, val are in block scope. control val is within the global scope.

How would you properly refactor this code block using the ternary operator?

walkSignal === 'Walk' ? console.log('You may walk!') : console.log('Do not walk!');

What is the outcome of this statement? console.log('hi!'.length);

3 is printed to the console.

What will the following code print to the console? let num = 10; num *= 3; console.log(num);

30 Correct *= will multiply the num by 3 and then reassign the value of num to that result.

function_reusable

A function is a reusable block of code that groups together a sequence of statements to perform a specific task.

Function Expressions

A function with no name is called an anonymous function. A function expression is often stored in a variable in order to refer to it. To declare a function expression: Declare a variable to make the variable's name be the name, or identifier, of your function. Since the release of ES6, it is common practice to use const as the keyword to declare the variable. 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. To invoke a function expression, write the name of the variable in which the function is stored followed by parentheses enclosing any arguments being passed into the function. syntax: variableName(argument1, argument2)

What is a globally scoped variable?

A variable that is accessible to any part of the program.

Which best defines a variable with block scope?

A variable that is defined within a block and only available inside a block.

Arrow Functions

Arrow functions remove the need to type out the keyword function every time you need to create a function. Instead, you first include the parameters inside the ( ) and then add an arrow => that points to the function body surrounded in { } like this:

Logical Operators

Codecademy Link: https://www.codecademy.com/courses/introduction-to-javascript/lessons/control-flow/exercises/logical-operators When we use the && operator, we are checking that two things are true: the and operator (&&) the or operator (||) When using the && operator, both 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 we only care about either condition being true, we can use the || operator. When using the || operator, only one of the conditions must evaluate to true for the overall statement to evaluate to true. In the code example above, if either day === 'Saturday' or day === 'Sunday' evaluates to true the if's condition will evaluate to true and its code block will execute. If the first condition in an || statement evaluates to true, the second condition won't even be checked. The not operator, otherwise known as the bang 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. Logical operators are often used in conditional statements to add another layer of logic to our code. see picture for syntax https://www.w3schools.com/js/js_comparisons.asp if (): {} else {};

short-circuit evaluation

Codecademy Link: https://www.codecademy.com/courses/introduction-to-javascript/lessons/control-flow/exercises/truthy-falsy-operators f you combine your knowledge of logical operators you can use a short-hand for the code above. In a boolean condition, JavaScript assigns the truthy value to a variable if you use the || operator in your assignment: Because || or statements check the left-hand condition first, the variable defaultName will be assigned the actual value of username if it is truthy, and it will be assigned the value of 'Stranger' if username is falsy. This concept is also referred to as short-circuit evaluation. let newVar = anotherVar || 'default value'

What is the general purpose of a conditional statement

Conditional statements evaluate code as either true or false.

What is preferable: defining variables in the global scope or defining variables in the block scope?

Defining variables in the block scope. Variables defined in the global scope can cause unexpected behavior in our code. 👏Correct! Global scope can make things like variable collision (using the same variable for two different purposes) more common.

else if

Else If Statements We can add more conditions to our if...else with an else if statement. The else if statement allows for more than two possible outcomes. You can add as many else if statements as you'd like, to make more complex conditionals! The else if statement always comes after the if statement and before the else statement. The else if statement also takes a condition. Let's take a look at the syntax: 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!');} 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. In the example above, since stopLight === 'red' evaluates to false and stopLight === 'yellow' evaluates to true, the code inside the first else if statement is executed. The rest of the conditions are not evaluated. If none of the conditions evaluated to true, then the code in the else statement would have executed.

What will the following code log to the console? see picture

Finding tacos

Ternary Operator In the spirit of using short-hand syntax, we can use a ternary operator to simplify an if...else statement.

In the spirit of using short-hand syntax, we can use a ternary operator to simplify an if...else statement. Take a look at the if...else statement example: let isNightTime = true; if (isNightTime) { console.log('Turn on the lights!');} else { console.log('Turn off the lights!');} We can use a ternary operator to perform the same functionality: isNightTime ? console.log('Turn on the lights!') : console.log('Turn off the lights!'); In the example above: The condition, isNightTime, is provided before the ?. Two expressions follow the ? and are separated by a colon :. If the condition evaluates to true, the first expression executes. If the condition evaluates to false, the second expression executes. Like if...else statements, ternary operators can be used for conditions which evaluate to true or false.

When to use semicolons in Javascript

It is easier for me to think of statements the same way we use that word in spoken language. A "statement" is when you are stating something, not asking about something. If you say something is true, that is a statement. If you say something equals something else, that is a statement. If you tell someone to do something, that is a statement. If you are asking a question (is this true?) then you are not making a statement. https://www.codecademy.com/resources/blog/your-guide-to-semicolons-in-javascript/

Concise Body Arrow Functions

JavaScript also provides several ways to refactor arrow function syntax. The most condensed form of the function is known as concise body. We'll explore a few of these techniques below: Functions that take only a single parameter do not need that parameter to be enclosed in parentheses. However, if a function takes zero or multiple parameters, parentheses are required. A function body composed of a single-line block does not need curly braces. Without the curly braces, whatever that line evaluates will be automatically returned. The contents of the block should immediately follow the arrow => and the return keyword can be removed. This is referred to as implicit return.

Translate this to Javascript: Log "Bear!" to console if isFurry is true and weight is over 100 pounds.

Log "Bear!" to console if isFurry is true and weight is over 100 pounds. Correct! This only logs "Bear!" if isFurry is true and weight is greater than 100.

What is the correct way to call the random method on the Math global object?

Nice work! This is the correct syntax.

What will the code block log to the console? let runTime = 35;let runDistance = 3.5; if (runTime <= 30 && runDistance > 3.5) { console.log("You're super fast!");} else if (runTime >= 30 && runDistance <= 3) { console.log("You're not making your pace!");} else if (runTime > 30 || runDistance > 3) { console.log("Nice workout!"); } else { console.log("Keep on running!");}

Nice workout! Exactly right! The condition (runTime is greater than 30 OR runDistance is greater than 3) is true. see picture

If Statement

Notice in the example above, we have an if statement. The if statement is composed of: 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.

Default Parameters

One of the features added in ES6 is the ability to use default parameters. 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. Take a look at the code snippet below that uses a default parameter: function greeting (name = 'stranger') { console.log(`Hello, ${name}!`)} greeting('Nick') // Output: Hello, Nick!greeting() // Output: Hello, stranger! In the example above, we used the = operator to assign the parameter name a default value of 'stranger'. This is useful to have in case we ever want to include a non-personalized default greeting! When the code calls greeting('Nick') the value of the argument is passed in and, 'Nick', will override the default parameter of 'stranger' to log 'Hello, Nick!' to the console. When there isn't an argument passed into greeting(), the default value of 'stranger' is used, and 'Hello, stranger!' is logged to the console.


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

Wold Population and Foods Final Exam Study Set

View Set

Complete Subjects and Predicates

View Set

Chapter 31: Assessment and Management of Patients with Hypertension

View Set

Chapter 37: Assessment and Management of Patients With Allergic

View Set

16-1: Preparing an Income statement

View Set