Create a variable with a variable declaration In JavaScript

Create a variable with a variable declaration In JavaScript

 






To use a variable in code, you must create one. This is called declaring a variable.


In JavaScript, declaring a variable is as simple as using the let keyword, followed by the chosen variable name:

let numberOfCats = 2;
let numberOfDogs = 4;

Here, we declare (create) and initialize (give a value to) two variables:  numberOfCats and  numberOfDogs.

Practice creating variables!

Head to CodePen Exercise P1CH2a and follow the instructions below to practice creating and initializing two variables.

You will create two variables which are needed by a component built by your colleague. Together, you are building the list view for TV shows, and each TV show needs a variable for the number of seasons that show has, and the number of episodes there are in each season.

Your colleague requests that you name these variables numberOfSeasons and numberOfEpisodes in order to be compatible with their code.

  1. Create a variable called numberOfSeasons and assign it the value 6 between the lines created for you in the JavaScript editor (the tab labeled "JS"). Remember to use the let keyword, and don't forget the semicolon at the end of the line!

  2. Next, create a variable called numberOfEpisodes, and assign it the value 12.

Solution:

Once you've given it a go, watch me code a solution and see how your approach compares. And here is a new CodePen with a solution to the exercice.

Disclaimer: In many JavaScript demos, you may come across the keyword var instead of  let. While there is one subtle difference between the two (which we will explore in our chapter on scoping), for now you can simply think of  var as the older version of  let: it is another way of creating a variable.