Variables-tutorial
In JavaScript, variables are like containers that store data such as numbers, text, objects, or even functions.
They help you manage and use data in your programs dynamically.
They help you manage and use data in your programs dynamically.
Key Point
- Variables are used to store and manage data in JavaScript.
- Variables can be declared using: var, let, and const.
There are two main types of variables based on scope
- Local variables
- Global variables
How to Declare Variables in JavaScript
JavaScript has three keywords to declare variables, each with unique features
var
Example:
- Function-scoped (visible inside the entire function where declared).
- Hoisted to the top of its scope (can be accessed before declaration but value is undefined until assigned).
Example:
function example() { var x = 14; if (true) { var x = 20; // re-declares x within the same function scope } console.log(x); // Outputs: 20}example();
let
Example:
- Block-scoped (only accessible within the nearest curly braces { }).
- Not hoisted in the same way as var.
Example:
if (true) { let y = 30;}// console.log(y); // Error: y is not defined outside the block
const
Example:
- Block-scoped.
- Must be initialized when declared.
- Cannot be reassigned (but if it holds an object, the object’s content can still change).
Example:
const b = 70;// b = 80; // Error: Assignment to constant variable
Difference between var, let and const
Feature | var | let | const |
---|---|---|---|
Scope | Function scope | Block scope | Block scope |
Hoisting | Yes | No (temporal dead zone) | No (temporal dead zone) |
Re-declare | Allowed | Not allowed in same scope | Not allowed in same scope |
Reassign | Allowed | Allowed | Not allowed |
Types of Variables: Local & Global
Local Variables
Declared inside a function or block; only accessible there.
Example:
<script>function abc() { var x = 5; // local variable}</script>
Global Variables
Declared outside any function; accessible anywhere in the code.
Example:
<html>
<body> <script> var data = 200; // global variable function a() { document.writeln(data); } function b() { document.writeln(data); } a(); // Outputs: 200 b(); // Outputs: 200 </script></body>
</html>
Output
.webp)