Edit Template
  • Home
  • /
  • Variable Naming Rules
Edit Template
  • Home
  • /
  • Variable Naming Rules

Variable Naming Rules

JavaScript is a dynamically typed language. That means you don’t have to specify whether a variable holds a number, a string, or anything else when you declare it—the type is figured out automatically based on what value you assign.

For example:

				
					var x = 10;        // x is a number
var y = "hello";   // y is a string
var z = [1, 2, 3]; // z is an array

				
			

Pretty flexible, right?

Now let’s talk about naming variables properly.

Rules for Naming Variables

There are a few essential rules you must follow:

  • Names can only contain letters, numbers, underscores _, or dollar signs $.

  • Names must not begin with a number.

  • Variable names are case-sensitive. So myVar and MyVar are two different variables.

And here’s a tip from every good programmer:

Use clear, meaningful names. Avoid names like x, y, or data unless you’re just experimenting or the context is obvious.

Good example:

				
					let userAge = 25;


				
			

Not-so-good example:

				
					let a = 25;

				
			

Using Variables in JavaScript

Once you’ve declared a variable, you can use it to store and retrieve values at any time.

Here’s a simple example:

				
					var x = 10;
console.log(x); // prints: 10

x = "hello";
console.log(x); // prints: hello

				
			

As you can see, JavaScript allows you to change the value and type of x on the fly.

You can also perform operations on variables. Here’s how:

Example: Math

				
					var x = 10;
var y = 20;
var sum = x + y;
console.log(sum); // prints: 30


				
			

Example: Strings

				
					var str1 = "hello";
var str2 = "world";
var combined = str1 + " " + str2;
console.log(combined); // prints: hello world

				
			
Scroll to Top