Programming is all about manipulating and displaying data, which can be any kind of information used in computer programs, such as social media usernames, age, and profile photos. To work with this data and create interesting things, programmers need a way to store and keep track of it. This is where the concept of variables comes in.

A variable is an essential concept in almost every programming language, and there is much to know and understand about it.

In this post, we will explore almost all of the concepts related to variables in programming, but from a beginner's perspective. We will keep things simple to understand, and use simple examples.

Even if you are new to programming and don't have much knowledge about JavaScript, you will be able to understand all the concepts we cover.

So, let's get started!

Table of Contents

Variables in javascript

In JavaScript, a variable is a named reference to a memory location that can hold different types of data, such as numbers, strings, booleans, objects, or functions. To access or modify the data stored in a variable, we use its name.

It's a little confusing, right?

let's have a look at the computer memory. If you have a basic understanding of computer memory then you must know that Computer memory has millions of cells on it and every cell has its own address.

In our program, if we want to store value to access it later throughout the program, we have to keep it somewhere in the computer memory and we will need a way to call that value whenever we need to. We could have done that using the memory address after storing the data in the memory. The problem is we can't use this address directly in our program because the computer works in the binary system and in the binary system, this memory address looks too weird and confusing. Also, it's almost impossible to memorize.

This is where Variables come in.

We can simply create a variable and assign it to the value we want to store. Now we don't need to memorize the weird and confusing memory address we can do the same using a simple and human-readable name.

When we are creating a variable and assigning a value to it, behind the scenes, the Compilers and interpreters store the data inside the memory and replace the symbolic names of variables with the real data location/memory address.

That means our data is stored in memory and the variable is pointing to this memory location.

Note: In real scenarios, memory allocation is not as simple as I discussed here. also, Primitive type and Reference type values are treated differently when assigning them to variables in javascript. but for this post, I have avoided the advanced things and kept it simple so you can get an overall idea of how things work behind the scenes.

If you are still confused by it, simply think of variables as named containers that hold information and can be referred to the data simply by naming the container.

That means,

Think of these steps as

Note: A Javascript variable is a container, not a value, this means that variables aren’t themselves values; they are a named container for values.

Declaring Variables

Before you use a variable in a JavaScript program, you must create it, we call this declaring a variable.

We can Declare a JavaScript Variable using var or `let` :

var name; 
let age;

Here we are creating two variables, one using var and one using let.

var and let are the keywords that tell JavaScript you’re declaring a variable.

Name and Age are the names of those variables.

In Javascript, Semicolons(;) are totally optional (unless you want to have multiple statements in a single line, of course). (similar to a full stop(.) in the English language.)

Note: Though Semicolons(;) are optional in javascript, there are many languages where Semicolon(;) is a big factor. In those languages you must end the line using a semicolon otherwise will occur an error to your program.

You can also declare multiple variables with the same var or `let` keyword:

var name, age;
let birthYear, address;

There is another keyword to declare variables in javascript which is const. This is used to declare the constant variables in javascript.

const  Pi = 3.1416

We will talk about this in another blog post.

Naming Variables

In Javascript as well as all other languages, variables must be identified with unique names following some rules and regulations. These unique names are called identifiers. These Identifiers or names can be short (like `a`, `b`, and `c`) or more descriptive (`age`, `name`, `userName`).

Rules for variable Name

There are some general rules to follow when we are choosing a name (unique identifiers) for the variable.

Here are the rules below:

Note: In Javascript '_' and '$' are just like letters. They don't have any special meaning.

For example: let, var, for, and function are reserved.

The code below gives an Uncaught SyntaxError:

let var = 5;   //  Uncaught SyntaxError: Unexpected token 'var'
let function = 5; // Uncaught SyntaxError: Unexpected token 'function'

That is: words go one after another, every word except the first one starting with a capital letter.

For example, firstName, lastName, birthYear, etc.

Here are some valid and invalid variable names below:


// Example of valid variables names
let camelCased         //  first word is lowercase any additional word starts with an uppercase letter
let here2num                  // number in the middle, but not starting with numbers
let JAVASCRIPT_IN_UPPERCASE       // uppercase letters with underscores
let _Javascript_              //start and end with an underscore, with letters in the middle
let $_$                       // dollar signs and underscores
let $_foo3                // mix the dollar sign, underscores, letters and numbers
let _12foo           //start with underscores and contain numbers and letters
let _                 //   contains only underscore
let $             // contain only a dollar sign


