Difference Between Static and Const in JavaScriptWe make use of both static and const variables in different languages. In this section, we will describe the difference points between both variables. Let's discuss. What is a Static variable in JavaScriptA static variable is a class property that is used in a class and not on the instance of the class. The variable is stored on the data segment area of the memory, and the same value is shared among every instance created in a class. To use a static variable, we use the static keyword. We can use the static keyword for making a static value, a static function, with classes, operators, properties and work as a utility function for the application or websites. The value of a static variable is set at the run time and is a kind of global value that can be used for the instance of the specified class. What is a Const variable in JavaScriptA const variable is a variable that has a fixed value and remains the same throughout the program. A property of the const variable is that we cannot change or modify its value throughout the program. It is because as soon as we make a const value, the compiler gets informed that the value is fixed and should be prevented from the programmer. Thus, whenever the programmer tries to modify a const value, an error gets displayed that the const value cannot be changed. To use a const variable, we use a 'const' keyword and input value. Static vs. Const in JavaScriptThere are the following difference points which will let us understand the difference between the two:
Above are some difference points that will make us understand the working of both JavaScript keywords. Apart from these theoretical difference descriptions, let's have a look over an example of both through which we can understand the use and working of the static and const variable. Using JavaScript StaticBelow is a practical implementation of using JavaScript static keyword within a class: In the above program code, we can see that a static method is created within a class and when it is invoked, it calls the statement within the static method of the class. The output of the following is shown below: Using Javascript constBelow is a practical implementation of using JavaScript const keyword: In the above code, it is seen that the const variable is assigned with a value but when we try to re-assign another value, an error is thrown which tells that the value described as const cannot be changed. Hence, the output of the above code is: In this section, we understood that static as well as const variable have different roles and are used for different purposes where a static variable can be used for a class method or property and a const variable is used for initializing a const value for an array, variable or an object. |