JS Variables

In JavaScript, variables are used to store data values. They act as containers to hold values like numbers, strings, objects, etc.


Declaring Variables in JavaScript:

You can declare JavaScript variables using:

  • var (old way, avoid using in modern code)
  • let (block-scoped, preferred for variable values that change)
  • const (block-scoped, preferred for constants or values that won't change)
Example
var oldVariable = "I am a var variable"; // Avoid using
let modernVariable = "I am a let variable"; // Preferred for mutable variables
const constantVariable = "I am a const variable"; // Preferred for immutable variables

Variable Rules:

  • Variable names must start with a letter, _, or $.
  • Variable names are case-sensitive (myVar is different from MyVar).
  • Reserved JavaScript keywords cannot be used as variable names (var, let, const).
Valid Examples:
let userName = "Alice";
let _id = 123;
let $price = 99.99;
Invalid Examples:
let 1user = "Error"; // Cannot start with a number
let let = "Error"; // Reserved keyword

Differences Between var, let, and const

Keyword

Scope

Can Reassign?

Can Redeclare?

Hoisting

var

Function Scope

Yes

Yes

Hoisted with undefined

let

Block Scope

Yes

No

Hoisted without initialization

const

Block Scope

No

No

Hoisted without initialization

Example Comparison:
// var example
var x = 10;
if (true) {
var x = 20; // Same variable is overwritten
}
console.log(x); // Output: 20

// let example
let y = 10;
if (true) {
let y = 20; // Different variable (block scope)
}
console.log(y); // Output: 10

// const example
const z = 10;
z = 20; // Error: Assignment to constant variable

Try it yourself


Variable Scope:

1. Global Scope:

  • Variables declared outside any function or block are global.
  • Accessible anywhere in the code.

2. Function Scope:

  • Variables declared with var inside a function are function-scoped.

3. Block Scope:

  • Variables declared with let and const inside a block {} are block-scoped.
Example
function exampleFunction() {
var functionVar = "I am function-scoped";
let blockVar = "I am block-scoped";
if (true) {
let insideBlock = "Only accessible here";
}
console.log(functionVar); // Works
// console.log(insideBlock); // Error: not defined
}

Try it yourself


Variable Hoisting:

  • Variables declared with var are hoisted to the top of their scope and initialized with undefined.
  • Variables declared with let and const are hoisted but not initialized.
Example
console.log(a); // undefined (hoisted with var)
var a = 5;

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

Best Practices for Variables:

  • ✅ Use const by default.
  • ✅ Use let if the variable needs to change.
  • ❌ Avoid var unless absolutely necessary.
  • ✅ Use meaningful variable names (userAge, totalPrice).
  • ✅ Follow camelCase naming convention (firstName, lastValue).

Data Types of Variables

JavaScript variables can store values of different data types:

  • String: "Hello"
  • Number: 42
  • Boolean: true / false
  • Null: null
  • Undefined: undefined
  • Object: { key: "value" }
  • Array: [1, 2, 3]
  • Function: function() {}
Example
let name = "John"; // String
let age = 30; // Number
let isActive = true; // Boolean
let user = { id: 1, name: "Alice" }; // Object

Constants in JavaScript (const)

  • Must be initialized at declaration.
  • Cannot be reassigned.
  • Object and array values can still be modified (only the reference is constant).
Example
const user = { name: "Alice" };
user.name = "Bob"; // Allowed

// user = { name: "Eve" }; // Error: Assignment to constant variable

Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.