JavaScript: Variable and Constant [ includes var vs let vs const ]

A variable is a named identifier of a storage/space in the memory. The variable represents and points to some space in memory, so we can change the variable value, and the value/content in the pointed memory is changed.

We can use the variable as many times as we want, after the declaration.

In this article, we are discussing JavaScript naming process and the process of defining a variable.

Variable Naming

Naming the variable is very important, as that name will be used in different places in the code. So we should know the rules of declaring a variable name, and also how to define a good & meaningful name of the variable.

Allowed Variable Names

Here is how we can define a valid variable name-

  • The name must only contain letters, numbers/digits, and the symbols – dollar sign($) and underscore(_). Here are some variable names-
    • name
    • age
    • firstName
    • first_name
    • customerId
    • customer_id
    • customer$id
    • $customer_name
    • my$var$with$dollar$sign
    • $varStartedWithDollarSign
    • _varStartedWithUnderscore
    • __varWithDoubleUnderscore
    • my_var_with_underscore
    • my3var1with9number
    • 5varStartedWithNumber
  • A dollar sign($) and an underscore(_) is a valid variable name. The following variable names are valid-
    • $ = 100
    • _ = “my sign here”
  • Non-Latin characters are allowed in the variable name. The following are valid variable names-
    • переменная
    • 变量
    • मेरी_पहचान
    • আমার_ভেরিয়েবল
    • 내변수

Not Allowed Variable Name

The following are not allowed in a variable name in JS.

  • The first character can not be a number/digit. The first letter should be a letter, or symbol($ or _).
  • A variable name can not contain any sign other than “$” or “_“. Like, these are invalid variable names – big-box-var, my*wrong#var@name, etc.
  • Reserved keywords, like – let, var, const, function, return, etc. are not allowed as a variable name.

Variable Naming Recommendation

  • A variable name should be meaningful and represent the purpose of the variable usage.
  • By convention, a variable name should start with a small letter.
  • If the name contains multiple words then use a camelCase for the naming, like- firstName, streetAddress, totalAmount, isInputValid.
  • Variable names are case-sensitive. So, firstName, FirstName, fIrStNaMe, etc. are completely different variable names, and represent.
  • Though non-Latin characters are allowed in the variable name, but using those characters is not recommended. As using those characters can cause some readability issues for non-native software engineers.

Variable Declaration

There are 2 ways we can declare a variable in JavaScript-

  • var
  • let

let” is the preferred way of declaring a variable.
Use “var” if you need it in some cases. Be aware of the scope and side effects of using both types of variable declaration.

Variable Declaration with “let

Let’s check how we can declare variables with “let” and what are the different uses of those variables. Here we are discussing case by case.

Case #1: Declare a Variable

We can define a variable with “let” by typing a valid variable name after let. There should be at least a space between the let keyword and the variable name.

// Declare a variable
let firstName;

// Check variable just after declaring it
console.log("Fist Name before value assignment: " + firstName);

// Later we can assign the value of the variable
firstName = 'Lucienne';

// Check the value after declaration
console.log("Fist Name after value assignment: " + firstName);

Output:

Fist Name before value assignment: undefined

Fist Name after value assignment: Lucienne

Case #2: Declare and Assign Value

We can declare a variable and assign a value at the same time. Use “let”, then at least a space, then the variable name. Then put an equal sign(=) and write the value of the variable.

// Declare variable and define at the same time
let lastName = "O'Keefe";

// Check value
console.log(lastName);

Output:

O'Keefe

Case #3: Change Variable Value

We can change the variable as many times as required, after declaration-

// Declare and define variable
let country = "United States";

// Check value
console.log(country);


// Change value to Canada
country = "Canada";

// Check latest value
console.log(country);


// Change value to France
country = "France";

// Check latest value
console.log(country);


// Change value to Japan
country = "Japan";

// Check latest value
console.log(country);


// Change value to Germany
country = "Germany";

// Check latest value
console.log(country);

Output:

United States

Canada

France

Japan

Germany

Case #4: Declare Multiple Variable

We can declare multiple variables using the same “let” statement-

// Declare multiple variables
let city, state, zip;

// Check the values
console.log("Values just after declaration-")
console.log("City: " + city);
console.log("State: " + state);
console.log("Zip: " + zip);


// Assign values
city = 'Troutdale';
state = 'Oregon';
zip = '97060';

// Check the values
console.log("Values after assignment-")
console.log("City: " + city);
console.log("State: " + state);
console.log("Zip: " + zip);

Output:

Values just after declaration-
City: undefined
State: undefined
Zip: undefined

Values after assignment-
City: Troutdale
State: Oregon
Zip: 97060

Case #5: Declare and Set Multiple Variable

Let’s declare multiple variables and assign values at the same time-

// Declare multiple variables and assign value
let address = '3265 SW Sundial Ave',
    phone = '(503) 405-9520';

// Check the values
console.log("Address: " + address);
console.log("Phone Number: " + phone);

Output:

Address: 3265 SW Sundial Ave
variables:7 Phone Number: (503) 405-9520

Case #6: [Error] Declare Same Variable Multiple Times

We can not declare variables with the same name multiple times. Declaring the same variable names multiple times will throw an error-

let customerId = 101;

console.log(customerId);

