JavaScript syntax I

Ace your homework & exams now with Quizwiz!

whats a template literal, give example

${} is a template literal. normally there will be a variable in there a template literal is wrapped in `backticks`

how would you use if / if else / else if - whats the correct order

1. if 2. else if 3. else

What are functions

A function is a reusable block of code that groups together a sequence of statements to perform a specific task. When first learning how to calculate the area of a rectangle, there's a sequence of steps to calculate the correct answer: Measure the width of the rectangle. Measure the height of the rectangle. Multiply the width and height of the rectangle We can calculate the area of one rectangle with the following code: const width = 10; const height = 6; const area = width * height; console.log(area); // Output: 60 Imagine being asked to calculate the area of three different rectangles: // Area of the first rectangle const width1 = 10; const height1 = 6; const area1 = width1 * height1; // Area of the second rectangle const width2 = 4; const height2 = 9; const area2 = width2 * height2; // Area of the third rectangle const width3 = 10; const height3 = 10; const area3 = width3 * height3; In programming, we often use code to perform a specific task multiple times. Instead of rewriting the same code, we can group a block of code together and associate it with one task, then we can reuse that block of code whenever we need to perform the task again. We achieve this by creating a function.

what is the Switch keyword, how and when do you use it, what does it do, give examples

A switch statement provides an alternative syntax that is easier to read and write than tons of 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; } // Prints 'Papayas are $1.29' The switch keyword initiates the statement and is followed by ( ... ), which contains the value that each case will compare. Inside the block, { ... }, there are multiple cases. The case keyword checks if the expression matches. if it does it runs otherwise it keeps going down the list The value of groceryItem is 'papaya', so the third case runs The break keyword tells the computer to exit the block and not execute any more code if one runs.Note: Without break keywords, the first matching case will run, but so will every subsequent case regardless of whether or not it matches—including the default At the end of each switch statement, there is a default statement. If none of the cases are true, then the code in the default statement will run.

Arithmetic Operators

An operator is a character that performs a task in our code. Add: + Subtract: - Multiply: * Divide: / Remainder: %

String

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

Object

Collections of related data.

what does concatenate mean

Connect

What are Default Parameters, how and when to use them, give examples

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 set the default value of the parameter name to 'stranger' by using the = operator When the code calls greeting('Nick') the value of the argument is passed 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. By using a default parameter, we account for situations when an argument isn't passed into a function that is expecting an argument.

whats a typeof operator, how do you use it, and when do you, give example.

If you need to check the data type of a variable's value, you can use the typeof operator. The typeof operator checks the value to its right and returns, or passes back, a string of the data type. const unknown1 = 'foo'; console.log(typeof unknown1); // Output: string const unknown2 = 10; console.log(typeof unknown2); // Output: number const unknown3 = true; console.log(typeof unknown3); // Output: boolean

what are function declarations, how to/when to use them, give examples

Just like how a variable declaration binds a value to a variable name, a function declaration binds a function to a name, or an identifier. A function declaration is a function that is bound to an identifier, or name. A function declaration consists of: 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, { }.

what is truthy and falsy

Let's consider how non-boolean data types, like strings or numbers, are evaluated when checked inside a condition. 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. let myVariable = 'I Exist!'; if (myVariable) { console.log(myVariable) } else { console.log('The variable does not exist.') } The code block in the if statement will run because myVariable has a truthy value; which values are falsy— or evaluate to false when checked as a condition? 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 let numberOfApples = 0; if (numberOfApples){ console.log('Let us eat apples!'); } else { console.log('No apples left!'); } // Prints 'No apples left!' The condition evaluates to false because the value of the numberOfApples is 0

What is a built in Object, what are some of them, what do they do, give examples,

Math is a built in object. Built-in objects, including Math, are collections of methods and properties that JavaScript provides. These objects to various things (see mdn) Objects have methods. one built in object that uses a method is Math.random which prints a random number between 0 and 1. example: console.log(Math.random()); // Prints a random number between 0 and 1. in order to generate a random number thats higher we would add multiply by whatever we wanted so if we added a * 50 after the closing parenthesis we would get a random number between 0 and 50. other objects include Math.floor, Math.ceil, etc... Math.floor takes a decimal number and rounds down to the nearest whole number. you can use Math.floor and Math.random together like this: Math.floor(Math.random() * 50);

what are Properties and how to use them / write out a example

Properties are attached to strings, they can do things like tell you how many characters are in the string. You can retrieve property information by appending the string with a period and the property name example: console.log('Hello'.length); // Prints 5

whats the difference between properties and methods

Properties define it, while methods allow it to do things.

Truthy and Falsy shorthand

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: let username = ''; let defaultName; if (username) { defaultName = username; } else { defaultName = 'Stranger'; } console.log(defaultName); // Prints: Stranger If 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: let username = ''; let defaultName = username || 'Stranger'; console.log(defaultName); // Prints: Stranger 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.

