Variables
Variables are used whenever there’s a need to store a piece of data. A variable contains data that can be used in the program elsewhere. Using variables also ensures code re-usability since it can be used to replace the same value in multiple places.
const currency = '$';let userIncome = 85000;console.log(currency + userIncome + ' is more than the average income.');
The code above produces the following output:
$85000 is more than the average income.
Codebyte Example 1
Run the following codebyte example to understand the usage of variables in JavaScript:
Declaring a Variable
To declare a variable in JavaScript, any of these three keywords can be used along with a variable name:
var
is used in pre-ES6 versions of JavaScript. It is function scoped.let
is the preferred way to declare a variable when it can be reassigned. It is block scoped.const
is the preferred way to declare a variable with a constant value. It is also block scoped.
var age;let weight;const numberOfFingers = 20;
Codebyte Example 2
Run the following codebyte example to understand how to declare variables in JavaScript:
Dynamic Typing
Unlike many programming languages, JavaScript doesn’t require the user to specify a variable’s data type. It assumes the data type based on the value. The example below assigns a string to a variable by enclosing some numbers in single quotation marks. Without them, JavaScript reads the value as a number.
let movieTitle = '300'; // Stringlet audienceNumber = 300; // Number
Video Walkthrough
Watch this video for a description on what JavaScript variables are and how to use them to store values.
All contributors
- smiosso
- sczerman
- Anonymous contributor
- Anonymous contributor
- christian.dinh
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.