JavaScript Variables
Learn how to declare and use variables in JavaScript using var, let, and const.
In JavaScript, a variable is a named container used to store and manage data values within a program. These values can represent numbers, text (strings), boolean values, objects, arrays, or even functions, depending on the needs of the application.
Variables allow developers to store information once and reuse it throughout the code, making programs more dynamic, efficient, and easier to maintain. Without variables, handling changing data would be complex and repetitive.
In JavaScript, variables can be declared using the keywords var, let, or const. Each of these keywords differs in terms of scope, reassignment behavior, and recommended usage in modern JavaScript development.
Why Use Variables in JavaScript?
- Store and manage changing data: Variables act as placeholders for values that may change while a program is running, such as user input or calculated results.
- Improve code readability and structure: Using clear and descriptive variable names makes your code easier to read, understand, and maintain—especially in large projects.
- Enhance reusability and efficiency: Once a value is stored in a variable, it can be reused multiple times without rewriting the same data, reducing duplication.
- Support dynamic and interactive applications: Variables are essential for building responsive web applications that react to user actions and real-time data changes.
Rules for Naming Variables in JavaScript
When declaring variables in JavaScript, developers must follow a set of strict naming rules. These rules define what are known as valid identifiers and help ensure that the code runs correctly without syntax errors.
- Variable names must begin with a letter (a–z or A–Z), an underscore (_), or a dollar sign ($). They cannot start with a number.
-
After the first character, numbers (0–9) are allowed.
Example:value1,user2 -
Variable names are case-sensitive, meaning uppercase and lowercase letters are treated
differently.
Example:countandCountrefer to two different variables. -
JavaScript reserved keywords (such as
if,for,return, andclass) cannot be used as variable names, as they have special meanings in the language.
Example: Declaring and Using Variables
JavaScript Example
// Declaring variables
let name = "John";
const age = 25;
// Using variables
console.log("Name:", name);
console.log("Age:", age);
Try it Yourself »
Declaring Variables in JavaScript
In JavaScript, variables are used to store data values that can be accessed, reused, and modified throughout a program. Declaring a variable means creating a named reference that points to a value in memory.
JavaScript provides three keywords for declaring variables: var, let, and const. Each keyword differs in terms of scope, reassignment rules, and recommended usage in modern JavaScript development.
There are three main ways to declare variables in JavaScript:
1. Using var Keyword
The var keyword was the original way to declare variables in JavaScript.
Variables declared with var are function-scoped, meaning they are
accessible anywhere within the function in which they are declared, regardless of block boundaries.
This behavior can lead to unexpected bugs, especially in large or complex applications.
For this reason, the use of var is generally discouraged in modern JavaScript
in favor of let and const.
var a = "TpointTech";
console.log(a);
2. Using let Keyword
The let keyword was introduced in ES6 (ECMAScript 2015) to address the limitations
of var. Variables declared with let are block-scoped,
meaning they are only accessible within the block { } in which they are defined,
such as inside loops or conditional statements.
This block-level scoping makes let more predictable and safer to use,
reducing the risk of accidental variable redeclaration or scope-related errors.
As a result, let is widely recommended for variables whose values may change.
let a = 20;
console.log(a);
3. Using const Keyword
The const keyword is used to declare variables whose values
should remain constant after initialization. Once a value is assigned to a
const variable, it cannot be reassigned,
which helps protect important data from being modified unintentionally.
Variables declared with const are block-scoped,
similar to let. While the variable itself cannot be reassigned,
it is important to note that if the value is an object or an array,
its internal properties or elements can still be modified.
Because of its safety and predictability, const is the
recommended default choice for variable declarations in
modern JavaScript when the value is not expected to change.
const p = "TpointTech"; console.log(p);
JavaScript Variable Data Types
In JavaScript, variables can store different kinds of data, known as data types. Data types define the type of value a variable holds and determine how that value can be processed, stored in memory, and manipulated during program execution.
JavaScript is a dynamically typed language, meaning a variable’s data type is determined automatically at runtime based on the assigned value. Below are the most commonly used JavaScript data types:
-
String: Represents textual data enclosed in single quotes, double quotes,
or backticks. Strings are commonly used for names, messages, and other text content.
Example:"Hello, JavaScript" -
Number: Represents numeric values, including both integers and floating-point
numbers. JavaScript uses a single number type for all numeric values.
Example:100,3.14 -
Boolean: Represents logical values that can be either
trueorfalse. Booleans are commonly used in conditional statements and comparisons. - Undefined: Indicates that a variable has been declared but has not yet been assigned a value by the program.
- Null: Represents an intentional and explicit absence of any object value. It is often used to reset a variable or indicate that a value is intentionally empty.
- Object: Represents a collection of related data stored as key–value pairs. Objects are used to model real-world entities and complex data structures.
- Array: Represents an ordered list of values stored in a single variable. Arrays are commonly used to store collections of related data items.
Types of Variables in JavaScript
In JavaScript, variables are classified primarily based on their scope— that is, where they can be accessed within a program—and how they are intended to be used. Choosing the appropriate type of variable improves code readability, reliability, and long-term maintainability.
There are two main types of variables in JavaScript: local variables and global variables.
JavaScript Local Variable
A local variable is declared inside a function or a block using
let or const. It is accessible only within the scope in which
it is defined and cannot be used outside that function or block.
Once the execution of the function or block is complete, the local variable is no longer accessible.
Example 1: Local Variable Scope
JavaScript Example
// Function with a local variable
function showMessage() {
let message = "Hello from Local Variable";
console.log(message);
}
showMessage();
console.log(message);
Try it Yourself »
Example 2: Same Local Variable Name in Different Functions
JavaScript Example
// Each function has its own local variable
function calculateOrderTotal() {
let total = 150;
console.log("Order Total:", total);
}
function calculateDiscountTotal() {
let total = 30;
console.log("Discount Total:", total);
}
calculateOrderTotal();
calculateDiscountTotal();
Try it Yourself »
JavaScript Global Variable
A global variable is declared outside of any function or block and is accessible from anywhere within the script. Because global variables can be read and modified by multiple parts of a program, they should be used cautiously to avoid unintended side effects and naming conflicts.
Example: Global Variable Usage
JavaScript Example
// Global variable
let appName = "Funcoding";
function displayAppName() {
console.log("Application Name:", appName);
}
displayAppName();
// Updating the global variable
appName = "Funcoding Pro";
console.log("Updated Application Name:", appName);
Try it Yourself »
Best Practices for Using JavaScript Variables
-
Prefer
letandconstovervarto avoid scope-related issues and unexpected behavior. - Use clear and descriptive variable names that accurately describe the data they store and their role in the program.
-
Follow the camelCase naming convention
(for example,
totalScore) to maintain consistency with JavaScript standards. -
Use
constby default and switch toletonly when reassignment is required. - Minimize the use of global variables to reduce the risk of name collisions, unintended side effects, and hard-to-track bugs.
JavaScript Variables – FAQs
What is the difference between var, let, and const?
The var keyword uses function scope, which can lead to
unexpected results in complex programs. In contrast, let and const
use block scope, providing better control and predictability.
Additionally, variables declared with const cannot be reassigned after initialization.
Should I still use var in JavaScript?
In modern JavaScript development, the use of var is generally discouraged.
Developers are advised to use let and const instead,
as they provide clearer scoping rules and help prevent common programming errors.
Can objects declared with const be modified?
Yes. When an object is declared using const, the variable reference itself
cannot be reassigned. However, the properties or elements within the object
can still be modified.