Reading Time 3
Number of Words 465
In JavaScript, a variable is a named storage location that holds a value. Variables allow you to store data and manipulate it throughout your program. For example:
let age = 25; const name = "John";
Declaring Variables
JavaScript provides three main ways to declare variables:
-
var: This is the oldest way to declare variables. It has function scope, meaning the variable is available within the function it is declared in, even if it’s inside a block likeiforfor. Its use is discouraged in modern code due to unexpected behaviors. -
let: Introduced in ECMAScript 6 (ES6),letdeclares variables with block scope, which means the variable is only available within the block where it is defined. This prevents many scope-related errors. -
const: Also introduced in ES6,constis used to declare variables whose value cannot be reassigned after the initial assignment. Likelet, it has block scope.
let x = 10; // a variable that can change its value const y = 20; // a constant whose value cannot change
Assigning Values
Once a variable is declared, you can assign a value using the assignment operator =:
let message; message = "Hello, world!";
You can also declare and assign a value in one line:
let greeting = "Welcome!";
Rules for Variable Names
When naming variables in JavaScript, follow these rules:
-
Names can contain letters, digits, underscores (
_), and dollar signs ($). -
Names must start with a letter, underscore, or dollar sign.
-
Variable names are case-sensitive (
ageandAgeare different). -
Names cannot be reserved keywords (like
let,const,function, etc.).
Best Practices
-
Use
constby default to prevent accidental changes to values that should remain constant. -
Use
letwhen you need to reassign a variable’s value. -
Avoid using
vardue to its unpredictable function scope. -
Choose descriptive variable names that clearly indicate their purpose.
Code example with variables without errors
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div>TODO write content</div>
<script type="text/javascript">
console.log(text2);
const name = "myName";
let text = 'myLetText';
var text2 = 'myVarText';
console.log(name);
console.log(text);
console.log(text2);
</script>
</body>
</html>