Javascript Variables

Challenge Inside! : Find out where you stand! Try quiz, solve problems & win rewards!
Video Tutorial
Variables in JavaScript

In JavaScript, a variable is a name given to a memory location that is used to store any type of data. As the name suggests, variables mean it can vary, i.e., data stored in a variable can be changed or updated later in the program if required. In short, a variable is a symbolic name for (or reference to) data or a piece of information.

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

Example: Think of a box named Age which stores the age of a person. So, the name is the variable name, and the age stored in it is the value.

Age 23

JavaScript Identifiers

To declare a Javascript variable, one must know the rules to follow, as one can mess up the code while declaring a variable. If one doesn't follow the rules, he/she may end up getting an error.

Rules are as follows:

  • Variables are case-sensitive in Javascript. This means that schoolName and schoolname are considered different variables.
  • We can use letters, digits, symbols like dollar sign ($) and underscore ( _ ) in a variable name.
  • We cannot start a variable name with a digit (0-9).
  • We cannot use any of the reserved keywords (function, return, typeof, break, etc.) of Javascript as a variable name.

Important Points

  • Javascript allows multiple white spaces and even line breaks in a declaration of a variable.
  • We can separate different variable declarations using a comma.
  • In Javascript, we can store any type of value in a variable and also change it at any time.

Examples

  1. Declaring a JavaScript variable using line breaks and spaces:
  1. Declaring two variables in a single line separated by comma:
  1. Using reserve keywords while declaring a variable:
  1. Valid variable name examples:
  1. Invalid variable name examples:

Declaring a Variable

Using var:

Using let:

Using const:

Mixed Keyword:

In the mixed keyword example, we've declared variables x using var, y using let, and z using const. This illustrates how variables declared with different keywords behave with regard to reassignment and scope.

Initializing a Variable

After you have declared a variable, you can initialize that variable with a value. This initialization can be done by just writing the variable name followed by an equals sign and then the value you want the variable to store.

Now, try writing these lines in the console. After writing these lines, you can write only the variable names and press enter, the output will be the value stored in it.

Note: You can even declare and initialize a variable in a single line. Example:

When to Use var, let, or const?

In JavaScript, you should choose between var, let, or const based on the intended behavior of your variables and the scope in which they are used. Here's a general guideline for when to use each of these variable declarations:

var:

Use var when you need to declare variables with a function-level scope. It was the traditional way of declaring variables in JavaScript but is less commonly used in modern JavaScript. Variables declared with var are hoisted to the top of their function or global scope.

Example:

let:

Use let when you need block-level scope or you intend to reassign the variable. It's the preferred choice for most variables in modern JavaScript. Variables declared with let are not hoisted to the top of their block.

Example:

const:

Use const when you want to declare a variable that should not be reassigned. It's also block-scoped like let, but you cannot reassign values to variables declared with const. You should use const for values that should remain constant throughout their scope.

Example:

Learn more about the Difference between Var, Let, and Const in JavaScript on Scaler Topics.

Difference between the Properties of let, var, and const Keywords in JavaScript

You might be wondering what is let, as we haven't discussed it in detail. Here we will explain the difference between var and let. First of all, both keywords are used to declare variables in JavaScript.

  • The main difference between var and let is that the scope of the variable that is defined by let is limited to the block in which it is declared, whereas the variable declared using var has the global scope, i.e., can be used throughout the code.
  • If we declare a variable using var outside of any block (i.e., in the global scope), then the variable gets added to the window object, whereas variables declared with let will never get added to it.
  • We cannot declare the same variable multiple times if one of them is declared using let, whereas we can declare the same variable any number of times using var.
  • Variable hoisting can be done using var, but hoisting cannot be done using let.

Try the below codes in your browser's console and you will understand it better.

Example 1:

Example 2:

In this case, the scope of the variables x and y is only limited to the function, that’s why we cannot find the reference to the variables x and y outside the function, thus resulting in the reference error. We will describe the Variable Scope in the later part of this article.

Updating a Variable

Once a variable is declared or initialized, we can change its value anytime and anywhere within its scope. It is similar to re-initializing the variable. We can update/change the value by just typing the variable name followed by an equals sign and then followed by the new value we want it to store.

Example:

Variable Types

  1. Numbers:

    • In JavaScript, numbers are used to represent numeric data, including integers and floating-point numbers (decimals).
    • Numbers can be used for mathematical operations such as addition, subtraction, multiplication, and division.
  2. Strings:

    • Strings are sequences of characters enclosed within single (''), double ("") or backticks (``) quotes.
    • They are used to represent textual data, such as words, sentences, or any combination of characters.
    • Strings can be manipulated, concatenated, and compared in various ways.
  3. Booleans:

    • Booleans are a data type with only two possible values: true or false.
    • They are commonly used for making decisions in conditional statements or controlling the flow of a program.
  4. Arrays:

    • Arrays are ordered collections of data, where each element can be of any data type (including other arrays).
    • They are defined using square brackets [] and can be accessed by their index.
    • Arrays provide a convenient way to store and manipulate multiple values in a single variable.
  5. Objects:

    • Objects are collections of key-value pairs, where each key is a string (or symbol in more recent versions of JavaScript), and the values can be of any data type.
    • Objects are used to represent complex and structured data. They are often used to model real-world entities or data structures.
    • Objects can have methods, which are functions associated with them, and properties, which are variables associated with them.

These are fundamental data types in JavaScript, and understanding how to work with them is essential for building applications and performing various programming tasks. Different data types serve different purposes and can be used in combination to create more complex and meaningful data structures.

JavaScript Reserved Words

In Javascript, there are some reserved keywords that one cannot use as a variable name. Some of the reserved words are given in this table:

breakcasecatchclass
constcontinuedebuggerdefault
deletedoelseexport
extendsfinallyforfunction
ifimportininstanceof
newreturnsuperswitch
thisthrowtrytypeof
varvoidwhilewith

Dynamic Typing

You might have heard that JavaScript is called "a dynamically typed language". This means that the data type of a variable is not fixed. A variable can store any type of data, and the user can achieve this without specifying the type of data he/she wants to store(eg: number, string, objects, arrays, etc).

Also, one can change the stored value to any type of data, anytime freely.

Examples:

Try running these lines in console for better understanding.

Constants in JavaScript

You have seen that variables are those, whose values could be changed if required. Now, JavaScript also lets you declare constants. We declare a constant using the keyword const;

Syntax:

These constants are similar to variables but have some properties which are different from variables, such as:

  • The constant must be initialized when you declare it, otherwise, it will throw a " SyntaxError: Missing initializer in const declaration ".
  • Once assigned a value to a constant, you can’t re-assign values afterward. That is, a value is fixed to a constant.

Example 1:

Example 2:

Note: Though we cannot change the value of the constant, but if the constant value is an object, then we can modify the object's properties.

Example:

You can even add, or update or remove properties from a constant object, because you are just changing the details of the object, not the reference. The constant will still point to the same object.

Conclusion

  • Variables are containers that store values.
  • Variables can be declared using var and let keywords.
  • Variables can be updated or modified anytime and anywhere in its scope.
  • We cannot use any javascript reserved keywords as a variable name.
  • In JavaScript, there are only two types of variable scopes:
    • Global scope
    • Local scope
  • Constants in JavaScript are those values that do not change throughout the code.