Variables are the containers for storing values or expressions They are used to store data temporarily in the computer
Example
section = "3U"
console.log(section)
⚖️ Rules for js variables
- Case sensitive
- Must start with an an alphabet or underscore
- Cannot start with a number
- Cannot use reserved words as variables
- Should be meaningful
- Cannot contain space or hyphen (-)
Here are few examples:
- score ✅
- _id ✅
- 01 🚫
- await 🚫
📢 Declaration of varaibles
There are three methods of declaring a variable in js
- let keyword
- const keyword
- var keyword
| Keyword | Access | Assignment | Initialise |
|---|---|---|---|
| let | {...} | Reassignable | Optional |
| const | {...} | Final | Required |
| var | function | Reassignable | Optional |
Reassignment
let count = 0
count = 1 //This works
const count = 0
count = 1 //This doesn't work
var count = 0
count = 1 //This works
Accessibility
{
let blockVariable = "I am hidden";
var functionVariable = "I am visible";
}
console.log(blockVariable); //This doesn't work
console.log(functionVariable); //This works
Declearing multiple variables
// Both works
let name="Rohan" , role="Student";
let name="Rohan";
let role="Student";
Note
- If you assign values to variables that have not yet been declared, the variables will automatically be declared.
x = 120; // No error here
- "var" has some confusing behaviors regarding scope and hoisting, so modern developers generally avoid it in favor of let and const.
Comments
Join the discussionNo comments yet. Be the first to comment.
Decode Javascript
Explore JavaScript one concept at a time, from the fundamentals to advanced topics. Learn through clear explanations, practical examples, and code as we uncover how JavaScript works and use it to build for the web.
