JavaScript Variables

Variables help you store data values. You can modify, delete, and access this data whenever you want.

JavaScript offers you 3 keywords var, let, and const to declare variables. To assign value to a variable, an equal sign is used.

Ensure a variable always has a meaningful name. Use the camelCase to name variables that have multiple words. The camelCase convention makes it mandatory for all words after the first to have capital first letters, e.g. myNewVariable

Example:

.lang-js
let a;

a= 9;

If you declare a variable but don’t assign a value, the value undefined gets automatically assigned.

How can you declare multiple variables all together?

JavaScript allows you to declare multiple variables all together, separated by a comma.

Example:

var name = "John Smith", class = 2, gender =”male”;

or

var name = "John Smith",

class = 2,

gender =”male”;

What is the difference between let and const keywords?

The let and const keywords work similarly. However you cannot reassign the variables declared using the const keyword.

Rules for naming JavaScript variables

  • A variable name should start with a letter, underscore (_), or dollar sign ($).

  • A variable name cannot begin with a number.

  • A variable name can only have alpha-numeric characters (A-z, 0-9) and underscores.

  • A variable name should not contain spaces.

  • You cannot have a JavaScript keyword or reserved word as a variable name.