Variables and Constant in JavaScript

In the JavaScript, if we want to store a single piece of information then we use variables and constant. In this tutorial, we will deep dive in this topic.

What you will learn?

  • What is a Variable?
  • Declaring Variables
  • Variables Naming Convention
  • Common Errors While Declaring Variables
  • Changing Variables Values
  • Const Keyword
  • Var Keyword

Let’s Start,

What is a Variable?

Any software application we write contains data. Application needs to perform some business logic on data & for that it needs to be stored in the computer memory. Variables help us to store data in the memory.

For Example:

Color, Name, Age etc. Suppose, you want to store Age data then it requires computer memory. Basically this data is stored in the memory address which is complicated to read & remember.

So the computer language which you are using makes it easy for you by using Variables. We store data in variable & that variable points internally to the computer memory address.

You can set (save) and get (retrieve) data/values using variables.

Declaring Variables

‎‎‎
let color = "Green";
let price = 250;
let flag  = true;
‎

In the above example, you can see we have declared 3 variables. color contains string, price contains number & flag contains Boolean (True or False) values. JavaScript automatically interprets type of data stored in the variable.

In the languages like C# and Java we have data types specific to their data. For example int or double use to store numbers, string use to store word/sentence/numbers, bool use to store Boolean value etc.

But in the JavaScript, We have let, const & var data types. These data types automatically interprets type of data. We’ll talk about them later.

Other Way to Declare Variables

You can declare variables using comma also. In the below example you can see that we have written let type only once and declared variables comma separated.

‎‎‎
let color = "Green",
    price = 250,
    flag  = true;
‎

Note: To keep code clean use earlier example.

Variables Naming Convention

It’s not only about declaring variables but it is also good to follow naming conventions. If you don’t follow naming convention, then JavaScript is NOT going to throw any Errors or Warnings at you BUT to keep code clean and readable, it is good to follow them.

Let’s look at some of naming conventions for variables.

Convention 1: Starting of Variable Name

You can start variable name with underscore (_), $, letter (lower or uppercase) & Unicode character.

Convention 2: Followed by Number or Any

After first character you can use underscore (_), $, letter (lower or uppercase), number & Unicode character.

Note: If you start variable name with a number then JavaScript engine will get confused between number and variable name & it will throw you an error.

Examples of variable names adhere to above conventions.

Suppose you want to store a account number. Let’s see how we write variable names for that & how some characters has different meaning for that variable.

  • account_number or accountNumber or accountnumber are three best way to to describe name for account number variable name.
  • Don’t use single character (Example a) to describe variable name. It is difficult to read and maintain. Always avoid single character name while declaring variables.
  • _accountNumber or _accountnumber. This type of naming convention (starting with underscore) you can use when your want to declare private variables. It denotes that variable is private.
  • $accountNumber. This type of naming convention (starting with dollar) generally we use for auto generated code. It can be use by IDE or plugins for auto generated code. Not much use in user define code.
  • _123. This is very non-descriptive. DO NOT declare this type of variable names.
  • _accountnumber_. This type of variables (Underscore at start & end) used for non-standard features.

Keep in the mind that best variable names are those who can describe the data without any confusion.

If there is any problem with variable naming convention, JavaScript Engine or your IDE will let you know. Still, lets see some of the errors you may come up with while declaring variables.

Common Errors While Declaring Variables

Example 1:

‎
let 999account = 457894;
‎

When you run the above code you can see below error in the browser console. Because variable name is started with a number which leads JavaScript engine to confusion.

Uncaught SyntaxError: Invalid or unexpected token

Note: Above error you can see in the Chrome Browser. Error description may differ browser to browser.

Example 2:

‎
let account number = 457894;
‎

In the about code you can see that there is a space between variable name. Variable should not contain any space in between characters otherwise JavaScript engine will throw an error. You will get below error in the Chrome Browser.

Uncaught SyntaxError: Unexpected identifier

Example 3:

‎
let let = 457894;
‎

In the above example you can see that we have used (let) Reserved Word(s) as a variable name. You cannot use them. JavaScript will throw below error.

Uncaught SyntaxError: let is disallowed as a lexically bound name

Example 4:

‎
let price;
console.log(price);
‎

Above code will not throw an error. But if you see the output in the console, it will show undefined warning. It is always good to assign value before you use the variable.

These are some errors you can avoid easily if you write variables as per the given conventions.

Changing Variable Values

Changing variables value is very easy. You just need to re-assign new value & it will get change/override/alter. Let’s see the example.

‎
let number = 999;
console.log(number);
‎

It is a very simple example. We are just declaring number variable with initial value of 999. If you see output in console you will get 999. Now, in the next example we will change value 999 to 555.

‎
let number = 999;
number = 555;
console.log(number);
‎

Here you can see we have used already declared variable (number) and we have assigned new value to it. If you see output in the console you will get 555 value.

You can also left variable unassigned and then assign value to it before using. Let’s see below example.

‎
let number;
number = 555;
console.log(number);
‎

You can see we left variable number unassigned BUT at the next line we have assigned value to it, because on the 3rd line we are using the variable. So always remember to assign value to the variable before using it otherwise you will get value undefined error.

Note: Above variable changing explanation doesn’t apply to the const type. It only works with var & let. Why? We’ll learn this in next point about constant.

Const (Constant) Keyword

If variable is NOT going to change then it should be declared as const (Constant). For example value of pi is 3.14. It is not going to change and it shouldn’t be change by anyone accidently. So in this case instead of let or var we should use const.

Let’s see example.

‎
const pi = 3.14;
console.log(pi);
‎

As you can see, we have declared const pi & assigned value to it immediately. You CAN’T change its value like shown in the “changing variable names” section above. Also, you CAN’T even left const variable unassigned and assign value before using it. JavaScript engine will throw you an error in the both cases.

Always remember to assign value to const when you declare it.

Var Keyword

let & const are relatively new keywords to JavaScript than var. Let’s see the example, why we should prefer to use let or const instead of var.

Example with var

‎
console.log(price);
var price = 100;
‎

If you see output of above code in the console then you will get no value or undefined in the browser. In common sense it should have thrown error because we are using value before declaration.

That’s why, if you use var then it will be confusing and prone to error in a complicated code. Let’s see the same example with let.

‎
console.log(price);
let price = 100;
‎

If you use let and see the output in the console then you will get below error.

Uncaught ReferenceError: Cannot access ‘price’ before initialization

which clearly says that, you cannot use price because it is not initialized.

Always use let over var keyword. It gives you more control over code. Read difference between var, let & const in more detail.

We hope you have understood how to use variables and constant. In the next topic, we will learn Types and Operators in JavaScript in detail.

Categories js

Subscribe Now!

Subscribe Us For Latest Articles