DEV Community

Muhammad Rizwan Ashiq
Muhammad Rizwan Ashiq

Posted on • Edited on

Variables

What is variable

Computer programs are all about storing and manipulating data. All the modern programming languages have a concept of variables, which is more or less the same. A variable is a named storage location that can store a value of a particular type, which can be changed later in the program.

Like other programming languages, in JavaScript, variables are containers that store values in memory. You can use variables to store number, strings, booleans, arrays, objects, etc types of values.

How to declare a variable

In JavaScript, you need to declare a variable before you use it except var, you can use it before declaring it. Declaring a variable means to give it a name, which will be used to refer to the variable later. When variable is declared it is assigned a space in memory to store the value. You can declare a variable using:

Let's see each of them in detail:

const

The const keyword is used to declare which can't be reassigned a different value. A const variable must be given a value when it is declared, and it can't be changed afterward. const variables are also block-scoped, which means that they are only visible within the block of code in which they are defined.

const PI = 3.14;
// This will error
PI = 3.14159; // TypeError: Assignment to constant variable.
Enter fullscreen mode Exit fullscreen mode

Note: Don't confuse const with const in C++, final in Java, or readonly in C#. const in JavaScript is not a constant value, it's a constant reference to a value. The value it holds is still mutable, just the variable identifier can't be reassigned.

Objects and arrays declared with const are mutable. For example, in the following code, the person object is declared as a constant:

const person = {
    name: "John",
    age: 30,
};

// However, the person object can still be changed:

person.name = "Peter"; // it'll change the name to Peter
person.age = 46; // it'll change the age to 46

// But you can't reassign a different object to person
// This will error
person = { name: "Amy", age: 20 }; // TypeError: Assignment to constant variable.
Enter fullscreen mode Exit fullscreen mode

Same thing with arrays:

const cars = ["Saab", "Volvo", "BMW"];
cars[0] = "Toyota"; // it'll change the first element to Toyota
cars.push("Audi"); // it'll add Audi to the end of the array

// But you can't reassign a different array to cars:
// This will error
cars = ["Toyota", "Volvo", "Audi"]; // TypeError: Assignment to constant variable.
Enter fullscreen mode Exit fullscreen mode

let

The let keyword is used to declare a variable whose value can be changed later. let is similar to var, but it has some important differences. One of the main differences is that let variables are block-scoped, whereas var variables are function-scoped. This means that let variables are only visible within the block of code in which they are declared, whereas var variables are visible throughout the entire function in which they are declared.

let x = 5;
x = 10; // This is allowed
Enter fullscreen mode Exit fullscreen mode

A variable declared with let can be reassigned a new value, but it can't be declared again in the same scope. For example:

let message = "Hello, world!";
message = "Hello, JavaScript!"; // works

// This will error
let message = "Hello, again!"; // SyntaxError: Identifier 'message' has already been declared
Enter fullscreen mode Exit fullscreen mode

var

The var keyword is used to declare a variable whose value can be changed later. var is the oldest way to declare variables in JavaScript, still supported in modern browsers, and it has some limitations that make let a better choice in most cases. However, var variables are still widely used, and you will encounter them in older codebases.

var x = 5;
x = 10; // This is allowed
Enter fullscreen mode Exit fullscreen mode

A variable declared with var can be reassigned a new value and declared again in the same scope. For example:

var message = "Hello, world!";
message = "Hello, JavaScript!"; // works

var message = "Hello, again!"; // works
Enter fullscreen mode Exit fullscreen mode

When to use const, let, and var

It's generally a good idea to use const whenever you can, and only use let if you need to reassign a value to the variable. var should generally be avoided in favor of let or const because they provide better control over the scope and the lifetime of variables

Naming variables

In JavaScript, you can use letters, digits, underscores, and dollar signs to name variables. You can also use Unicode letters. However, a variable name must begin with a letter, underscore, or dollar sign. You can't use a number to begin a variable name.

// Valid variable names
let myName = "John";
let $myName = "John";
let _myName = "John";
let myName1 = "John";
let myName$ = "John";

// Invalid variable names
// This will error
let 1myName = "John"; // SyntaxError: Unexpected strict mode reserved word
// This will error
let my-name = "John"; // SyntaxError: Unexpected token '-'
// This will error
let my name = "John"; // SyntaxError: Unexpected identifier
Enter fullscreen mode Exit fullscreen mode

Caution: JavaScript is case-sensitive. This means that myName and myname are different variables. It is a good practice to use camelCase for variable names. This means that the first word is in lowercase, and the first letter of each subsequent word is capitalized. For example, myName, myFirstName, myFavoriteColor, etc. You can also use underscores to separate words, but this is not recommended. For example, my_name, my_first_name, my_favorite_color, etc.

Reserved keywords

The following keywords can't be used as variable names:

  • break
  • case
  • catch
  • class
  • const
  • continue
  • debugger
  • default
  • delete
  • do
  • else
  • enum
  • export
  • etc.

A complete list of JavaScript keywords can be found here. If you use a reserved keyword as a variable name, you will get an error.

// This will error
let break = 5; // SyntaxError: Unexpected strict mode reserved word
Enter fullscreen mode Exit fullscreen mode

Variable scope

Scope in JavaScript refers to the accessibility and visibility of variables, functions, and objects within different parts of a codebase.

There are two types of scope:

Global scope

Global scope refers to variables, functions, and objects that are defined outside any function and are accessible from anywhere in the codebase. For example:

let globalVariable = "This is a global variable";

function myFunction() {
    console.log(globalVariable);
}

myFunction(); // Output: "This is a global variable"
Enter fullscreen mode Exit fullscreen mode

In this example, the variable globalVariable is defined outside any function and can be accessed by any function in the codebase, including myFunction().

Local scope

Local scope refers to variables, functions, and objects that are defined within a function and are only accessible within that function. For example:

function myFunction() {
    let localVariable = "This is a local variable";
    console.log(localVariable);
}

myFunction(); // Output: "This is a local variable"
// This will error
console.log(localVariable); // ReferenceError: localVariable is not defined
Enter fullscreen mode Exit fullscreen mode

In this example, the variable localVariable is defined within the myFunction() function and can only be accessed within that function. If we try to access it outside the function, we get a ReferenceError.

Variable shadowing:

It's important to note that local scope variables can "shadow" global scope variables with the same name. For example:

let globalVariable = "This is a global variable";

function myFunction() {
    let globalVariable = "This is a local variable";
    console.log(globalVariable);
}

myFunction(); // Output: "This is a local variable"
console.log(globalVariable); // Output: "This is a global variable"
Enter fullscreen mode Exit fullscreen mode

In this example, the local variable globalVariable within myFunction() takes precedence over the global variable with the same name. This is known as variable shadowing.

Conclusion

In this article, we learned about variables in JavaScript. We learned about the var, let, and const keywords, and we learned about variable scope. We also learned about naming variables and reserved keywords.

Top comments (0)