Difference Between Static and Const in JavaScript


Static variables can be defined as a class property that is used in a class and not on the class instance. This type of variable is stored in the data segment area of the memory. The value assigned to these types of variables is shared among every instance that is created in the class.

We need to use the static keyword for creating any static entity like a static variable, static function, operators, properties, etc. The value of a static variable is set at the runtime of the application and serves as a global value for the whole application.

Example 1

In the example below, we are creating a static method and then excessing its value.

# index.html

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Static</title>
</head>
<body>
   <h1 style="color: green;">
      Welcome To Tutorials Point
   </h1>
   <script>
      class example {
         static staticMethod() {
            return "I am a Static Method";
         }
      }
      document.write(example.staticMethod());
   </script>
</body>
</html>

Output

You will get a similar result as below on successful execution of the above program −

Const − A constant can be defined as a variable that has a fixed defined value and remains the same throughout the program.

A property of the const variable is that we cannot change or modify this value anywhere in a project once it is initialized.

It is because the compiler is informed about the fixed value and therefore should be prevented from any modifications.

Thus whenever any modification occurs in the const value an error is thrown instead of actually modification.

Example 2

In the example below, we are creating a static method and then excessing its value.

# index.html

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Static</title>
</head>
<body>
   <h1 style="color: green;">
      Welcome To Tutorials Point
   </h1>
   <script>
      const value= "I am a constant value";
      document.write(value);
   </script>
</body>
</html>

Output

You will get a similar result as below on the successful execution of the above program −

StaticConstant
Static methods are used for creating a static copy of an object.The const variable declares a constant value that cannot be modified
The static keyword is used for declaring the static method, variable, or operatorThe const keyword is used for declaring the constant value.
Static is used with methods and classes.We can use the const keyword with arrays and objects in JavaScript
The value of a static variable can be modified.A constant value cannot be modified
Static is a storage specifier.Const/Constant is a type qualifier.
Static can be assigned for reference types and set at run time.Constants are set at compile-time itself and assigned for value types only.

Updated on: 21-Apr-2022

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements