Javascript Variables - How to declare variables in different ways in JavaScript ?



Javascript Variables

  • 4 Ways to Declare a JavaScript Variable
    • Using var
    • Using let
    • Using const
    • Using nothing

What are Variables

  • Variables are containers for storing data (storing data values).

Var Keyword

In this example, a, b, and c, are variables, declared with the var keyword.

javascript-var-variable

Sample Code

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Variables</h1>

<p>In this example, a, b, and c are variables.</p>

<p id="demo"></p>

<script>
var a = 4;
var b = 10;
var c = a + b;
document.getElementById("demo").innerHTML = "The value of c is: " + c;
</script>

</body>
</html>

Output

JavaScript Variable
In this example, a, b, and c are variables.
The value of c is: 14

let Keyword

In this example, x, y, and z, are variables, declared with the let keyword.

javascript-let-variable
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Variables</h2>

<p>In this example, x, y, and z are variables.</p>

<p id="demo"></p>

<script>
let x = 5;
let y = 6;
let z = x + y;
document.getElementById("demo").innerHTML = "The value of z is: " + z;
</script>
</body>
</html>

Output

JavaScript Variables
In this example, x, y, and z are variables.
The value of z is: 11

In this example, x, y, and z, are undeclared variables.

Sample Code

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Variables</h1>
<p>In this example, x, y, and z are undeclared variables.</p>
<p id="demo"></p>
<script>
x = 5;
y = 6;
z = x + y;
document.getElementById("demo").innerHTML = "The value of z is: " + z;
</script>

</body>
</html>

Output

JavaScript Variables
In this example, x, y, and z are undeclared variables.
The value of z is: 11

When to Use JavaScript var ?

  • Always declare JavaScript variables with var,let, or const.
  • The var keyword is used in all JavaScript code from 1995 to 2015.
  • The let and const keywords were added to JavaScript in 2015.
  • If you want your code to run in older browsers, you must use var.

When to Use JavaScript const ?

  • If you want a general rule: always declare variables with const.
  • If you think the value of the variable can change, use let.
  • In this example, p1, p2, and total, are variables:

Const Keyword

Sample Code

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Variables</h1>

<p>In this example, p1, p2, and total are variables.</p>

<p id="demo"></p>

<script>
const p1 = 5;
const p2 = 6;
let total = p1 + p2;
document.getElementById("demo").innerHTML = "The total is: " + total;
</script>

</body>
</html>

Output

JavaScript Variables
In this example, p1, p2, and total are variables.
The total is: 11

Related Searches to Javascript Variables - How to declare variables in different ways in JavaScript ?