// Example of invalid variables names

let random%         //  Don't use the percentage symbol
let 11years           //  Don't start with number(s)
let some-let      //  Don't use dashes
let one variable   //  Don't use spaces
let function           //  Don't use reserved keywords

Naming variable Good practices

Giving a good name to the variable is one of the most important and complex skills in programming. Proper descriptive variable names can create a good impression for a programmer in the viewer's eyes.

In a real project, most of the time a programmer spends modifying and extending an existing code base rather than writing something completely new. When we return to the code after doing something else for a while or maybe for a long period of time, it’s much easier to get back into a flow for well-labeled code. Or, in other words, when the variables have been declared with good names.

So, please spend time thinking about the right name when you are declaring a variable. Doing so will make you benefited in the future.

Note: Though There is no limit to the length of the variable name and it can be almost unlimited in length, You should avoid creating extremely long variable names. Shorter variable names help the JavaScript engine to execute the program faster.

Undefined value of a variable

When we declare a variable without assigning a value to it will have the value undefined.

It's the default behavior of javascript. Though this container should be empty, it is not. It still contains a value that is `undefined`.

Note: undefined is one type of data in javascript. we will see about undefined and other data types in any other blog in detail.

If you want to see their value, you can do that by simply doing `console.log()` in your web browser's console the output will be `undefined`.

let name, age, birthYear;
console.log(name);          // undefined
console.log(age);           // undefined
console.log(birthYear);     // undefined

Undeclared/Unassigned variable

Suppose you want to use a variable in a statement, but you haven't declared this variable yet. In this case, your code will throw a `ReferenceError` showing that the variable is not defined. In short, if we want to access an undeclared variable, the code will throw a runtime error.

Example:

console.log(xyz);  // ReferenceError: xyz is not defined

Try running the above line in the browser console.

In the real program, You should never try accessing a variable without declaring it.

Note: Don't get confused with the undefined and Unassigned/Undeclared variables — they are very different things. An undefined variable is a variable that has been declared in the program but has not been initialized with a value. In contrast, an undeclared variable is a variable that has not been declared yet.

Assigning value to the variable

After the declaration has been completed, we can use the equal(`=`) sign to assign a value to the variable.

Example:

let age;
age = 22;

Where the age is the name of the variable and it is assigned a value of 22.

Note: In JavaScript, the equal sign (`=`) is an "assignment" operator, not an "equal to" operator like in algebra. Though the following does not make sense in algebra:

x = x + 10;

But In JavaScript, it makes perfect sense: First It calculates the value of x + 10 and assigns the result to variable `x`. In simple words, The value of x is incremented by 10.

Note: in JavaScript, the "equal to" operator is written like ==.

Also, the variable declaration and initialization can be combined. that means variable initialization can be done in the declaration:

var greetings = "Hello";
let name = "Robiul"

// or,
var greetings = "Hello", name = "Robiul";

//The same declaration can even span across multiple lines using comma(,):

var greetings = "Hello", 
      name = "Robiul";

Note: we can assign a variable value from user input.

// Gets user input
var name = prompt("What is your name?");
var age = prompt("What is your favorite age? ");
console.log(name)  
console.log(age)

Changing/Updating/Re-assigning the value of a variable

The meaning of the word ‘variable’ is anything that can vary. That means once the initialization is finished we can change or update the value of the variable later on in the program if required.

It is similar to re-initializing the variable. We can update/change the value by just typing the name of the variable followed by an equals sign(`=`) and then followed by the new value we want it to store.

var greetings = "Hello";
let myHobby = "Drawing";
console.log(greetings);   // Hello
console.log(myHobby);   // Drawing

// changing the value 
greetings = "Hi";
myHobby = "Programming"
console.log(greetings);   // Hi
console.log(myHobby);   // Programming

//   also, we can change the value as many times as we want:

let message;
message = "Hello";
console.log(message);  // Hello
message = "World"; 
console.log(message);  // World

javascript variable doesn't contain the history of the variable, which means when we change the value of a variable it removes the old data and stores the new one.

