Variables are essential in all programming languages. They are used to store data, such as text strings, numbers, and more. The data or value stored in variables can be set, updated, and retrieved whenever needed. In essence, variables are symbolic names for values.
You can create a variable using the var
keyword, and the assignment operator (=
) is used to assign a value to a variable, like this: var varName = value;
var name = "Peter Parker";
var age = 21;
var isMarried = false;
Tip: Always assign meaningful names to your variables. Additionally, for variables with multiple words, camelCase is commonly used. In this convention, all words after the first start with an uppercase letter, e.g., myLongVariableName
.
In the above example, we created three variables: the first one is assigned a string value, the second one a number, and the last one a boolean value. Variables can hold different types of data, which we'll learn about in a later chapter.
In JavaScript, variables can also be declared without assigning any initial values. This is useful for variables that are meant to hold values like user inputs.
// Declaring Variable
var userName;
// Assigning value
userName = "Clark Kent";
Note: In JavaScript, if a variable has been declared but not assigned a value explicitly, it is automatically assigned the value undefined
.
Moreover, you can declare multiple variables and set their initial values in a single statement. Each variable is separated by commas, as shown in the following example:
// Declaring multiple Variables
var name = "Peter Parker", age = 21, isMarried = false;
/* Longer declarations can be written to span
multiple lines to improve the readability */
var name = "Peter Parker",
age = 21,
isMarried = false;
ES6 introduces two new keywords let
and const
for declaring variables.
The const
keyword functions just like let
, except that variables declared with const
cannot be reassigned later in the code. Here's an example:
// Declaring variables
let name = "Harry Potter";
let age = 11;
let isStudent = true;
// Declaring constant
const PI = 3.14;
console.log(PI); // 3.14
// Trying to reassign
PI = 10; // error
Unlike var
, which declares function-scoped variables, both let
and const
keywords declare variables scoped at the block level ({}
). Block scoping means that a new scope is created within a pair of curly brackets {}
. We'll delve into this concept further in the JavaScript ES6 features chapter.
Note: The let
and const
keywords are not supported in older browsers like IE10. IE11 partially supports them. Refer to the JS ES6 features chapter to learn how to begin using ES6 today.
Here are the rules for naming a JavaScript variable:
_
), or dollar sign ($
).A-z
, 0-9
), and underscores.Note: Variable names in JavaScript are case-sensitive, meaning $myvar
and $myVar
are treated as two distinct variables. Therefore, be cautious when defining variable names.