Webdev

JavaScript Variables:


Variables are containers used to store values that can be used and manipulated throughout a program. They play a fundamental role in programming by allowing us to hold, retrieve, and update data.

In JavaScript, variables are declared using three keywords: var, let, and const. Each of these has different behaviors and rules regarding scope, reassignment, and hoisting.


1. Declaring Variables

You declare a variable by using one of the keywords var, let, or const, followed by the variable name.

Example:

var x = 5;        // Using var
let y = 10;       // Using let
const z = 15;     // Using const

2. Variable Naming Rules

Valid Names:

let firstName;
let _age;
let $price;

Invalid Names:

let 2cool;       // Cannot start with a number
let my-name;     // Hyphen is not allowed, use underscore or camelCase

3. Assigning Values to Variables

You assign a value to a variable using the assignment operator (=).

Example:

let name = 'John';   // String
let age = 25;        // Number
let isStudent = true;  // Boolean

4. Variable Types

JavaScript is dynamically typed, which means you don’t have to specify the type of variable when declaring it. The type is automatically determined based on the value assigned.

Example:

let myString = "Hello World"; // String
let myNumber = 42;            // Number
let isTrue = false;           // Boolean
let notAssigned;              // Undefined
let emptyValue = null;        // Null

5. var, let, and const: Key Differences

var (function-scoped):

Example:

var x = 5;
var x = 10;    // No error, re-declaration is allowed
x = 20;        // No error, value can be updated

let (block-scoped):

Example:

let y = 10;
// let y = 15;  // Error: Cannot re-declare a 'let' variable in the same scope
y = 20;       // Can be updated

const (block-scoped):

Example:

const z = 100;
// z = 200;     // Error: Cannot reassign a const variable

Scope and var vs. let/const:


6. Hoisting

Example of var hoisting:

console.log(a);  // Output: undefined (hoisted but not initialized)
var a = 10;

Example of let hoisting:

console.log(b);  // Error: Cannot access 'b' before initialization
let b = 10;

7. Variable Re-assignment and Mutability


8. Best Practices for Variable Declaration


Summary


Mastering variables is an essential first step in learning JavaScript, as they are the foundation for managing data in any program.