what is the process of appending one string to another called?

String concatenation or just concatenation

String Concatenation with Variables. other words how do you connect strings/value of variables if they're stored in deferent areas

The + operator can be used to combine two string values even if those values are being stored in variables: let myPet = 'armadillo'; console.log('I own a pet ' + myPet + '.'); // Output: 'I own a pet armadillo.' we assigned the value 'armadillo' to the myPet variable. On the second line, the + operator is used to combine three strings: 'I own a pet', the value saved to myPet, and '.'. in short simple terms you just use the + operator

What are Concise body Arrow functions, how and when to use them, give examples

The most condensed form of the function is known as concise body examples: Zero parameters - const functionName = () => {}; One parameter - const functionName = paramOne => {}; Two or more parameter - const functionName = (paramOne, paramTwo) => {}; Single-line block - const sumNumbers = number => number + number; Multi-line block - const sumNumbers = number => {Const sum = number + number; Return sum; } 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. this is known as a implicit return. const squareNum = (num) => { return num * num; }; We can refactor the function to: const squareNum = num => num * num; the parentheses around num have been removed, since it has a single parameter. The curly braces { } have been removed since the function consists of a single-line block. The return keyword has been removed since the function consists of a single-line block.

what symbol is the remainder operator and what does it do. give a example with solution of how to use it

The remainder operator 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.

What are Function expressions, how and when to use them, give examples

To define a function inside an expression, we can use the function keyword. In a function expression, the function name is usually omitted. 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. const calculateArea = function (width, height) { const area = width * height; return area; } Declare a variable to make the variable's name be the name, or identifier, of your function. 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. variableName(argument1, argument2)

What is Return, how and when to use it, give examples

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. 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 function rectangleArea(width, height) { if (width < 0 || height < 0) { return 'You need positive integers to calculate area!'; } return width * height; } If an argument for width or height is less than 0, then rectangleArea() will return 'You need positive integers to calculate area!'. The second return statement width * height will not run. The return keyword is powerful because it allows functions to produce an output.

What are the different keywords and when/why are they preferred over each other

Var, let, const. the let keyword can me reassigned a different value. let meal = 'Enchiladas'; console.log(meal); // Output: Enchiladas meal = 'Burrito'; console.log(meal); // Output: Burrito you do not need to assign let a value right away. The const keyword cannot be reassigned a value because it is constant. const variables must be assigned a value when declared

what are Logical Operators, how to use, when to, give examples

We can 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 (!) When we use the && operator, we are checking that two things are true if (stopLight === 'green' && pedestrians === 0) { console.log('Go!'); } else { c onsole.log('Stop'); } 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 you only need one of the two conditions to be met (true) we can use the or operator || The ! not operator reverses the value of a boolean: let excited = true; console.log(!excited); // Prints false let sleepy = false; console.log(!sleepy); // Prints true 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 to add another layer of logic to our code

What are Helper Functions, how and when to use them, give examples

We can use the return value of a function inside another function. These functions being called within another function are 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. If we wanted to define a function that converts the temperature from Celsius to Fahrenheit, we could write two functions like: function multiplyByNineFifths(number) { return number * (9/5); }; function getFahrenheit(celsius) { return multiplyByNineFifths(celsius) + 32; }; getFahrenheit(15); // Returns 59 getFahrenheit() is called and 15 is passed as an argument. The code block inside of getFahrenheit() calls multiplyByNineFifths() and passes 15 as an argument. multiplyByNineFifths() takes the argument of 15 for the number parameter. The code block inside of multiplyByNineFifths() function multiplies 15 by (9/5), which evaluates to 27. 27 is returned back to the function call in getFahrenheit(). getFahrenheit() continues to execute. It adds 32 to 27, which evaluates to 59. Finally, 59 is returned back to the function call getFahrenheit(15). We can use functions to section off small bits of logic or tasks, then use them when we need to. Writing helper functions can help take large and difficult tasks and break them into smaller and more manageable tasks.

String Concatenation / create a chained String Concatenation

When a + operator is used on two strings, it appends the right string to the left string: console.log('hi' + 'ya'); // Prints 'hiya' example: console.log('One' + ', ' + 'two' + ', ' + 'three!'); // Prints 'One, two, three!'

What are Parameters and Arguments, how and when to use them, give examples

When declaring a function, we can specify its parameters. 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. function calculateArea (width, height) { console.log(width, height); } In the diagram above, calculateArea(), computes the area of a rectangle, based on two inputs, width and height. The parameters are specified between the parenthesis as width and height, and inside the function body, they act just like regular variables. width and height act as placeholders for values that will be multiplied together. When calling a function that has parameters, we specify the values in the parentheses that follow the function name. The values that are passed to the function when it is called are called arguments. Arguments can be passed to the function as values or variables. console.log(10, 6); In the function call above, the number 10 is passed as the width and 6 is passed as height. const rectWidth = 10; const recHeight = 6; calculateAre (rectWidth, rectHeight); The variables rectWidth and rectHeight are initialized with the values for the height and width of a rectangle before being used in the function call.

