Working with Variables in JavaScript
- in JavaScript, variables are containers for storing data values .
- They allow you to name and reuse values (e.g., numbers, strings, booleans, objects) throughout your code.
JavaScript offers three keywords for declaring variables: var, let, and const. Each has distinct behavior.
- The traditional way to declare variables. It has function scope or global scope if declared outside a function.
- Variables declared with
varcan be redeclared and reassigned.
var name = "Alex";var name = "Sam"; // Redeclaration OKname = "Jess"; // Reassignment OKconsole.log(name); // "Jess"javascript
- Issue: Hoisting (moved to top of scope) can lead to bugs.
console.log(x); // undefined (not an error!)var x = 5;javascript
- Introduced in ECMAScript 6 (ES6, 2015).
- Block-scoped, can be reassigned but not redeclared in the same scope.
letprovides better control over variable scoping compared tovar
let age = 25;age = 26; // OKlet age = 30; // Error: Cannot redeclareconsole.log(age); // 26javascript
- Also introduced in ES6,
constis used to declare variables that cannot be reassigned or redeclared after their initial value has been set. constis block scoped.
const pi = 3.14;pi = 3.15; // Error: Assignment to constantconst person = { name: "Alex" };person.name = "Sam"; // OK (object mutation)console.log(person.name); // "Sam"javascript
Variables are assigned values using the = operator.
- For
constvariables, the value must be assigned during declaration and cannot be reassigned afterward.
let name = "Josée"; // Assign a string to 'name'name = "Bob"; // Reassign the value of "Bob" to 'name'javascript
The scope of a variable determines where in the code the variable can be accessed.
- Declared outside functions, accessible everywhere.
let globalVar = "I'm everywhere";function logIt() { console.log(globalVar); // "I’m everywhere"}logIt();javascript
varis limited to the function it’s declared in.
function test() { var localVar = "I'm local"; console.log(localVar); // "I’m local"}test();console.log(localVar); // Error: localVar is not definedjavascript
letandconstare limited to{}blocks (e.g.,if,for).
if (true) { let blockVar = "I'm trapped"; console.log(blockVar); // "I’m trapped"}console.log(blockVar); // Error: blockVar is not definedjavascript
// Global scopelet globalVar = "I am global";
function testScope() { var functionVar = "I am inside the function"; // Function scope let blockVar = "I am inside a block"; // Block scope
if (true) { let innerBlockVar = "I am inside an if block"; // Block scope console.log(innerBlockVar); // Accessible here }
// console.log(innerBlockVar); // Error: innerBlockVar is not defined outside the if block}
testScope();// console.log(functionVar); // Error: functionVar is not defined outside the functionconsole.log(globalVar); // Accessible globallyjavascript