JavaScript Variables

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'; // note that there's no `let` this time
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

Destructing #

Shortcuts to assign properties to variables (like for functions).

So rather than being explicit like so:

const someFunction = (param1, param2) => {
    return {
        param1: some_value1,
        param2: some_value2
    }
}

The same thing can be expressed as the following without naming the keys:

const someFunction = (param1, param2) => {
    return {
        some_value1,
        some_value2
    }
}

^ A bit lazier, a bit less explicit, but it works just the same.

Destructured Assignment #

Simple way to pull key-value pairs from objects and save to variables.

Destructing involve a structure like:

const {someKey} = someObject; // assign to object

It also works with nested key-values:

const {someNestedKey} = someOject.someKey;

For instance, something like this:

const somePerson = {
    name: 'Bob',
    age: 20,
    city: 'Hartford'
}

const city = somePerson.city;
console.log(city); // returns 'Hartford'

Can become something like this with destructing:

// assume the same somePerson object as above
constant {city} = somePerson;

^ This is briefer, lazier.