JavaScript Variables

JavaScript variables are used to store data that can be used and changed while a program is running. A variable acts like a container that holds a value such as a number, text, or result of an operation. You can use this value later in your code whenever you refer to the variable name.

A variable is created by giving it a name and assigning it a value. This allows your program to remember information and work with it across different parts of your code. Variables make programs flexible and dynamic instead of hardcoding values everywhere.

Naming Rules

Variable names in JavaScript must follow certain rules:

  • Must start with a letter, underscore (_), or dollar sign ($)
  • Cannot start with a number
  • Can contain letters, numbers, underscores, and dollar signs
  • Are case-sensitive, so total and Total are different variables
  • Cannot use JavaScript reserved keywords as names
Naming Styles

There are different ways variable names are written to keep code clean and readable.

Camel Case:

This is the most common style in JavaScript. The first word starts with a lowercase letter, and each new word starts with an uppercase letter.
Example: userName, totalScore

Snake Case:

Snake case is a naming style where words are written in lowercase and separated by underscores. It is used to make variable names easy to read when they contain multiple words. Example: user_name.

Pascal Case:

Starts every word with an uppercase letter. This style is often used for class names.
Example: UserName, TotalScore