Note: There are a few functional programming languages, like Scala or Erlang that don't allow changing variable values.In such languages, once the value is assigned in a variable, it’s there forever. If we want to reassign the variable or want to change the value of the variable, the language forces us to create a new variable (declare a new variable). We can’t reuse the old one.

Accessing JavaScript variables

As a beginner, you might be thinking about the procedure to access/use the value that is stored in a specific variable. It's simpler than declaring and assigning the variable. You just need to write the name of the variable that contains the value you want to access and you are done. This things also called “referencing a variable”.

// Declare and initialize the variable
var myNumVariable = 85
let myTextVariable = 'This is text.'

// Access the values in myNumVariable and myTextVariable
myNumVariable
// 85
myTextVariable
//  'This is text.'


// Re-assign myNumVariable and myTextVariable
myNumVariable = 50
myTextVariable = 'This is a updated Text'


// Access the values in myNumVariable and myTextVariable again
myNumVariable
// 50
myTextVariable
// 'This is a updated Text'

Basic usage of variables

var x = 10;
x + 2;
console.log(x)   // 12

var x = 100;
var y = x + 102;
console.log(y)  // 202

let x = 5 + 2 + 3;
console.log(x)  // 10

let x = "John" + " " + "Doe";
console.log(x)   // John Doe

Note: During arithmetic operations, If you put a number in quotes, the rest of the numbers will be treated as strings, and all of them will be concatenated.

Now try this:

let y = "5" + 2 + 3;
console.log(y)   // 523

This is called coercion in javascript

Why should we use variables?

So far we have discussed what a variable is, how to create it, and how it works in our program. But we haven't discussed why this is so important and why should we use the variable.

Let's have a look at this too.

To Understand these points let's see a program of a pretty simple and state-forward game called guess my number. This game logic is very simple, we will use a number in our code and the user will have to guess the number if the user guesses the correct number our program will show a successful message and if the user is wrong the program will show a failed message.

if(userInput==20){
  console.log("Hurrah, You guess the correct number.");
}else if(userInput<20){
  console.log("Sorry, Your guessed number is small. Please try a bigger one.")
}else if(useInput>20){
  console.log("Sorry, Your guessed number is Big. Please try a bigger one.")
}

Here in this program, we have used the number 20 to make our program logic. This program will perform fine but this program is not well coded.

let's see what's wrong with this program and why this is not well coded and how variable makes our life easy and help us to make our code more efficient and optimized:

let myNum = 20;
if(userInput==myNum){
  console.log("Hurrah, You guess the correct number.");
}else if(userInput<myNum){
  console.log("Sorry, Your guessed number is small. Please try a bigger one.")
}else if(useInput>myNum){
  console.log("Sorry, Your guessed number is Big. Please try a bigger one.")
}

let myNum = 20;
console.log(myNumber) // 20
if(userInput==myNum){
console.log(myNumber) // 20
  console.log("Hurrah, You guess the correct number.");
}else if(userInput<myNum){
  console.log(myNumber) // 20
  console.log("Sorry, Your guessed number is small. Please try a bigger one.")
}else if(useInput>myNum){
  console.log(myNumber) // 20
  console.log("Sorry, Your guessed number is Big. Please try a bigger one.")
}
// change the value
myNum = 30;
console.log(myNumber) // 30
if(userInput==myNum){
  console.log(myNumber) // 30
  console.log("Hurrah, You guess the correct number.");
}else if(userInput<myNum){
  console.log(myNumber) // 30
  console.log("Sorry, Your guessed number is small. Please try a bigger one.")
}else if(useInput>myNum){
  console.log(myNumber) // 30
  console.log("Sorry, Your guessed number is Big. Please try a bigger one.")
}

Simple right?

  let myNum =  prompt("enter a number?");
if(userInput==myNum){
  console.log("Hurrah, You guess the correct number.");
}else if(userInput<myNum){
  console.log("Sorry, Your guessed number is small. Please try a bigger one.")
}else if(useInput>myNum){
  console.log("Sorry, Your guessed number is Big. Please try a bigger one.")
}

Now that our code is dynamic we can change the value whenever we want without changing or editing the source code.

Thus, variable helps us to write optimized, developer-friendly, and easy-to-understand code.

Note: Though variable helps us in many ways. but too many variables can harm the code performance very badly and it's can increase the server cost. so, we should be careful when we are declaring a variable.

Recap

Resources


Also published here.