Javascript Fundamental: Variables

All applications work with data. We need to store this data somewhere, for example, eCommerce application has data regarding products, users, cart, etc. Variables are used to store this information. Let us study variables in detail.

JavaScript Variables

According to w3schools variables are containers for storing data. We can imagine them as a container with a label on it and in the container, we can store numbers, strings, objects, and other data.

let product;
let product;
product = 'watch';
// abbreviation
let product = 'watch';
var person = "John Doe", carName = "Volvo", price = 200;
var person = "John Doe",
carName = "Volvo",
price = 200;

The Assignment Operator

In javascript = is an assignment operator, not an equals operator. Means whenever we use = we assign a variable value not check if it is equal to another thing. Using this assignment operator we can reassign a value of a variable for example

let product = 'clothes';
product = 'shoes';
alert(product); // Gives popup with shoes written on it

Defining constants

Using let we can declare variables that can change but what if we want to declare variables that remain constant. For that, we can use the const keyword. Variables declared using const have a constant value and will throw an error if we try to reassign it.

const bestseller = 'watch';
bestseller = 'clothes'; // will throw an error

Javascript Identifiers

All variables should be defined with a name these names are called javascript identifiers but naming variables has some rules.

  1. Names must begin with a letter
  2. Names can also begin with $ and _ (but we will not use here)
  3. Names are case sensitive (y and Y are different variables)
  4. Reserved words (like JavaScript keywords) cannot be used as names

Naming right

We should be very careful while naming our variables, our variables should convey what we are trying to achieve by storing that information in a variable. What info does this variable contain? We often keep editing old code so if the variables are named well than editing code gets very easy which saves a lot of man-hours. So, naming variables right has real economic value.

  1. Stay away from abbreviations or short names like a, b, c, unless we really know what we’re doing.
  2. Make names maximally descriptive and concise. Examples of bad names are data and value. Such names say nothing. It’s only okay to use them if the context of the code makes it exceptionally obvious which data or value the variable is referencing.
  3. Agree on terms within our team and in our own minds. If a site visitor is called a “user” then we should name related variables currentUser or newUser instead of currentVisitor or newManInTown.

Front End Developer