Lecture: Variables
What is a Variable?
A good analogy is a labeled box. Outside is the label, inside is something, and it could be anything!
Officially:
A variable is a container. It has both a name and a value. You declare a new variable with the const or let keyword (more on that later), and assign it (aka give it) a value with the = sign.
const variableOne = 1;
const variableTwo = "Two";
const bensFavLanguage = "JavaScript";
console.log("Ben's favorite language is: " + bensFavLanguage);
// Ben's favorite language is: JavaScript
In JavaScript the value of a variable can change, but the name cannot.
However, this value can only change if you use let to declare your variable. const is, like its name implies, constant!
However, using let, you can re-assign variables with new values — even values from other variables.
const bensFavLanguage = "JavaScript";
let studentsFavLanguage = "French";
console.log("Student's favorite language was " + studentsFavLanguage);
// Student's favorite language was French
// .... after this lecture ....
studentsFavLanguage = bensFavLanguage;
console.log("Student's favorite language is " + studentsFavLanguage);
// Student's favorite language is JavaScript
Notice how in the code snippet above our second console.log statement is nearly identical to the first console.log statement but the output is drastically different since the value of the variable studentsFavLanguage has changed. In general, after you've declared a new variable, it can be used and reused as many times as you want.
As usual, the w3schools page on variables is a fantastic resource worth reading and visiting often.
Data Types
What's the difference between:
const label = "Do Not Disturb";
// and
const distance = 100;
The short answer is this: the first, const label, is a string, whereas the second, const distance, is a number. In JavaScript, data may have different types and each variable is used to represent a specific piece of data, complete with a type.
Numbers
Numbers are what you would expect them to be in the real world — numerical values that can be added, subtracted, multiplied, divided, etc.
// Examples
const radius = 5;
const g = 9.81; // decimals count as numbers
const piAsFraction = 22 / 7; // this is computed and stored as 3.142857142857143
We use the arithmetic (+,-,*,/) operators on numbers to do useful things like calculate someone's age or convert temperatures from Fahrenheit to Celsius.
Let's look at some examples.
// Examples
// calculating the circumference of a circle
const radius = 5;
const PI = 3.14;
// Note that we aren't actually changing the value of PI or radius with this console.log. They only change if we create them with let, and even then, we need an equals sign (=) to reassign them
console.log( 2 * PI * radius );
// converting F -> C
const F = 82;
// notice how parenthesis can be used for order of operations
let C = ( F - 32 ) / 1.8;
// QUESTION: what is stored inside the `C` variable?
console.log( C );
(Optional) Challenge: can you write an expression using variables that will take our C value and convert it back to the fahrenheit scale?
Strings
A string can be used to represent words and sentences. Anything wrapped in quotations (either double or single) will be represented as a string in javascript (even if the thing in quotes is a number).
Most arithmetic operators (-,*,/) do not work with strings. The + operator can be used to "add" or concatenate strings together.
Let's see this in action.
const firstName = "John"; // double quotes, this is string
const lastName = 'Smith'; // SINGLE quotes, still string
const fullName = firstName + " " + lastName; // John Smith
// notice how the '+' in this case combines three strings into one string
const stillAString = "2"; // this is still a string since wrapped in quotes
const invalid = "John Smith'; // NOTE: the quote TYPES mismatch, not kosher
Question: what would happen if you pasted the const invalid = "John Smith'; into repl.it?
Good Variable Names
Having good variable names is super important for you and others reading your code. You want the casing to be consistent across all the files in your project, and ideally consistent with the standards of the language. I like JavaScript Standard Style but not everyone has the same style. The most popular casing for variables in JavaScript is called "Camel Case" which starts with a lower case letter and only capitalizes the first letter of each internal word. Examples: myNumber, sortedPrimeNumbers, listOfBestPizzaInNyc.
You want your names to be as concise and as clear as possible. Being able to reason about what data is in a variable in the middle of a big and complicated program is important both for yourself and for when you share code. You will read more code than you will write as a programmer.
Best Practices
Variable names can contain:
- letters
- numbers
- underscores
- dollar signs
Variable names cannot contain:
- spaces
- dashes
- periods
Your variable names cannot start with a number. However, you may choose to start your variable names with letters (lowercased or uppercased based on your discretion), underscores, or dollar signs.
Here are some examples of bad and better variable names.
// BAD variable names
const 3.14isPi // can't start with number, can't have periods
const hello everyone! // space and '!' not allowed
const this-is-also-not-kosher-as-a-variable-name-for-use-later
// has dashes, OPINION: too long, concise names are better
// BETTER variable names
const pi // all lower cased, simple and succinct
const helloEveryone // 'camel cased': individual words are capitalized
const listOfAllUniqueNames // describes the type of data inside: a list
cosnt orderedListOfPrimeNumbers // describes the type and the organization: a sorted list
Evaluation / Execution of code
The word we use to describe turning a set of code into a single value is called evaluating or executing the code. This is useful to think about in situations where we assign the result of some math to a variable:
let x = 10;
let y = 20;
const someVariable = (100 * x / y) - x * y;
x = 0;
y = 0;
console.log(someVariable);
// -150
The value of some variable is decided at the moment of assignment when that line of code gets executed and the expression on the right side of the assignment gets evaluated. The point of this, fundamentally, is that JavaScript reads top-to-bottom, and with very few exceptions, won't backtrack to update values that have changed. Believe it or not, this is a good thing. It lets us change variables to update them without worrying about the previous code we've evaluated.
Useful and important syntax
let someNumber = 0;
const x = 5; // We'll use this later
//Increment: take a value and increase it by 1
someNumber = someNumber + 1;
someNumber += 1; // This and the above line can be any number
someNumber++;
++someNumber;
//Decrement: take a value and decrease it by 1
someNumber = someNumber - 1
someNumber -= 1 // This and the above line can be any number
someNumber--
--someNumber
//Multiply: take a value and multiply it by x
someNumber = someNumber * x;
someNumber *= x;
//Divide: take a value and divide it by x
someNumber = someNumber / x;
someNumber /= x;
(Optional) Challenge: what is the value of someNumber at the end of the above code snippet? Walk through each line of code and try to compute the value of someNumber yourself. Then, paste the snippet above into repl.it to check your answer.