what are Comparison Operators, how to use, give examples

When writing conditional statements, sometimes we need to use different types of operators to compare values. 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 use comparison operators on different data types like strings: 'apples' === 'oranges' // false All comparison statements evaluate to either true or false

what is calling a function, how to/when to use, give examples

a function declaration does not ask the code inside the function body to run. The code inside a function body runs, or executes, only when the function is called. To call a function in your code, you type the function name followed by parentheses. function sayThanks() { console.log('Thank you for your purchase! We appreciate your business.'); } sayThanks(); - this calls the functions This function call executes the function body, or all of the statements between the curly braces in the function declaration. We can call the same function as many times as needed

If...Else Statements, what is it, how to use, give example.

add and if else statement after the if statement, by doing this the else if statement will run if the if statement does not. else statements are also reffered to as else statements. if (false) { console.log('The code in this block will not run.'); } else { console.log('But the code in this block will!'); } // Prints: But the code in this block will! else statement must be paired with an if statement, and together they are referred to as an if...else statement.

if statement, what is it, how to use, give example.

if (true) { console.log('This message will print!'); } // Prints: This message will print! he if keyword followed by a set of parentheses () which is followed by a code block indicated with {} Inside the parentheses (), a condition is provided that evaluates to true or false. (isnt always true or false) If the condition evaluates to true, the code inside the curly braces {} runs, or executes. if it evaluates to false it wont run or execute

Whats a conditional statement, give example

if we are tired, we go to bed, otherwise, we wake up and start our day. the condition is that were tired so were going to bed, but if the condition is that youre not tired were not gonna go to bed. A conditional statement checks a specific condition(s) and performs a task based on the condition(s).

what are The Increment and Decrement Operators and how do you use them, give example

increment operator (++) and decrement operator (--). increment operator will increase the value of the variable by 1. let a = 10; a++; console.log(a); // Output: 11 The decrement operator will decrease the value of the variable by 1. let b = 20; b--; console.log(b); // Output: 19

whats better to use String Concatenation or String Interpolation

industry standard is String Interpolations because it is easier to read than concatenation. You also don't have to worry about escaping double quotes or single quotes.

What is the Dot Operator and what does it to

its a period " . " it attaches properties to strings

What are Methods, How do you use them,

methods are actions you can perform. attaching .toUpperCase to a string will make it all uppercase example: console.log('hello'.toUpperCase()); // Prints 'HELLO' methods can modify/tell you true or false statements/selecet single letters/ etc.. example of true or false; console.log('Hey'.startsWith('H')); // Prints true

What are Arrow functions, how and when to use them, give examples

shorter way to write functions by using the special "fat arrow" () => notation. Arrow functions remove the need to type out the keyword function. include the parameters inside the ( ) and then add an arrow => that points to the function body surrounded in { } const rectangleArea = (width, height) => { let area = width * height; return area; };

what are Else If Statements, how to when to use, give examples

the else if statement allows for more than two possible outcomes. You can add as many else if statements as you'd like. ( you use it as back up options for the if statement incase it is false/doesn't execute) The else if statement always comes after the if statement and before the else statement. The else if statement also takes a condition. The else if statements allow you to have multiple possible outcomes. 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!'); }

what does interpolate mean

to insert

what is String Interpolation, how do you use it, what can you do with it, give example,

using string interpolation we can insert, variables into strings using template literals. const myPet = 'armadillo'; console.log(`I own a pet ${myPet}.`); // Output: I own a pet armadillo.

what are Variables, what can you do with them, give a example

variables label and store data in memory. Create a variable with a descriptive name. Store or update information stored in a variable. Reference or "get" information stored in a variable. var myName = 'Arya'; console.log(myName);// Output: Arya var creates a variable named myName, the value of myName is set to 'Arya'. (= is the assignment operator) the variable is declared by calling on it inside of the console.log - ex: console.log(myName); variables cannot start with numbers, variable names are case sensitive so myName and myname would be 2 different variables, variables cant be the same as keywords

what is a Ternary Operator, how and when to use, give examples

we can use a ternary operator to simplify an if...else statement. (short-hand) 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 shorter 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. which it is so turn on the lights will run 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.

How to use mathematical assignment operators, give examples

you can use variables and math operators to calculate new values and assign them to a variable. let w = 4; w = w + 1; console.log(w); // Output: 5 using built-in mathematical assignment operators. it would look like this let w = 4; w += 1; console.log(w); // Output: 5


Related study sets

1-Guide to Computer Forensics and Investigations

View Set

HAP lecture exam; urinary system

View Set

Art Appreciation Ch. 12 (Gothic art)

View Set

coursera spanish - Paleolithic & neolithic

View Set

Homework 16: Monopolistic Competition

View Set