JavaScript Tutorial – Variables

In this tutorial, you will learn about JavaScript variables and how to declare, initialize and use variables in JavaScript applications.

What Are JavaScript Variables?

A variable is storage for data value and the date value can be changed later on.

How to Declare JavaScript Variables

Variables can be declare using any of the 3 reserved keywords, var, let and const. There are 3 rules for JavaScript variable naming convention:

  • Variable names must start with a letter, underscore, or dollar sign.
  • A variable name cannot be the same as the reserved keywords.
  • Variable names are case-sensitive. For example, Hello and hello are two different variables.

Examples of JavaScript Variable Declaration

	
		var x;
		let y;
		const z; 
	

If you plan to use a long name for your variables, make sure they follow camelCase.

Examples of camelCase Naming Convention

	
		let name;
		let myName;
		let ourFirstName; 
	

How to Initialize JavaScript Variables

All the variables we declared so far are undefined. This is because we didn’t initialize their values yet. To initialize a variable, you just need to add an equal sign (=) to the right of the variable name and assign a value.

For example, the following example declares a variable called name and initializes it to “Jay”:

	
		let name;
		name = "Jay";
	

Can you also declare and initialize the variable on the same line:

	
		let name = "Jay";
	

How to Change Value of a Variable

Once you initialize a variable, you can change its value by assigning a different value. For example:

		
			let name = "Jay";
			name = "Jack";
			document.write(name); 
		
	

What is Constant Variable in JavaScript

A constant variable is a variable that holds a value that does not change. You can use the keyword const to declare a constant variable. Once a constant is defined, you cannot change its value.

	
		const site = "WhatAboutHTML";