JavaScript Variables - The Guide

Variables are one of the important theories in programming. It could even be said to be the most important. They are part of the fundamentals of any programming language. Without them, it would be difficult to perform manipulation, and computations. We would have no way of storing information, retrieving them and no track of values.

A variable is a storage location or a memory location that holds a data type and values. JavaScript variables are variables declared and assigned in JavaScript, following the JavaScript syntax, that holds values and datatypes.
In this article, we will look at variables in JavaScript, the datatypes they hold, good naming and writing practices, how they are implemented and manipulated and their scope.

JavaScript variable declaration, Initializing and Assigning Variables

A variable is declared when it is created. In JavaScript, variables are declared using any of these three keywords - var, let and const.

var name; 
let website; 
const address;

A variable is initialized when it is assigned to a value.

var name = 'CodeCoda' 
let website = 'codecoda.com' 
const address = '123.33'

Not all variables are initialized when they are created or declared. A variable can be initialized later on in the program. 

//Write 'I am sorry i yelled' 10 times 
let punishment = '';
for (n = 0; n < 11; n++ ){ 
  punishment += 'I am sorry i yelled' + '<br>'; 
}
document.write(punishment);

Assigning a value to a variable means using the assignment operator (=) or any other assignment operator (which we will look at later on) to apportion a value to a memory location.

Multiple lines variables

Multiple variables can be declared and initialized in one line, separated by a comma.

// declaration on one line. This works better when they are of the same data type 
Let no1, no2, no3; 
// declaration and initialization on one line 
let no1 = 56, no2 = 96, no3 = 30; 
// Multiple lines but still in one statement 
let no1 = 458, 
    no2 = 834, 
    no3= 590;

Commas are important in each case and the end line separator “;” signifies the end of line and declaration.

Variable Syntax in JavaScript

The variable syntax is quite straightforward. First, we need to use any of the keywords - var, let or const followed by a variable name, an assignment operator, and a value.
The assignment operator separates the keyword and variable which are on the left-hand side from the value which is on the right-hand side.

var name = 'code now'; 
const price = 55; 
let price2 = 44;

name stores the value ‘code now’, price holds the value 55. Variables do not just hold values, they can also hold expressions.

let total = price + price2; 

The variable total holds the result of the expression price + price2 which is 99.

Technically, web browsers can control what users see, and sites using JavaScript can overwrite anything coming from the original authors. Browsers heavily utilize JavaScript to create an interactive Internet; sites like YouTube, Facebook, and Gmail would not exist without it.

Ben ShapiroDocumentary Director

Variable Names and identifiers

Variable names are unique identifiers with which we can identify and reference allocated memory locations and the values they hold. There are certain practices and rules while naming variables in JavaScript.

Variable naming convention in JavaScript

  • Variable names can contain letters, numbers, dollar signs, underscores.
  • A variable name must start with a letter, underscore, or dollar sign. Numbers or digits cannot start a variable name.
  • JavaScript variable names cannot contain hyphens.
  • Variable names can be a single letter or a string of words. Y works just as this_is_a_car.
  • Reserved words like for, let, const, etc cannot be used as variable names.
  • JavaScript variable names are case sensitive. Car and car are two different variables.
  • Variable names cannot consist of only digits or numbers.

Good practices while naming variables in JavaScript

  • Using camel capitalization except for the letter while joining a string of words. Eg. NameOfWebsite.
  • Using underscore to separate a string of words. Eg. name_of_website.
  • Using descriptive names instead of single letters or confusing words. Single letters are only best used during a loop.
  • Using the endline semi-colon at the end of variable declaration and initialization.

Var, Let and Const

Var

Before 2015 (ES6 release of JavaScript), var was the only keyword used in defining variables. It had some issues, one of it being that variables existed even outside the scope in which they were defined. So let and const were introduced to make up for the shortcomings of var.

Let

Let is one of the keywords released in ES6. It is a better option to use var. It allows variables to be updated, only within the block in which it is initialized. Let declarations are hoisted to the top.

Const

Const, just like let was introduced in 2015. It differs slightly from let and var. It is strict and used for variables whose values are constant and will not change during the execution of the program. These variables cannot be reassigned or updated.

const a = 'we'; 
a = 'me'; 
console.log(a); 
//Uncaught TypeError: Assignment to constant variable.

It is also like let as it is only accessed within the block in which it is defined.

Which should you use?

These days, it is advisable to use either let or const when defining variables.

Variables and datatypes in JavaScript

Variables usually have data types attached to them. JavaScript has about seven basic data types and a variable must be assigned to either of them.

1. Strings:

String data type holds only text. They could hold numbers, digits, symbols, and signs, but it would be regarded as text. Numbers written in string format cannot be computed.
Strings are usually enclosed in quotes. Double, single, or backticks. Double and single are commonly used and can be used interchangeably.

const name = 'codecoda';           //single quotes 
const website = "codecoda.com";    //double quotes 
const country = `Ireland`;        //backticks 
let str = name + "web address is at " + website + " and their headquarters is in " + country; 
document.write(str); 

Backticks are also used when expressions or variables need to be included into a string. In this case, the variables will be enclosed in curly braces - {} with a dollar sign before it.