// Declare variable with the same name
let customerId = 77;

console.log(customerId);

Output:

Uncaught SyntaxError: Identifier 'customerId' has already been declared

Variable Declaration with “var

Variable declaration process using “var” is the same as “let. The difference between variables declared “var” and “let” is in the scope of the declared variable.

Let’s see how we can declare variables with “var” keyword-

Case #1: Declare Variables

Declaring a variable with “var” has the same rule as let. The same naming conversion and same declaration process should be followed-

// Declare a variable
var customerName;

// Print customerName
console.log("Fist Name before value assignment: " + customerName);

// Change customerName
customerName = 'Lucienne';

// Print customerName again
console.log("Fist Name after value assignment: " + customerName);


// Declare multiple variables at the same time
var address = '3265 SW Sundial Ave',
    phone = '(503) 405-9520';

// Check the values
console.log("Address: " + address);
console.log("Phone Number: " + phone);

Output:

Fist Name before value assignment: undefined
Fist Name after value assignment: Lucienne

Address: 3265 SW Sundial Ave
Phone Number: (503) 405-9520

Case #2: Declare Same Variable Multiple Times

We can define a variable with the same name using “var”-

// Define a variable
var bigBoxVar = 99;

console.log(bigBoxVar);

// Define a variable with same name
var bigBoxVar = 100;

console.log(bigBoxVar);

Output:

99
100

Constant Declaration

A constant also follows the same naming rules as a variable, the only difference is a constant can not be changed once assigned.

Case #1: Declare Constant

Use the keyword “const” to declare a constant. We can use the constant using the declared name, after the declaration-

const bigBoxConst = 1001;

console.log(bigBoxConst);

Output:

1001

Case #2: [Error] Try to Change Constant

If we try to change the value of the constant, we get an error-

const bigBoxConst = 1001;

console.log(bigBoxConst);

// Try to use assign a value to constant after defining it
bigBoxConst = 9988;

console.log(bigBoxConst);

Output:

1001
Uncaught TypeError: Assignment to constant variable.

Case #3: [Error] Try to Declare and Assign Separately

Value of the constant need to be assigned in the same line. We can not first declare and assign value in a separate line.

const bigBoxConst;

bigBoxConst = 9988;

console.log(bigBoxConst);

Output:

Uncaught SyntaxError: Missing initializer in const declaration

Case #4: Change a Constant Object Property

Elements like an object can defined as a const, but as the object assignment is by references. So we can add property and add new property to the object, even if it is a constant-

const customer = {
    name: "Wyman Abshire",
    state: "California",
    zip: "94538",
    country: "United States",
}

console.log(customer);

// Add new property to a constant object
customer.street = "39407 Fremont Blvd";
customer.city = "Fremont";

console.log(customer);

// Change existing property of constant object
customer.city = "New Rochelle";
customer.state = "North Dakota";
customer.zip = "10801";
customer.phone = "(914) 813-0344";

console.log(customer);

// We can change the property of the object
// But we can not reassign any new object or other value to the constant
// The following are not allowed, and will throw error
//customer = {};
//customer = "abc";

Output:

{
    "name": "Wyman Abshire",
    "state": "North Dakota",
    "zip": "10801",
    "country": "United States",
    "street": "39407 Fremont Blvd",
    "city": "New Rochelle",
    "phone": "(914) 813-0344"
}

{
    "name": "Wyman Abshire",
    "state": "North Dakota",
    "zip": "10801",
    "country": "United States",
    "street": "39407 Fremont Blvd",
    "city": "New Rochelle",
    "phone": "(914) 813-0344"
}

{
    "name": "Wyman Abshire",
    "state": "North Dakota",
    "zip": "10801",
    "country": "United States",
    "street": "39407 Fremont Blvd",
    "city": "New Rochelle",
    "phone": "(914) 813-0344"
}

Case #5: Change a Constant Array Elements

We can change items of a constant array-

const productIds = [101, 99];

console.log(productIds);

productIds.push(1001, 2002, 3333);

console.log(productIds);

// We can change the elements of the constand array
// But we can not reassign any new array or other value to the constant
// The following are not allowed, and will throw error
//productIds = {};
//productIds = "abc";

Output:

[101, 99]
[101, 99, 1001, 2002, 3333]

var“, “let” and “const” Comparison

Let’s take a look at the differences between variables or constants declared using “var“, “let” and “const“.

CriteriavarletconstNotes
Default valueundefinedundefinedThere is no default valueA constant needs to be initialized
explicitly during the declaration.
Declare without initializationYesYesNoNot initializing a constant duration
the declaration will throw an error.
Change value after declarationYesYesNo
Redeclaration allowedYesNoNo
HoistedYesNoNoOnly variables declared with “var
are hoisted to the top of the scope.
Binds “this”YesNoNo
ScopeGlobal
Function
BlockBlockGlobal scope– this means the full scope, which stays at the top layer.
Function scope– only inside that function.
Block scope– defined by the curly braces “{}“. “{” = start, “}” = end.

You can check the details of JavaScript variable and constant scope from the link below-

Check details of JavaScript variable and function hoisting, from the link-

Also, check the details usage and scope of the “this” keyword, from the link below-

Leave a Comment


The reCAPTCHA verification period has expired. Please reload the page.