JavaScript Variable | How to Declare and Use Variables in JavaScript

In JavaScript, a variable is used to store data that can be referenced and manipulated later. JavaScript provides several ways to declare variables, such as using var, let, and const.

Types of Variables in JavaScript:

Syntax of Variable Declaration in JavaScript:

Syntax


var myVar = 5; // Using var to declare a variable
let myLet = 10; // Using let to declare a variable
const myConst = 20; // Using const to declare a constant

Example of Variable Declaration using var:

This example demonstrates how to declare and use a variable with var in JavaScript.

Example 1


var age = 30;
console.log(age); // Output: 30

Output:

30

Example of Variable Declaration using let:

This example demonstrates how to declare and use a variable with let in JavaScript.

Example 2


let number = 100;
console.log(number); // Output: 100

Output:

100

Example of Variable Declaration using const:

This example demonstrates how to declare and use a constant with const in JavaScript. Constants cannot be reassigned after their initial value is set.

Example 3


const pi = 3.14;
console.log(pi); // Output: 3.14

Output:

3.14

Why Use Variables in JavaScript?

Best Practices for Using Variables in JavaScript:

Common Mistakes to Avoid: