How do you declare and use variables in JavaScript?

Variables are fundamental building blocks in JavaScript that allow you to store and manipulate data in your programs. They serve as named containers for values that can be accessed and modified throughout your code.

Variable Declaration in JavaScript

JavaScript provides three primary ways to declare variables, each with different behaviors regarding scope, hoisting, and reassignment capabilities:

1. Using var (Pre-ES6)

var name = "Rahul";
var age = 30;
var isActive = true;

2. Using let (ES6+)

let name = "Priya";
let age = 25;
let isActive = true;

3. Using const (ES6+)

const PI = 3.14159;
const API_URL = "https://api.example.com";
const MAX_ATTEMPTS = 3;

Variable Declaration Without Assignment

You can declare variables without assigning values (except for const, which requires immediate initialization):

var count;       // undefined
let score;       // undefined
// const total;  // SyntaxError: Missing initializer in const declaration

Multiple Variable Declarations

You can declare multiple variables in a single statement:

// Using var
var firstName = "Rahul", lastName = "Sharma", age = 30;

// Using let
let x = 10, y = 20, z = 30;

// Using const
const MIN = 0, MAX = 100, AVERAGE = 50;

However, for better readability, it’s often recommended to declare variables on separate lines:

let firstName = "Rahul";
let lastName = "Sharma";
let age = 30;

Variable Naming Rules and Conventions

Rules (Must Follow)

  1. Names can contain letters, digits, underscores, and dollar signs
  2. Names must begin with a letter, underscore (_), or dollar sign ($)
  3. Names are case-sensitive (name and Name are different variables)
  4. Reserved words (like if, function, return) cannot be used as variable names

Conventions (Best Practices)

  1. Use camelCase for variable names (e.g., firstName, totalAmount)
  2. Use UPPER_CASE for constants (e.g., MAX_SIZE, API_KEY)
  3. Begin private variables with underscore (e.g., _privateValue)
  4. Use descriptive names that explain the purpose of the variable
  5. Avoid single-letter names except for simple loop counters
// Good variable names
let firstName = "Rahul";
let totalAmount = 1250.75;
const MAX_USERS = 100;
let _privateData = { key: "value" };

// Avoid these
let x = "Rahul";          // Not descriptive
let fn = "Rahul";         // Too abbreviated
let theUserFirstName = "Rahul"; // Too verbose

Variable Scope

Scope determines where variables are accessible in your code.

Global Scope

Variables declared outside any function or block have global scope and can be accessed from anywhere in the code:

// Global variable
var globalVar = "I'm global";
let globalLet = "I'm also global";
const GLOBAL_CONST = "I'm a global constant";

function testScope() {
  console.log(globalVar);      // "I'm global"
  console.log(globalLet);      // "I'm also global"
  console.log(GLOBAL_CONST);   // "I'm a global constant"
}

testScope();

Function Scope

Variables declared inside a function are only accessible within that function:

function testFunctionScope() {
  var functionVar = "I'm function-scoped";
  let functionLet = "I'm also function-scoped";
  
  console.log(functionVar);    // "I'm function-scoped"
  console.log(functionLet);    // "I'm also function-scoped"
}

testFunctionScope();
// console.log(functionVar);   // ReferenceError: functionVar is not defined
// console.log(functionLet);   // ReferenceError: functionLet is not defined

Block Scope

Variables declared with let and const are block-scoped, meaning they are only accessible within the block (enclosed by {}) where they are defined:

if (true) {
  var varInBlock = "I'm var in a block";
  let letInBlock = "I'm let in a block";
  const CONST_IN_BLOCK = "I'm const in a block";
}

console.log(varInBlock);        // "I'm var in a block" (var is not block-scoped)
// console.log(letInBlock);     // ReferenceError: letInBlock is not defined
// console.log(CONST_IN_BLOCK); // ReferenceError: CONST_IN_BLOCK is not defined

Lexical Scope (Closure)

Inner functions have access to variables declared in their outer functions:

function outerFunction() {
  let outerVar = "I'm from the outer function";
  
  function innerFunction() {
    console.log(outerVar);  // "I'm from the outer function"
  }
  
  innerFunction();
}

outerFunction();

Variable Hoisting

Hoisting is JavaScript’s default behavior of moving declarations to the top of their scope during the compilation phase.

Hoisting with var

console.log(hoistedVar);  // undefined (not ReferenceError)
var hoistedVar = "I'm hoisted";

// Equivalent to:
var hoistedVar;
console.log(hoistedVar);
hoistedVar = "I'm hoisted";

Hoisting with let and const

Variables declared with let and const are hoisted but not initialized, creating a “Temporal Dead Zone”:

// console.log(hoistedLet);  // ReferenceError: Cannot access 'hoistedLet' before initialization
let hoistedLet = "I'm hoisted but not accessible";

// console.log(hoistedConst);  // ReferenceError: Cannot access 'hoistedConst' before initialization
const hoistedConst = "I'm also hoisted but not accessible";

Variable Assignment and Reassignment

Assignment

Assignment gives a value to a variable:

let message;
message = "Hello, world!";  // Assignment

let count = 10;  // Declaration with assignment

Reassignment

Changing the value of an existing variable:

let score = 75;
console.log(score);  // 75

score = 90;
console.log(score);  // 90

Variables declared with const cannot be reassigned:

const PI = 3.14159;
// PI = 3;  // TypeError: Assignment to constant variable

However, for objects and arrays declared with const, the properties or elements can be modified:

const user = {
  name: "Rahul",
  age: 30
};

user.age = 31;  // Valid - modifying a property
// user = { name: "Priya" };  // TypeError: Assignment to constant variable

const numbers = [1, 2, 3];
numbers.push(4);  // Valid - modifying the array
// numbers = [5, 6];  // TypeError: Assignment to constant variable

Variable Types and Dynamic Typing

JavaScript is a dynamically typed language, meaning variables can hold values of any type, and the type can change during execution:

let value = 42;        // Number
value = "Hello";       // String
value = true;          // Boolean
value = null;          // Null
value = undefined;     // Undefined
value = { key: 42 };   // Object
value = [1, 2, 3];     // Array (which is an Object)
value = function() {}; // Function (which is an Object)

Type Checking and Conversion

Checking Variable Types

let value = 42;
console.log(typeof value);  // "number"

value = "Hello";
console.log(typeof value);  // "string"

value = true;
console.log(typeof value);  // "boolean"

value = null;
console.log(typeof value);  // "object" (this is a known bug in JavaScript)

value = undefined;
console.log(typeof value);  // "undefined"

value = {};
console.log(typeof value);  // "object"

value = [];
console.log(typeof value);  // "object"
console.log(Array.isArray(value));  // true

value = function() {};
console.log(typeof value);  // "function"

Type Conversion

// String to Number
let strNum = "42";
let num = Number(strNum);  // 42
num = parseInt(strNum, 10);  // 42
num = +strNum;  // 42

// Number to String
let number = 42;
let str = String(number);  // "42"
str = number.toString();  // "42"
str = number + "";  // "42"

// Boolean Conversion
let value = 0;
let bool = Boolean(value);  // false
bool = !!value;  // false (shorthand)

value = 1;
bool = Boolean(value);  // true
bool = !!value;  // true (shorthand)

Variable Destructuring (ES6+)

Destructuring allows you to extract values from arrays or properties from objects into distinct variables:

Array Destructuring

const numbers = [1, 2, 3, 4, 5];

// Basic destructuring
const [first, second, third] = numbers;
console.log(first, second, third);  // 1 2 3

// Skip elements
const [a, , c] = numbers;
console.log(a, c);  // 1 3

// Rest pattern
const [head, ...tail] = numbers;
console.log(head, tail);  // 1 [2, 3, 4, 5]

// Default values
const [x = 0, y = 0, z = 0] = [1, 2];
console.log(x, y, z);  // 1 2 0

Object Destructuring

const person = {
  name: "Rahul",
  age: 30,
  city: "Mumbai",
  country: "India"
};

// Basic destructuring
const { name, age } = person;
console.log(name, age);  // "Rahul" 30

// Rename variables
const { name: fullName, age: years } = person;
console.log(fullName, years);  // "Rahul" 30

// Default values
const { name: userName, role = "User" } = person;
console.log(userName, role);  // "Rahul" "User"

// Rest pattern
const { name: personName, ...details } = person;
console.log(personName, details);  // "Rahul" { age: 30, city: "Mumbai", country: "India" }

Nested Destructuring

const user = {
  name: "Rahul",
  age: 30,
  address: {
    city: "Mumbai",
    state: "Maharashtra",
    country: "India"
  },
  skills: ["JavaScript", "React", "Node.js"]
};

// Nested object destructuring
const { name, address: { city, country } } = user;
console.log(name, city, country);  // "Rahul" "Mumbai" "India"

// Nested array destructuring
const { skills: [primarySkill, secondarySkill] } = user;
console.log(primarySkill, secondarySkill);  // "JavaScript" "React"

Variable Declaration Best Practices

  1. Use const by default

    // Prefer const for values that won't change
    const API_URL = "https://api.example.com";
    const user = { name: "Rahul" };
  2. Use let when you need to reassign

    // Use let for counters, accumulators, etc.
    let count = 0;
    for (let i = 0; i < 10; i++) {
      count += i;
    }
  3. Avoid var in modern code

    // Avoid var due to its function scope and hoisting behavior
    // var message = "Hello";  // Not recommended
    let message = "Hello";     // Better
  4. Declare variables at the top of their scope

    function processData(data) {
      // Declare all variables at the top
      const results = [];
      let count = 0;
      let isValid = false;
      
      // Rest of the function...
    }
  5. Use descriptive variable names

    // Not descriptive
    const x = getUserData();
    
    // Descriptive
    const userData = getUserData();
  6. Group related variables

    // Related to user
    const userName = "Rahul";
    const userAge = 30;
    const userRole = "Admin";
    
    // Related to configuration
    const API_URL = "https://api.example.com";
    const MAX_RETRIES = 3;
    const TIMEOUT_MS = 5000;

Interview Tips

  • Explain the differences between var, let, and const regarding scope, hoisting, and reassignment
  • Discuss variable naming conventions and best practices
  • Explain the concept of variable scope and how it affects accessibility
  • Describe how hoisting works with different variable declarations
  • Demonstrate knowledge of destructuring for arrays and objects
  • Highlight the dynamic typing nature of JavaScript
  • Share best practices for variable declarations in modern JavaScript
  • Be prepared to write code examples that demonstrate variable behavior

Test Your Knowledge

Take a quick quiz to test your understanding of this topic.