Javascript Flashcards
What is a console?
The console is a panel that displays important messages, like errors, for developers. If we want to see things appear on our screen, we can print, or log, to our console directly.
console.log()
When we write console.log() what we put inside the parentheses will get printed, or logged, to the console. This is important so we can see the work that we’re doing.
What are the two types of code comments in Javascript?
A single line comment and a multi-line comment
How do you write a single line comment?
// + comment
Note: You can also write a single line comment after a line of code.
How do you write a multi-line comment?
/* to begin the comment, and / to end the comment.
Note: you can also use this syntax to comment something out in the middle of a line of code.
Ex: console.log(/IGNORED!*/ 5); // Still just prints 5
When is it a good time to use multi-line comments?
When preventing a block of code from running.
What are data types? How many fundamental data types are there?
Data types are the classifications we give to the different kinds of data that we use in programming. There are 7 fundamental data types.
What are the seven different fundamental data types?
Number, string, boolean, null, undefined, symbol, and object.
What is a string data type?
Any grouping of characters on your keyboard (letters, numbers, spaces, symbols, etc.) surrounded by single quotes: ‘ … ‘ or double quotes “ … “
What is a boolean data type?
A data type that only has two possible values- true or false. You can think of it as answers to a “yes” or “no” question.
What is a null data type?
This data type represents the intentional absence of a value, and is represented by the keyword null
What is an undefined data type?
Uses the keyword undefined (without quotes) and means that a given value does not exist. It represents the absence of a value like null but is used differently.
What is an object data type?
Collections of related data.
What is an operator?
An operator is a character that performs a task in our code.
Examples:
Arithmetic Operators
Assignment Operators
Comparison Operators
Logical Operators
What is the keyboard symbol for the multiply operator?
- Ex: 7 * 3 = 21
What is the keyboard symbol for the division operator?
/
Ex: 9/3 = 3
What is the keyboard symbol for the remainder operator?
%
console.log(11 % 3); // Prints 2
What is the remainder operator sometimes called?
modulo
What is string concatenation?
Combining one string to another string use the + operator.
Ex: console.log(‘hi’ + ‘ya’); // Prints ‘hiya’
How would we include space in between two strings when we are using string concatenation?
We have to include empty parenthesis in between them or space at the end or beginning of a string.
Ex:
console.log(‘front ‘ + ‘space’);
// Prints ‘front space’
console.log(‘back’ + ‘ space’);
// Prints ‘back space’
console.log(‘no’ + ‘space’);
// Prints ‘nospace’
console.log(‘middle’ + ‘ ‘ + ‘space’);
// Prints ‘middle space’
What are properties?
Properties are the values associated with a JavaScript object.
What is the symbol used for the dot operator?
.
Ex: console.log(‘Hello’.length); // Prints 5
What are methods?
A method is a function that belongs to some object or a set of some instructions that performs a certain task.
How do we use or “call” methods?
We call, or use, methods by attaching an instance with:
a period (the dot operator)
the name of the method
opening and closing parentheses
Ex:’example string’.methodName().
Ex: console.log(‘hello’.toUpperCase()); // Prints ‘HELLO’
.random()
This method returns a random number between 0 (inclusive) and 1 (exclusive). Math.random() always returns a number lower than 1.To generate a random number between 0 and 50, we could multiply this result by 51, like so:
Math.random() * 51;
Math.floor()
This method takes a decimal number, and rounds down to the nearest whole number.
Ex:
Math.floor(Math.random() * 50);
Math.ceil()
The Math.ceil() function always rounds up to the nearest integer.
Ex:
console.log(Math.ceil(.95));
// expected output: 1
Ex:
console.log(Math.ceil(4));
// expected output: 4
console.log(Math.ceil(7.004));
// expected output: 8
Number.isInteger()
method determines whether the passed value is an integer.
Ex:
console.log(Number.isInteger(2017))
//Prints true
How can we access properties and methods?
We can access properties and methods by using the ., dot operator.
What is a variable?
A variable is a container for a value. They are like little containers for information that live in a computer’s memory. You can have container, label it, and put “stuff” in it.
What three things can we do with variables?
- Create a variable with a descriptive name.
- Store or update information stored in a variable.
- Reference or “get” information stored in a variable.
var
var, short for variable, is a JavaScript keyword that creates, or declares, a new variable.
Ex:
var myName = ‘Arya’;
console.log(myName);
// Output: Arya
What is myName when creating a variable?
This would be the variable name (labeling the container). It is standard convention to use camel casing.
Ex:
var myName = ‘Arya’;
console.log(myName);
// Output: Arya
What is camel casing?
In camel casing you group words into one, the first word is lowercase, then every word that follows will have its first letter uppercased.
Ex:
camelCaseEverything
What is the = sign when creating a variable?
= is the assignment operator. It assigns the value (‘Arya’) to the variable (myName).
Ex:
var myName = ‘Arya’;
console.log(myName);
// Output: Arya
What are some important rules when naming variables?
- Variable names cannot start with numbers.
- Variable names are case sensitive, so myName and myname would be different variables. It is bad practice to create two variables that have the same name using different cases.
- Variable names cannot be the same as keywords.
let
The let keyword signals that the variable can be reassigned a different value.
Ex:
let meal = ‘Enchiladas’;
console.log(meal); // Output: Enchiladas
meal = ‘Burrito’;
console.log(meal); // Output: Burrito
What happens when we don’t assign a value to variable (var or let)?
If we don’t assign a value to a variable declared using the let keyword, it automatically has a value of undefined.
We can reassign the value of the variable.
Ex:
let price;
console.log(price); // Output: undefined
price = 350;
console.log(price); // Output: 350
const
The const keyword is short for the word constant. Just like with var and let you can store any value in a const variable.
Ex:
const myName = ‘Gilberto’;
console.log(myName); // Output: Gilberto
How are const different from let and var?
a const variable cannot be reassigned because it is constant. If you try to reassign a const variable, you’ll get a TypeError. Constants must also be assigned a value when declared. If you try to declare a const variable without a value, you’ll get a SyntaxError.
How can we use variables and math operators to calculate new values and assign them to a variable?
- We can create a variable and assign a number value to it (let w = 4) and then we can reassign it a new value by using the math operators to perform a calculation (w = w + 1).
- We can also use the built-in mathematical assignment operators.
Ex:
let w = 4;
w += 1;
console.log(w); // Output: 5
Explain the following line of code:
let w = 4
w +=1;
console.log(w); //Output: 5
- We create a variable and assign the value 4.
- We perform the mathematical operation of the first operator + using the number to the right (w + 1)
- Then we reassign w to the computed value.
++
The increment operator will increase the value of the variable by 1.
Ex:
let a = 10;
a++;
console.log(a); // Output: 11
–
The decrement operator will decrease the value of the variable by 1.
How can we combine two string values even if those values are being stored in variables?
By using the + operator
Ex:
let myPet = ‘armadillo’;
console.log(‘I own a pet ‘ + myPet + ‘.’);
// Output: ‘I own a pet armadillo.’
What is string interpolation?
String interpolation is when we insert, or interpolate, variables into strings using template literals.
Ex:
const myPet = ‘armadillo’;
console.log(I own a pet ${myPet}.
);
// Output: I own a pet armadillo.
What is a temperate literal wrapped in?
Backticks ` (this key is usually located on the top of your keyboard, left of the 1 key).
Ex:
const myPet = ‘armadillo’;
console.log(I own a pet ${myPet}.
);
// Output: I own a pet armadillo.
${…}
template literal syntax that allows you to interpolate variables and expressions into strings.
Ex:
const myPet = ‘armadillo’;
console.log(I own a pet ${myPet}.
);
// Output: I own a pet armadillo.
How can we check the data type of a variable’s value?
We can check the data type of a variable’s value by using the typeof operator.
Ex:
const unknown1 = ‘foo’;
console.log(typeof unknown1); // Output: string
const unknown2 = 10;
console.log(typeof unknown2); // Output: number
W/hat are conditional statements?
A conditional statement checks a specific condition(s) and performs a task based on the condition(s).
if() {}
Syntax for if statement
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 (true) {
console.log(‘This message will print!’);
}
// Prints: This message will print!
What are else statements?
Else statements run a block of code when the if statement evaluates to false.
An else statement must be paired with an if statement, and together they are referred to as an if…else statement.
What are comparison operators?
Comparison operators compare the value on the left with the value on the right.
Ex:
10 < 12 // Evaluates to true
What are some handy comparison operators?
Less than: <
Greater than: >
Less than or equal to: <=
Greater than or equal to: >=
Is equal to: ===
Is not equal to: !==
What is the syntax for the identity operator?
===
Ex:
‘apples’ === ‘oranges’ // false
What are logical operators?
Operators that work with boolean values.There are three logical operators:
the and operator (&&)
the or operator (||)
the not operator, otherwise known as the bang operator (!)
&&
When we use the and (&&) operator, we are checking that two things are true. 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.
Ex:
if (stopLight === ‘green’ && pedestrians === 0) {
console.log(‘Go!’);
} else {
console.log(‘Stop’);
}
||
We use the or operator (II) when we only care about either condition being true. If the first condition in an || statement evaluates to true, the second condition won’t even be checked.
Ex:
if (day === ‘Saturday’ || day === ‘Sunday’) {
console.log(‘Enjoy the weekend!’);
} else {
console.log(‘Do some work.’);
}
!
The not operator or bang operator (!) Reverses, or negates, the value of a boolean. The ! operator will either take a true value and pass back false, or it will take a false value and pass back true.
Why do we use logical operators?
We use logical operators to add another layer of logic to our code.
What are truthy values?
A truthy value is a value that is considered true when encountered in a Boolean context. All values are truthy unless they are defined as falsy.
All values are truthy unless they are defined as falsy. That is, all values are truthy except false, 0, -0, 0n, “”, null, undefined, and NaN.
What are falsy values?
Falsy value are values that are considered false when encountered in a Boolean context. The following are considered falsy values:
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
What is short-circuit evaluation?
Short-circuit evaluation is when each operand is converted to a boolean, gets evaluated from left to right, and if the operand is true (or false with and && operator) JavaScript with short-circuit and not even look at the second operand.
Ex:
let username = “ ‘’;
let defaultName = username || ‘Stranger’;
console.log(defaultName); // Prints: Stranger
What are ternary operators?
Ternary operators are short- hand syntax for if-else statements. We use a ? followed by :
Ex:
let isNightTime = true;
if (isNightTime) {
console.log(‘Turn on the lights!’);
} else {
console.log(‘Turn off the lights!’);
}
Using ternary operator:
isNightTime ? console.log(‘Turn on the lights!’) : console.log(‘Turn off the lights!’);
What are else if statements?
Else if statements are added to if else statements and allow you to add more than two possible outcomes for a conditional statement.The else if statement always comes after the if statement and before the else statement.
Ex:
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 are switch statements?
Switch statements execute a block of code if the value entered into the switch keyword matches the case it’s being compared to. Switch statements can replace multiple else if statements. depending on different cases.
What is a case clause?
A case clause used to match against an expression. If the value and the expression match, then the block of code will be executed.
What does the break keyword do?
The break keyword tells the computer to exit the block and not execute any more code.
What is the difference between type conversion and type coercion?
Type conversion is when we manually convert from one type to another. Type coercion is when JavaScript automatically converts types behind the scenes for us.
Example: Converting a string to a number
const inputYear = ‘1991’;
console.log(Number(InputYear));
console.log(Number(inputYear) + 18);
What are functions?
A function is a reusable block of code that groups together a sequence of statements to perform a specific task.
What is strict mode and the syntax to use it?
Strict mode is a special mode that we can activate in JavaScript, which makes it easier for us to write a secure JavaScript code. By secure we mean strict mode makes it easier for us to avoid accidental errors. It also stops us from using potential future keywords.
Syntax:
‘use strict’;
Must be first line of code (Comments before are ok).
What are the rules for type coercion?
- When we add a number and a string the number automatically is converted to a string.
- When we subtract a number and a string the string is converted to a number.
- When we multiply/divide strings are automatically converted to numbers.
4.
What is NaN
NaN stands for not a number. However, its data type is number. NaN is for an invalid number.
What are function declarations?
a function declaration binds a function to a name, or an identifier. Important: A function declaration does not ask the code inside the function body to run, it just declares the existence of the function. The code inside a function body runs, or executes, only when the function is called.
Ex:
function greetWorld() {
console.log(‘Hello, World!’);
}
What makes up a function?
- 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, { }.
Ex:
function greetWorld() {
console.log(‘Hello, World!’);
}
How do you call a function?
To call a function in your code, you type the function name followed by parentheses.
We can call the same function as many times as needed.
What are arguments (functions)?
Arguments are the values that are passed to a function when it is called. Arguments can be passed to the function as values or variables.
Ex:
calculateArea(10, 6);
What are 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.
What are return statements?
The return statement ends function execution and specifies a value to be returned to the function caller. When we do not use the return keyword when calling a function we receive an undefined valued will be returned.
What are helper functions?
Helper functions are functions that are called within other functions.
Ex:
function multiplyByNineFifths(number) {
return number * (9/5);
};
function getFahrenheit(celsius) {
return multiplyByNineFifths(celsius) + 32;
};
getFahrenheit(15); // Returns 59
What are function expressions?
A function expression is very similar to and has almost the same syntax as a function declaration. The main difference is that with function expressions the function name can be taken out to create an anonymous function (function without a name).A function expression is often stored in a variable in order to refer to it.
Ex:
cons calculateArea = function(width, height) {
const area = width * height
}
How do you declare a function expression?
- Declare a variable to make the variable’s name be the name, or identifier, of your function. (Using const is common practice)
- 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.
Ex:
cons calculateArea = function(width, height) {
const area = width * height
}
How do you invoke a function expression?
Use the variable name in which the function is found and parenthesis that have the arguments to be passed in the function.
Ex:
variableName(argument1, argument2)