Home HTML CSS JavaScript React Gamedatum.com
× Home HTML CSS JavaScript React Gamedatum.com

JS Variables


What's a JavaScript Variable?

The JavaScript Variable is a way of storing data that you can use in your programming. In JavaScript there are three ways to declare your variables:

The Variable declarations must be used correctly as they have their own restrictions.

  • var
  • let
  • const

The Var

The Javascript Var (along with the Let variable) is the most common way of declaring data values in JavaScript.

With this type of variable we can redeclare the variable without losing its value.

For example:
               
                
<script> 
 var myvariable;
 var myvariable = "Hello, I'm a variable value";
 </script>
                
                
              

The let

Unlike the Var keyword, the let keyword cannot be redeclared. This variable type has a Block or Function specific scope (inside a { } block).

               
                
<script>                   
function totalSum(){
let x = 2;
let y = 4;
let amount = x + y;
document.getElementById("test").innerText = amount; 
</script>
}
<button onclick="totalSum();">click me</button>


                
                
              
The output:

The const

The const keyword is smiliar to the oher two (var, let) but its value cannot be changed.

The const variable can be used by more than one functions.

A good practise is to declare the name of your cost variables in capital letters. This will help you and other developers to distinguish the const variables and wont change them by mistake manually.

               
                
<script>                   
function total(){
const year1 = 1902;
const year2 = 2010;
let diff = year2 - year1;
document.getElementById("test2").innerText = diff;
</script>
}
<button onclick="total();">click me</button>