![]() |
To create a static variable in JavaScript, you can use a closure or a function scope to encapsulate the variable within a function. This way, the variable maintains its state across multiple invocations of the function.
Why do we create a static variable in JavaScript?In JavaScript, we simulate static variables using closures or other patterns to share state among instances, persist data between calls, or encapsulate information. These “static-like” variables enhance modularity and encapsulation, providing a way to maintain a state without relying on global variables. Example 1: In the below example, we will create a static variable and display it on the JavaScript console. Javascript
Output
GeeksforGeeks static method has been called. Example 2: Static variable is called using this keyword. Javascript
Output
staticVariable : GeeksforGeeks |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 9 |