Variables #
Declare #
var #
var declares a new variable. = is the assignment operator.
var someVar = 'something or other';
console.log(some_var);
// outputs 'something or other'
^ convention for variable naming is camel case.
let #
Newer way of assigning a variable than var.
Advantage over var: variable can be re-assigned later on.
let favoriteFood = 'apple';
console.log(favoriteFood);
// outputs 'apple'
favoriteFood = 'banana';
console.log(favoriteFood);
// outputs 'banana'
Can also create a variable without assigning anything:
let favoriteFood; // that's it
const #
another way to do it, const is short for “constant”.
Difference from let - const can’t be re-assigned later on AND must be assigned a value upon creation.
Math #
Mathemetical operators can be used with variable assignment.
let thing = 1;
thing = thing + 1;
console.log(thing); // outputs 2
Another way to increment is with +=:
let thing = 1;
thing += 1; // same as above
Other operators:
*=-=/=++- increment (e.g.,someVar++;)--- decrement (e.g.,someVar--;)
Strings #
Concatenation #
Use +.
let stringVar = 'Sup';
console.log('stringVar' + ' cat')
Interpolation #
Use template literals to interpolate (insert) strings. Syntax: ${variable} in the middle of a string, all wrapped by back-ticks.
let animal = 'turtles';
console.log(`I like ${animal}.`); // note the back-ticks
Super readable.
Types #
Variables have types (numerical, string, bool, etc). typeof shows the variable type.
const something = 1;
console.log(typeof something);
Rules #
Variables are:
- case sensitive
- can’t start with numbers
- can’t be keywords