The Wayback Machine - https://web.archive.org/web/20240919003128/https://www.geeksforgeeks.org/how-to-create-static-variables-in-javascript/
Open In App

How to create Static Variables in JavaScript ?

Last Updated : 16 Jan, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

  • Static keyword in JavaScript: The static keyword is used to define a static method or property of a class. To call the static method we do not need to create an instance or object of the class.
  • Static variable in JavaScript: We used the static keyword to make a variable static just like the constant variable is defined using the const keyword. It is set at the run time and such type of variable works as a global variable. We can use the static variable anywhere. The value of the static variable can be reassigned, unlike the constant variable.

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




class Example {
    static staticVariable = 'GeeksforGeeks';
 
    //static variable defined
    static staticMethod() {
        return 'static method has been called.';
    }
}
// static variable called
console.log(Example.staticVariable);
// static method called
console.log(Example.staticMethod());


Output

GeeksforGeeks
static method has been called.

Example 2: Static variable is called using this keyword.

Javascript




class Example {
    static staticVariable = 'GeeksforGeeks';
    //static variable defined
    static staticMethod() {
        return 'staticVariable : ' + this.staticVariable;
    }
}
// static method called
console.log(Example.staticMethod());


Output

staticVariable : GeeksforGeeks


Similar Reads

React.js Blueprint Variables Font variables
In this article, we will learn about the Font Variables offered by the blueprint.js library. BlueprintJS is a React-based UI toolkit for the web. It is written in Typescript. This library is very optimized and popular for building interfaces that are complex and data-dense for desktop applications that run in a modern web browser. Font Variables: T
3 min read
Less.js Variables Default Variables
LESS (Leaner Style Sheets) is a simple CSS pre-processor that facilitates the creation of manageable, customizable, and reusable style sheets for websites. It is a dynamic style sheet language that enhances the working power of CSS. LESS supports cross-browser compatibility. CSS pre-processor is a scripting language that improves CSS and gets compi
3 min read
Less.js Variables Properties as Variables
LESS (Leaner Style Sheets) is a simple CSS pre-processor that facilitates the creation of manageable, customizable, and reusable style sheets for websites. It is a dynamic style sheet language that enhances the working power of CSS. LESS supports cross-browser compatibility. CSS pre-processor is a scripting language that improves CSS and gets compi
3 min read
How to create a static page with WordPress ?
WordPress is a free and open-source Content Management System (CMS) framework i.e. it is a tool that organizes the whole process of creating, storing and showcasing web content in an optimal way. WordPress started its journey as an improvement tool to enhance the regular typography of day-to-day writing. But it was taken as a blogging tool and as w
2 min read
How to create static front page in WordPress ?
Creating a static front page in WordPress can give your website a professional and customized look. Unlike the default setting where your latest posts are displayed on the homepage, a static front page allows you to showcase specific content that remains constant. This is particularly useful for business websites, portfolios, and landing pages wher
4 min read
JavaScript Course Variables in JavaScript
Variables in JavaScript are containers that hold reusable data. It is the basic unit of storage in a program. The value stored in a variable can be changed during program execution. A variable is only a name given to a memory location, all the operations done on the variable effects that memory location. In JavaScript, all the variables must be dec
4 min read
JavaScript Number Static Properties
The JavaScript Number is an object that can represent numeric values like integer, float, hexadecimal, decimal, etc. It acts as a wrapper object for primitive numeric values. It has various methods and properties that are used to perform different tasks on numbers. The following table shows some static properties of the Number object that can be us
2 min read
Difference Between Static and Const in JavaScript
Static variable: A static variable in JavaScript is basically a property of the class which is not used on the object of the class but is used in the class itself. This static variable is stored into the data segment of the memory and its value is shared among all the objects/instances created in that particular class. To declare a variable/functio
3 min read
How to fill static values in an array in JavaScript ?
In this article, we will see the methods to fill an array with some static values. There are many ways to fill static values in an array in JavaScript such as: Using Array fill() MethodUsing for loopUsing push() methodUsing from() methodUsing spread operatorMethod 1: Array fill() Method We use the array fill() method to fill static values in an arr
5 min read
Static Methods in JavaScript
JavaScript Static methods are defined directly on the classes, not on the instances of the class. Static methods can be of any name. A class can contain more than one static method. Note: "this" keyword is used to call a static method within any other static method in JavaScript. Example 1: The following is the code to invoke one static method. [GF
2 min read
How to Create Global Variables Accessible in all Views using Express/NodeJS ?
In Express.js, global variables can be immensely useful for sharing data across multiple views or middleware functions. Whether it's storing user authentication status, site-wide configurations, or any other frequently accessed data, global variables streamline development and enhance code organization. Table of Content Using app.localsUtilizing re
4 min read
How to create and use global variables in Postman?
Postman is an API(application programming interface) development tool that helps to build, test and modify APIs. It can make various types of HTTP requests(GET, POST, PUT, PATCH), save environments for later use, and convert the API to code for various languages(like JavaScript, and Python). In this article, we will learn How do you create and use
2 min read
How to unset JavaScript variables?
To know how to unset a variable we must know what are JS variables and how to declare a variable first. JavaScript variables are containers for storing data values. Variables can be declared using the 'var' keyword. Example : var x = 5; In the above code declaration, the value 5 has been assigned to the variable 'x'. The unsetting of a variable mea
3 min read
What are undeclared and undefined variables in JavaScript?
Undefined: It occurs when a variable has been declared but has not been assigned any value. Undefined is not a keyword. Undeclared: It occurs when we try to access any variable that is not initialized or declared earlier using the var or const keyword. If we use 'typeof' operator to get the value of an undeclared variable, we will face the runtime
1 min read
View the list of all variables in Google Chrome Console using JavaScript
All the variables in Google Chrome can be listed for the use of debugging. There are two approaches to list all variables: Method 1: Iterating through properties of the window object: The window object in JavaScript represents the current browser's window. The properties of this object can be used to find the variables of the Chrome browser. Each o
2 min read
How to use JavaScript variables in jQuery selectors ?
In this article, we will discuss how to use JavaScript variables in jQuery selectors. In the following examples, it can be seen that we have used the values stored in JavaScript Variables used inside the jQuery Selectors. Example 1: The concatenation technique can be applied in order to use the values stored in JavaScript variables. In the followin
2 min read
Reference and Copy Variables in JavaScript
In this article, we will talk about pass-by-value and pass-by-reference in JavaScript. JavaScript always passes by value, but in an array or object, the value is a reference to it, so you can 'change' the data. JavaScript has 5 primitive data types that are passed by value, they are Boolean, NULL, undefined, String, and Number. It has 3 non-primiti
5 min read
How to swap variables using destructuring assignment in JavaScript ?
Destructuring assignment is a feature introduces in EcmaScript2015 which lets you extract the contents of array, properties of object into distinct variables without writing repetitive code. Example 1: Here in this example we declared two variables a and b unassigned and an array with two strings "First" and "Second" int it. On line 5 we used destr
1 min read
How to make variables private in Constructor functions in JavaScript ?
In Javascript there's no specific way to make variables private in a Constructor function. If a variable is genuinely private, meaning it cannot be accessible from the outside. A constructor is a function that generates a new instance of a class, sometimes referred to as an "object." A constructor's job is to build an object and assign or set value
2 min read
How to check for null, undefined or blank Variables in JavaScript ?
JavaScript is one of the most widely used programming languages in the world, powering everything from simple web pages to complex web applications. As a dynamically-typed language, JavaScript allows for the creation of variables without specifying their type, which can sometimes lead to confusion and errors when dealing with null, undefined, or bl
3 min read
JavaScript Local Variables
What are Local Variables in JavaScript?JavaScript local variables are declared inside a block ({} curly braces) or a function. Local variables are accessible inside the block or the function only where they are declared. Local variables with the same name can be used in different functions or blocks. Local variables are deleted after a function is
2 min read
How to declare multiple Variables in JavaScript?
In this article, we will see how to declare multiple Variables in JavaScript. The variables can be declared using var, let, and const keywords. Variables are containers that store some value and they can be of any type. These are the following ways to declare multiple variables: Table of Content Declaring Variables IndividuallyDeclaring Variables i
2 min read
Difference Between Variables and Objects in JavaScript
The variables and objects are fundamental concepts but they serve different purposes. The Variables are used to store data values while objects are used to group related data and functions into a single entity. JavaScript VariableA variable in JavaScript is a named container that stores a value. It can be created using the var, let, or const. Synta
2 min read
How to swap two variables in JavaScript ?
The swapping process refers to changing the value from one variable to another variable. In this article, we will be learning about swapping 2 variables with Various Approaches. We would be using various ways to swap variables: Table of Content Using Temporary variableUsing Arithmetic OperationsUsing destructing AssignmentUsing XOR Bitwise Operator
3 min read
How to Concatenate Two Variables in JavaScript ?
In JavaScript, you can concatenate two variables (combine their values into a single string) using the + operator. Example 1: Here, the + operator is used to concatenate the values of firstName, a space character, and lastName into the variable fullName. C/C++ Code let firstName = "John"; let lastName = "Doe"; le
1 min read
JavaScript Variables
Variables are used to store data in JavaScript. Variables are used to store reusable values. The values of the variables are allocated using the assignment operator(“=”). Examples of JavaScript VariablesJavaScript Assignment OperatorJavaScript assignment operator is equal (=) which assigns the value of the right-hand operand to its left-hand operan
4 min read
How to declare Global Variables in JavaScript ?
Global Variables Global variables in JavaScript are variables declared outside of any function. These variables are accessible from anywhere within the script, including inside functions. Global variables are declared at the start of the block(top of the program)Var keyword is used to declare variables globally.Global variables can be accessed from
2 min read
How to use arrays to swap variables in JavaScript ?
The technique of swapping two variables in coding refers to the exchange of the variables' values. In an array, we can swap variables from two different locations. There are innumerable ways to swap elements in an array. let's demonstrate a few ways of swapping elements such as: Table of Content Using a Temporary VariableOne-Line SwapUsing arithmet
4 min read
JavaScript Global Variables
JavaScript Global Variables can be accessed outside any function or block. They are declared within the window object or outside any block or scope. A variable declared without a keyword is also considered global even though it is declared in the function. Example 1: In this example, we will see the declaration of global variables and accessing the
1 min read
How to Pass variables to JavaScript in Express JS ?
Express is a lightweight framework that sits on top of Node.js’s web server functionality to simplify its APIs and add helpful new features. It makes it easier to organize your application’s functionality with middleware and routing. When working with Express.js you may encounter scenarios where you need to pass variables from your server-side code
2 min read