Javascript Flashcards
How many data types are there in Javascript?
7.
Number, String, Boolean, Null, Undefined, Symbol Object
Operator
An operator is a character that performs a task in our code.
String Concatenation
Operators aren’t just for numbers! When a + operator is used on two strings, it appends the right string to the left string:
console.log(‘hi’ + ‘ya’); // Prints ‘hiya’
console.log(‘wo’ + ‘ah’); // Prints ‘woah’
console.log(‘I love to ‘ + ‘code.’)
// Prints ‘I love to code.’
.length
Use the .length property to log the number of characters in the following string to the console:
Ways to call methods
We call, or use, these methods by appending an instance with:
a period (the dot operator)
the name of the method
opening and closing parentheses
.toUpperCase
console.log(‘hello’.toUpperCase()); // Prints ‘HELLO’
Math.random
Math.random generates a random number between 0 and 1.
Math.floor()
Then, Math.floor() rounds the number down to the nearest whole number.
console.log().
Data is printed, or logged, to the console, a panel that displays messages, with console.log()
var
var, short for variable, is a JavaScript keyword that creates, or declares, a new variable.
myName
myName is the variable’s name. Capitalizing in this way is a standard convention in JavaScript called 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. (e.g. camelCaseEverything).
const entree = 'Enchiladas'; console.log(entree);
Proper syntax for constant variable console.log
var favoriteFood = ‘pizza’;
Declaring a variable syntax
Declaring a variable syntax
var favoriteFood = ‘pizza’;
var numofSlices = 8;
Syntax for assigning a number to a var (no’ ‘)
Declare a variable named numOfSlices using the var keyword and assign to it the number 8.
Syntax for assigning a number to a var (no’ ‘ marks like text)
Declare a variable named numOfSlices using the var keyword and assign to it the number 8.
var numofSlices = 8;
var favoriteFood = 'pizza'; console.log(favoriteFood);
How to properly console log a variable
How to properly console log a variable
var favoriteFood = 'pizza'; console.log(favoriteFood);
var favoriteFood = 'pizza'; console.log(favoriteFood);
var numOfSlices = 8; console.log(numOfSlices);
Console logging words vs. Console logging a var w/ numerical value
Console logging words vs. Console logging a var w/ numerical value
var favoriteFood = 'pizza'; console.log(favoriteFood);
var numOfSlices = 8; console.log(numOfSlices);
assign a var a boolean value
let changeMe = true
let changeMe = true
How to assign a var a bullian value
How to console.log a variable
let changeMe = false; console.log('changeMe')
let changeMe = false; console.log('changeMe')
How to console log a variable
let changeMe = true;
changeMe = false;
How to console log boolean value of variable (no need for lets or var considering that there is no need to declare a var before making changes
How to console log boolean value of variable (no need for lets or var considering that there is no need to declare a var before making changes
let changeMe = true;
changeMe = false;
const entree = ‘Enchiladas’;
Creating a constant variable syntax
Creating a constant variable syntaxconst entree = ‘Enchiladas’;
const entree = ‘Enchiladas’;
Proper syntax for constant variable console.log
const entree = 'Enchiladas'; console.log(entree);
const entree = 'Enchiladas'; console.log(entree);
Proper syntax for console logging constant
const entree = 'Enchiladas'; console.log(entree); entree = 'Tacos'
Causes error when attempting to change constant variable
Causes error when attempting to change constant variable
const entree = 'Enchiladas'; console.log(entree); entree = 'Tacos'
let w = 4; w += 1;
console.log(w); // Output: 5
+= Operator
+=Operator
let w = 4; w += 1;
console.log(w); // Output: 5
let experience = 18;
experience += 16;
console.log(experience); // Output: 34
Properly using += to change numeric value of a variable
Properly using += to change numeric value of a variable
let experience = 18;
experience += 16;
console.log(experience); // Output: 34
Increase Incriment
let a = 10;
a++;
console.log(a); // Output: 11
let a = 10;
a++;
console.log(a); // Output: 11
Increase Increment
let b = 20;
b–;
console.log(b); // Output: 19
Decrease in incriment
Decrease in increment
let b = 20;
b–;
console.log(b); // Output: 19
How to concatenate regular text with string value of variable
let favoriteAnimal = 'Phoenix'; console.log('My favorite animal: '+ favoriteAnimal);
let favoriteAnimal = 'Phoenix'; console.log('My favorite animal: '+ favoriteAnimal);
How to concatenate regular text with string value of variable
String Interpolation
In the ES6 version of JavaScript, we can insert, or interpolate, variables into strings using template literals. Check out the following example where a template literal is used to log strings together:
const myPet = 'armadillo'; console.log(`I own a pet ${myPet}.`); // Output: I own a pet armadillo.
In the ES6 version of JavaScript, we can insert, or interpolate, variables into strings using template literals. Check out the following example where a template literal is used to log strings together:
const myPet = 'armadillo'; console.log(`I own a pet ${myPet}.`); // Output: I own a pet armadillo.
String Interpolation
let newVariable = ‘Playing around with typeof.’;
console.log(typeof newVariable);
// Result is string
typeof operator
While writing code, it can be useful to keep track of the data types of the variables in your program. 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.
typeof operator
While writing code, it can be useful to keep track of the data types of the variables in your program. 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.
let newVariable = ‘Playing around with typeof.’;
console.log(typeof newVariable);
// Result is string
let newVariable = ‘Playing around with typeof.’;
console.log(typeof newVariable);
newVariable = 1;
console.log(typeof newVariable);
Result is
String
Number
Proper protocol for adding a set variable to an unset number
const kelvin = 293; // Setting Kelvin as constant const celsius = kelvin -273;
const kelvin = 293; // Setting Kelvin as constant const celsius = kelvin -273;
Proper protocol for adding a set variable to an unset number
const kelvin = 293; // Setting Kelvin as constant const celsius = kelvin -273; // Declaring celsius and converting from kelvin const fahrenheit = celsius * (9 / 5)+32; // Declaring fahrenheit and converting from celsius6
Thermometer Code
fahrenheit = Math.floor(fahrenheit);
Proper example of using Math.floor object
Proper example of using Math.floor
fahrenheit = Math.floor(fahrenheit); // Math floor (Math being the object .floor being the method)
String Interpolation syntax
const kelvin = 293; // Setting Kelvin as constant const celsius = kelvin -273; // Declaring celsius and converting from kelvin let fahrenheit = celsius * (9 / 5) + 32; // Declaring fahrenheit and converting from celsius6 fahrenheit = Math.floor(fahrenheit);
// Math floor (Math being the object .floor being the method)
console.log(The temperature is ${fahrenheit} degrees Fahrenheit.
);
const kelvin = 293; // Setting Kelvin as constant const celsius = kelvin -273; // Declaring celsius and converting from kelvin let fahrenheit = celsius * (9 / 5) + 32; // Declaring fahrenheit and converting from celsius6 fahrenheit = Math.floor(fahrenheit);
// Math floor (Math being the object .floor being the method)
console.log(The temperature is ${fahrenheit} degrees Fahrenheit.
);
String interpolation syntax
let myName = 'Leon David'.toLowerCase(); console.log(myName);
Proper use of built in method .toLowerCase
Proper use of built in method .toLowerCase
let myName = 'Leon David'.toLowerCase(); console.log(myName);
//Output leon david
What is the outcome of this statement?
console.log(‘hi!’.length);
3 is Printed to the console
Proper if else syntax based on Boolean value
let sale = true;
sale = false;
if(sale) {
console.log(‘Time to buy!’);}
else { console.log(‘Time to wait for a sale.’);
}
let sale = true;
sale = false;
if(sale) {
console.log(‘Time to buy!’);}
else { console.log(‘Time to wait for a sale.’);
}
Proper if else syntax based on Boolean value
Comparison Operators
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
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
===
String comparison
Ex. ‘apples’ === ‘oranges’ // false
‘apples’ === ‘oranges’
String comparison with false Boolean value
let hungerLevel = 7;
if(hungerLevel > 7) { console.log('Time to eat!'); } else { console.log('We can eat later!'); };
If Else example (No need to specify inverse of if condition in this example)
Working with conditionals means that we will be using booleans, true or false values. In JavaScript, there are operators that work with boolean values known as logical operators. 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 (!)
Logical Operator
Logical Operator
Working with conditionals means that we will be using booleans, true or false values. In JavaScript, there are operators that work with boolean values known as logical operators. 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 (!)
Working with conditionals means that we will be using booleans, true or false values. In JavaScript, there are operators that work with boolean values known as logical operators. 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 (!)
Logical Operator
&& Operator
When we use the && operator, we are checking that two things are true:
if (stopLight === 'green' && pedestrians === 0) { console.log('Go!'); } else { console.log('Stop'); }
When we use the && operator, we are checking that two things are true:
if (stopLight === 'green' && pedestrians === 0) { console.log('Go!'); } else { console.log('Stop'); }
&& Operator
let mood = 'sleepy'; let tirednessLevel = 6;
if (mood === 'sleepy' && tirednessLevel > 8) { console.log('time to sleep'); } else { console.log('not bed time yet'); }
Proper && Syntax w/ a numerical value
Truthy 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; 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.
Falsy Values
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
Truthy Vs. Falsy Example
let wordCount = 0; wordCount = 5
if (wordCount) { console.log("Great! You've started your work!"); } else { console.log('Better get to work!'); } // Truthy
let favoritePhrase = ‘’;
if (favoritePhrase) { console.log("This string doesn't seem to be empty."); } else { console.log('This string is definitely empty.'); } //Falsy
let wordCount = 0; wordCount = 5
if (wordCount) { console.log("Great! You've started your work!"); } else { console.log('Better get to work!'); } // Truthy
let favoritePhrase = ‘’;
if (favoritePhrase) { console.log("This string doesn't seem to be empty."); } else { console.log('This string is definitely empty.'); } //Falsy
Truthy vs. Falsy example
let wordCount = 0; wordCount = 5
if (wordCount) { console.log("Great! You've started your work!"); } else { console.log('Better get to work!'); } // Truthy
let favoritePhrase = ‘’;
if (favoritePhrase) { console.log("This string doesn't seem to be empty."); } else { console.log('This string is definitely empty.'); } //Falsy
let tool = ‘’;
// Use short circuit evaluation to assign writingUtensil variable below: let writingUtensil = tool || 'pen'
console.log(The ${writingUtensil} is mightier than the sword.
);
// Output The pen is mightier than the sword.
Example of use of the || operator states the var then changes name of var and value. In this instance it turns writing utensil into a string
Ternary Operator Syntax
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 isLocked = false;
isLocked ? console.log(‘You will need a key to open the door.’) : console.log(‘You will not need a key to open the door.’);
let isLocked = false;
isLocked ? console.log(‘You will need a key to open the door.’) : console.log(‘You will not need a key to open the door.’);
Ternary Operator
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!’);
Create using Ternary Operator
let isNightTime = true;
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!”);
Ternary Operator with Comparison Operator
Ternary Operator with Comparison Operator
let favoritePhrase = ‘Love That!’;
favoritePhrase === ‘Love That!’ ? console.log(‘I love that!’)console.log(“I don’t love that!”);
Else ifs in appropriate Syntax
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.’);
}
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.’);
}
Else if in appropriate Syntax
The switch keyword
else if statements are a great tool if we need to check multiple conditions. In programming, we often find ourselves needing to check multiple values and handling each of them differently. For example:
else if statements are a great tool if we need to check multiple conditions. In programming, we often find ourselves needing to check multiple values and handling each of them differently. For example:
The switch keyboard
Switch Keyword single appropriate syntax
let athleteFinalPosition = ‘first place’;
switch(athleteFinalPosition){
case ‘first place’:
console.log(‘You get the gold medal!’);