CA Resources

Variables

Overview of JavaScript variables, including their declaration using var, let, const, and examples demonstrating their usage.

Variable means anything that can vary. In JavaScript, a variable stores data that can be changed later on.

Variables are containers for storing data values. All JavaScript variables must be identified with unique names. The unique names are called identifiers. Identifiers can be short names (like x and y) or more descriptive names (like age, sum, total).

Declaring Variables

There are 4 ways to declare variables in JavaScript:

Using var

var keyword is used to declare variables since JavaScript was created. It is confusing and error-prone when using variables declared using var.

<!DOCTYPE html>
<html>
  <body>
    <h1>JavaScript Variables</h1>
    <p>In this example, fname and age are variables declared using var.</p>
    <p id="fname"></p>
    <p id="age"></p>
    <script>
      var fname = "Amber";
      var age = 10;
      document.getElementById("fname").innerHTML = "My name is " + fname;
      document.getElementById("age").innerHTML = "I am " + age + " years old";
    </script>
  </body>
</html>

Using let

let keyword removes the confusion and error of var. It is the new and recommended way of declaring variables in JavaScript.

<!DOCTYPE html>
<html>
  <body>
    <h1>JavaScript Variables</h1>
    <p>In this example, fname and age are variables declared using let.</p>
    <p id="fname"></p>
    <p id="age"></p>
    <script>
      let fname = "Miah";
      let age = 10;
      document.getElementById("fname").innerHTML = "My name is " + fname;
      document.getElementById("age").innerHTML = "I am " + age + " years old";
    </script>
  </body>
</html>

Using const

const keyword is used to declare a constant variable that cannot be changed once assigned a value. Constant variables must be declared and initialized at the same time. The value of the constant variables can't be changed after initialized them.

The value of a constant variable cannot be changed but the content of the value can be changed. For example, if an object is assigned to a const variable then the underlying value of an object can be changed.

<!DOCTYPE html>
<html>
  <body>
    <h1>JavaScript Variables</h1>
    <p>In this example, fname and age are variables declared using const.</p>
    <p id="fname"></p>
    <p id="age"></p>
    <script>
      const fname = "Geastine";
      const age = 8;
      document.getElementById("fname").innerHTML = "My name is " + fname;
      document.getElementById("age").innerHTML = "I am " + age + " years old";
    </script>
  </body>
</html>

Using nothing (direct variable names)

<!DOCTYPE html>
<html>
  <body>
    <h1>JavaScript Variables</h1>
    <p>In this example, fname and age are undeclared variables.</p>
    <p id="fname"></p>
    <p id="age"></p>
    <script>
      fname = "Zildjian";
      age = 8;
      document.getElementById("fname").innerHTML = "My name is " + fname;
      document.getElementById("age").innerHTML = "I am " + age + " years old";
    </script>
  </body>
</html>

When to use var?

The var keyword is used for declaring variables in all JavaScript code from 1995 to 2015.

The let and const keywords were only added to JavaScript in 2015. var is used when created web sites will be used in older browsers.

When to use let and const

  • We will use const if the value of the variable will not be changed within the program.
  • We will use let if the value of the variable can be change within the program.

Using let and const

<!DOCTYPE html>
<html>
  <body>
    <h1>JavaScript Variables</h1>
    <p id="demo"></p>
    <script>
      const num1 = 12;
      const num1 = 28;
      let total = num1 + num2;
      document.getElementById("demo").innerHTML = "The total is " + total;
    </script>
  </body>
</html>

Notes in Declaring Variables in JavaScript

  • You can assign a value to a variable using the = operator when you declare it or after the declaration and before accessing it.

    let msg;
    msg = "Hello JavaScript!"; // assigning a string value

    In the above example, the msg variable is declared first and then assigned a string value in the next line.

  • You can declare a variable and assign a value to it in the same line. Values can be of any datatype such as string, numeric, boolean, etc.

    let name = "Juan";    // assigned string value
    let num = 100;        // assigned numeric value
    let isActive = true;  // assigned boolean value
  • Multiple variables can be declared in a single line, as shown below.

    let name = "Juan", num = 100, isActive = true;
  • You can copy the value of one variable to another variable, as shown below.

    let num1 = 100;
    let num2 = num1;
  • JavaScript allows multiple white spaces and line breaks when you declare a variables.

    let name = "Juan", 
        num = 100, 
        isActive = true;

You cannot redeclare a variable using let keyword

  • Variable names are case-sensitive in JavaScript. You cannot declare a duplicate variable using the let keyword with the same name and case. JavaScript will throw a syntax error. Although, variables can have the same name if declared with the var keyword (this is why it is recommended to use let).
    let num = 100;
    let num = 200; // syntax error
     
    var num = 100;
    var num = 200; // ok 👍

General Rules for Constructing Variable Names

  • Variable names are case-sensitive in JavaScript. So, the variable names msg, MSG, Msg, mSg are considered separate variables.
  • Variable names can contain letters, digits, or the symbols $ and _.
  • A variable name cannot start with a digit 0-9.
  • A variable name cannot be a reserved keyword in JavaScript, e.g. var, function, return cannot be variable names.

Dynmic Typing

  • JavaScript is a loosely typed language. It means that you don't need to specify what data type a variable will contain. You can update the value of any type after initialization. It is also called dynamic typing.
  • JavaScript variables can hold numbers and text values or strings.
  • Strings are declared by placing them inside double or single quotes.
  • Numeric values are declared without quotes. If you put a number in quotes, it will be treated as a text string.
<!DOCTYPE html>
<html>
  <body>
    <h1>JavaScript Data Types</h1>
    <p id="line1"></p>
    <p id="line2"></p>
    <script>
      const pi = 3.14;
      let age = 25;
      let fname = "Andrew";
      let lname = "Ford";
      document.getElementById("line1").innerHTML = "I am " + fname + " " + lname + " and I am " + age + " years old";
      document.getElementById("line2").innerHTML = "The value of Pi is " + pi;
    </script>
  </body>
</html>

Variable Scope

Global Variables

Variables declared out of any function are called global variables. They can be accessed anywhere in the JavaScript code, even inside any function.

Local Variables

Variables declared inside the function are called local variables of that function. They can only be accessed in the function where they are declared but not outside.

function myFunction() {
  let msg = "JavaScript!";
  alert(greet + msg); // can access global and local variable
}
 
myFunction();
 
alert(greet); // can access global variable
alert(msg);   // error: can't access local variable

Declare Variables Without var and let Keywords

Variables can be declared and initialized without the var or let keywords. However, a value must be assigned to a variable declared without the var keyword.

The variables declared without the var keyword become global variables, irrespective of where they are declared. It is recommended to declare variable using the let keyword.

function myFunction() {
  msg = "JavaScript!";
}
 
myFunction();
alert(msg);   // msg becomes global variable so can be accessed here

Undefined Values in Variables

In computer programs, variables are often declared without a value. The value can be something that has to be calculated, or something that will be provided later, like user input.

A variable declared without a value will have the value undefined.

Example:

  • let name;
  • the value of name will be undefined and will just wait for the value assigned within the program or provided by the user as an input.
Edit on GitHub

Last updated on