Skip to content

Try our new Crash Courses!

Buy one of our new Crash Courses, now hosted on Podia.

Variables – JavaScript

Summary

To create a variable in JavaScript, use the let keyword:

let myVariable = "This is a variable";

Details

A variable in JavaScript lets you store a value. Unlike a constant, you’re allowed to change the value of a variable multiple times after it has been initialized.

A variable is set using the let keyword. A value is assigned to the variable using the equals sign.

Here is an example of creating a variable on one line and assigning it a value on a different line:

let myVariable;
myVariable = "This is a variable";

Here is an example of creating a variable and assigning it a value on the same line:

let myVariable = "This is a variable";

Here’s an example of assigning a value to a variable and then changing its value:

let myVariable = "This is a variable";
myVariable = "This is a new value";

Notice that you don’t need to include the let keyword when changing the variable’s value. You only need the variable’s name. If you use the let keyword again, you’ll get an error.

let myVariable = "This is a variable";
let myVariable = "This is a new value"; // This will generate an error!

You can use variables to hold many different types of values: strings, numbers, booleans, arrays, objects, etc.

After you’ve created a variable and assigned it a value, you can refer to it just using its name. Here’s an example of using a variable with console.log():

console.log(myVariable);

This will print out the value stored inside the variable.

Naming convention

In JavaScript, variable and constant names are written using camelCase. If a variable name is just a single word, the name is written in lowercase letters, like this:

let name = "John Smith";

If a variable name is composed of multiple words, then the first word is written in lowercase letters while the first letter of each subsequent word is capitalized, like this:

let myFirstName = "John";

undefined

If you try to use a variable that has been declared but has not been given a value, the browser will tell you the value is undefined.

let myVariable;
console.log(myVariable);
// output: undefined

The var keyword

The let keyword is a relatively new addition to JavaScript. In the past, developers used the var keyword to declare variables in JavaScript. Currently, you should use let in your JavaScript projects, though you may still see var used in older articles or code bases.

Demo

Exercises

Try the following statements in the console:

let myVariable = 10
myVariable = 11

References

let statement on MDN

Back to: JavaScript Reference > JS Basic Syntax