Understanding JavaScript Variables – DEV Community
December 23, 2024

Understanding JavaScript Variables – DEV Community


introduce

variable In JavaScript, it is like a container for storing data. Think of them like labeled jars in the kitchen – some hold sugar, some hold flour, some even hold cookies! 🍪They bring your code to life and enable you to store and manipulate information.

Variable declaration, initialization and naming conventions
1️⃣ declaration
Declaring a variable means creating it without assigning a value.
📌 Example:

let name; // Declaration
Enter full screen mode

Exit full screen mode

2️⃣ initialization
Initializing a variable means assigning a value to it for the first time.
📌 Example:

let name = "Richa"; // Declaration + Initialization
Enter full screen mode

Exit full screen mode

You can also declare it first and then initialize it:
📌 Example:

let age; // Declaration
age = 25; // Initialization
console.log(age); // Outputs: 25
Enter full screen mode

Exit full screen mode

3️⃣ naming convention
Follow these rules to name variables efficiently:

  • Start with a letter, $or _. Valid: userName, _temp, $amountInvalid: 123name, @value
  • Avoid reserved keywords: Invalid: let var = 10; (cannot be used var as a name)
  • Use camelCase notation for better readability: example: firstName, totalCost
  • Be descriptive: instead of xuse userAge or productName.

📌 Example:

let userName = "John"; // Descriptive and camelCase
const MAX_USERS = 100; // Use uppercase for constants
let _tempValue = 42; // Valid use of underscore
let $price = 99.99; // Valid use of $
Enter full screen mode

Exit full screen mode

variable type
JavaScript provides three ways to declare variables: var, letand const.

1️⃣ Yes (old school)
scope: Function scope or global scope.
usage: Due to its quirks, it’s best avoided in modern JavaScript.
this var Keywords were popular in JavaScript before 2015.
📌 Example:

var stuff = "Toy";
var stuff = "Book"; // Re-declaration allowed (confusing behavior).
console.log(stuff); // Outputs: Book
Enter full screen mode

Exit full screen mode

and varyou can declare the same variable multiple times. However, this often results in buggy and confusing code.
⁉️hanging Behavior:
declared variables var are “promoted”, which means you can use them before declaring them.
📌 Example:

console.log(stuff); // Outputs: undefined
var stuff = "Toy";
Enter full screen mode

Exit full screen mode

This behavior may cause unexpected problems, so avoid relying on var Used for variable declaration.
👉A real world example

2️⃣ let (flexible)
scope:Block scope (only the declared block).
usage: use let When the variable value needs to be changed.
📌 Example:

let jar = "Tomatos";
jar = "Spices"; // Allowed
console.log(jar); // Outputs: Spices
Enter full screen mode

Exit full screen mode

Try redeclaring let Variables will throw an error:
📌 Example:

let jar = "Tomatos";
let jar = "Spices"; // Error: Identifier 'jar' has already been declared
Enter full screen mode

Exit full screen mode

unlike varthe declared variable let Not hoisted in the same way:
📌 Example:

console.log(jar); // ReferenceError: Cannot access 'jar' before initialization
let jar = "Tomatos";
Enter full screen mode

Exit full screen mode

👉A real world example

3️⃣ const (immutable)
scope: block scope, e.g. let
usage: use const For values ​​that should not change after initialization.
const Great for declaring constants or variables that should not be reassigned.
📌 Example:

const packet = "Milk";
packet = "Juice"; // Error: Assignment to constant variable
Enter full screen mode

Exit full screen mode

You must initialize a const When declaring a variable:
📌 Example:

const packet; // Error: Missing initializer in const declaration
Enter full screen mode

Exit full screen mode

👉A real world example


The task of exploring variables

Here are some examples to test your understanding of variables:

/* Task 1: */ 
let age = 4;
console.log(age); // Outputs: 4

/* Uncomment the following to see errors: */
/* const age = 10; // SyntaxError: Identifier 'age' has already been declared */

/* Task 2: */
const salary = 2000; // Correct
console.log(salary);

/* Task 3: */
/* const salary; // SyntaxError: Missing initializer in const declaration */

/* Task 4: */
/* const salary = 0;
console.log(salary);
salary = 10; // TypeError: Assignment to constant variable */
Enter full screen mode

Exit full screen mode


in conclusion

Mastering variables is the first step to writing clean, efficient JavaScript code.

  • use const Be as stable as possible.
  • use let Only if the value needs to be changed.
  • avoid var to prevent difficult-to-debug problems.

Happy coding! 🎉

2024-12-23 06:30:00

Leave a Reply

Your email address will not be published. Required fields are marked *