const str = `${name} web address is at ${website} and their headquarters is in ${country}`; 
document.write(str);

By using backticks this way, we don’t need to concatenate strings with the addition sign.

2. Number:

This represents all integers, and decimal numbers. A number could also be a NAN (not a number) a +infinity and a -infinity.

const no1 = 33; 
const no2 = 44.3; 
const no3 = 12/3; 
 
document.write(no1, no2, no3);

3. BigInt:

These represent numbers that are larger than the 253-1 numbers that Number data type represent. They are created by appending an n to the end of the integer.

const no1 = 302908483484959384940n;

Operations could be performed on them just like regular numbers

const no1 = 302908483484959384940n; 
const no2 = 600719924738393739998n; 
document.write(no1 + no2); 

NOTE: Even though they both represent numbers and digits, operations cannot be performed on BigInt and Number data types.

document.write(no1 + 5); 
//this raises an error 

4. Null:

This represents an empty or unknown value.

let nos = null; 
document.write(nos); 

Null is written without quotes, else it becomes a string.

5. Undefined:

Undefined data type represents a variable that is declared but not assigned to any value.

let name;
document.write(name);

6. Boolean:

These are logical entities representing either true or false values.

const Ttrue = true; 
const Ffalse = false; 
document.write(Ttrue, Ffalse); 

7. Object:

This represents data stored in a key/pair collection or hash table.

let car = { 
  name: 'Ford', 
  model: 'F12', 
  year_prodcued: 2021 
}; 
document.write(car.name, car.model, car.year_prodcued); 

To check the data type associated with any variable, we use the typeof method.

let car = 'Ford' 
let year = 2010;
document.write(typeof(car));  //string 
document.write(typeof(year)); //number 

Loose type language

JavaScript is regarded as a loose-type language because it doesn’t require the programmer to explicitly classify or specify the type of variable to be declared.
This is the opposite of strict or strong-typed languages that require the data type to be specified during initialization. The value assigned to the variable should also match the variable data type, else it raises an error.
Because JavaScript is a loose-typed language, variables acquire high flexibility. Also, Variables can be assigned and reassigned easily.

Reassigning Values in a Variable

In a language like Java that is considered strict-typed, we would declare variables like this:

Int nos = 10;   //for integers and numbers 
String str = 'Java';  //for strings 

The variable nos can only hold an integer while the variable str can only hold a string. If the values need to be reassigned, only integers or numbers can be reassigned to nos. And only string values can be reassigned to str.
In JavaScript, values can be assigned and reassigned to variables without regards to the data type they are supposed to hold.

let a = 10; 
let b = 15; 
let c = 20;
if (b < c) { 
  a = "Why?" 
} 
document.write(a) 
//Why? 
// a changes from a number to a string 

Assignment operators and how they affect JavaScript variables

The equals sign assignment operator (=) is not the only assignment operator used on variables. There are a couple of other variables, and they affect the behaviour of the variables and their results. We will make these distinctions between strings and numbers.

Operands are the values which an operation is to be performed on.

=

The most common operator. It assigns a value to a variable

var a = 9; 
document.write(a); 
// 9 

It is also used to reassign values, replacing the operand on the right with new value.

let a = 10; 
let b = 15; 
let c = 20; 
if (b < c) { 
  a = "Why?"
}
document.write(a) 

+

The addition sign is used to add numbers.

let x = 12 + 4; 
document.write(x); 
// 16 

It concatenates strings.

let name = "Rita"; 
let surname = " Ora"; 
document.write(name + surname) 
// Rita Ora 
//With strings and numbers 
let d = "Hello World " + 10; 
document.write(d) 
// Hello World 10 

-

The minus sign subtracts values from numbers. 

let x = 10 - 5; 
document.write(x); 
//5 

It doesn’t work on strings, returning a NAN, it also doesn’t work on string/number combinations.

+=

This operator, a combination of the equal sign and plus sign, for number,  assigns the value of the right operand to another value and adds the result to the variable. Just like the + operator.

let n = 20; 
n += 5; 
document.write(n) 
// 25 

For strings, it adds the string on the right operand, to the new value, concatenating them.

let a = 'hello'; 
let b = a += ' world'; 
document.write(b); 
//hello world 

* and *=

They multiply numbers.

let x = 2; 
let y = 4; 
document.write(x * y); 
// 8 

/ and /=

They divide numbers.

let x = 2; 
let y = 4; 
document.write(x / y); 
// 0.5 

Conclusion

Today we looked at the use cases of variables and data types. Unlike in other programming languages, datatypes are strict in JavaScript, not allowing mixed operands. If not used appropriately, you will need to handle the resulting errors by implementing error handlers, or you are risking execution stops of your JavaScript routines.

Like this article? Please rate it!

Author

Ivan Georgiev | Software Engineer

Ivan is an extremely intelligent and knowledgeable professional with a hunger for improvement and continuous learning. Being versatile in a number of programming languages, he picks up on new tech in a matter of hours. He is a person that masters challenges by investigation and clear, structured execution, bringing in his experience and innovative ideas to solve problems quickly and efficiently. Ivan is also a Certified Shopware Engineer.