Skip to content

Variable

Variables hold reusable data in a program and associate it with a name. They are stored in memory.

Create a variable

let is the preferred way to declare a variable when it can be reassigned, and const is the preferred way to declare a variable with a constant value.

JavaScript
let meal = 'Enchiladas';
console.log(meal); // Output: Enchiladas
meal = 'Burrito';
console.log(meal); // Output: Burrito

const myName = 'Gilberto';
console.log(myName); // Output: Gilberto

We can declare a variable without assigning the variable a value. In such a case, the variable will be automatically initialized with a value of undefined:

JavaScript
let price;
console.log(price); // Output: undefined
price = 350;
console.log(price); // Output: 350

Info

The var keyword is used in pre-ES6 versions of JS.

Mathematical Assignment Operators

Mathematical assignment operators make it easy to calculate a new value and assign it to the same variable. Try +=, -=, *=, /=, ++ and -- to see what it does.

String Concatenation with Variables

The + operator can be used to combine two string values even if those values are being stored in variables:

JavaScript
let myPet = 'armadillo';
console.log('I own a pet ' + myPet + '.'); 
// Output: 'I own a pet armadillo.'

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:

JavaScript
const myPet = 'armadillo';
console.log(`I own a pet ${myPet}.`);
// Output: I own a pet armadillo.

Template literals use backticks \` and ${} to interpolate values into a string.

Typeof Operator

The typeof keyword returns the data type (as a string) of a value.

JavaScript
const unknown1 = 'foo';
console.log(typeof unknown1); // Output: string

const unknown2 = 10;
console.log(typeof unknown2); // Output: number

const unknown3 = true; 
console.log(typeof unknown3); // Output: boolean