JavaScript for Beginners

1.Var

  • Function-scoped (not block-scoped)
  • Can be redeclared and updated
  • Not recommended for modern code

 

Example:

 

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Variables</h1>

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

<p id=”demo”></p>

<script>
var x = 5;
var y = 6;
var 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

 

2. Let

  • Block-scoped
  • Cannot be redeclared in the same scope
  • Can be updated

 

Example :

 

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Variables</h1>

<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

 

3. Const

  • Block-scoped
  • Cannot be redeclared or reassigned
  • Must be initialized when declared

 

Example: 

 

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Variables</h1>

<p>In this example, price1, price2, and total are variables.</p>

<p id=”demo”></p>

<script>
const price1 = 5;
const price2 = 6;
let total = price1 + price2;
document.getElementById(“demo”).innerHTML =
“The total is: ” + total;
</script>

</body>
</html>

 

Output

JavaScript Variables

In this example, price1, price2, and total are variables.

The total is: 11 

 

Description :

In JavaScript, a variable is a container for storing data values. Variables allow you to store and manipulate data in your program. Each variable is given a name (known as the identifier) and a value.

Variables can store different types of data, such as numbers, strings, objects, or even more complex structures like arrays and functions.