Declaring Variables and Setting Their Values - jpjohnsonjr/learning-notes GitHub Wiki
const and let
There are two basic ways to declare variables:
const — Short for constant, a JavaScript keyword that creates a new variable with a value that cannot change. The typical naming convention for constants is myName. This is known as camelCasing because the capital letters look like camel humps. A declaration might look like this:
const myName = 'Arya';
console.log(myName);
The = is the assignment operator. The variable value is Arya in this case. Other examples:
const entree = 'Enchiladas';
const price = 12;
let — Creates a new variable with a value that can be changed.
Example: The following will throw an error message:
const entree = 'Enchiladas';
entree = 'Tacos';
This will return the error `TypeError: Assignment to constant variable'. The following would not:
let meal = `Enchiladas`
console.log(meal);
meal = `Tacos`;
console.log(meal);
Setting a Boolean Value
Examples:
let changeMe = true;changeMe = false;
Creating an Undefined Variable
It is also possible to create a variable but not assign a value; JavaScript will create space for the variable in memory and set it to undefined, which is the fifth and final primitive data type. Example:
let notDefined;
console.log(notDefined);
Mathematical Assignment Operators
Example:
let x = 4;
x = x + 1;
The above creates the variable x and then increases its value by 1. Other operators:
let x = 4;
x += 2; // x now equals 6
let y = 4;
y -= 2; // y now equals 2
let z = 4;
z *= 2; // z now equals 8
let r = 4;
r++; // r now equals 5 (incremented by 1)
let t = 4;
t--; // t now equals 3 (decremented by 1)
String Interpolation
String interpolation in the term in JavaScript for inserting data saved to a variable into a string. The + operator is used to interpolate, as shown:
let myPet = 'armadillo';
console.log('I own a pet ' + myPet + '.');
// Output: 'I own a pet armadillo.'
Newest version of JavaScript also allows this to be done this way:
console.log(`I own a pet ${myPet}.`);
Not necessary to use the + operator or close and re-open the string using this technique, but must use backticks instead of single quotes (`);