DEV Community

Dastagir2k
Dastagir2k

Posted on

Understanding Variables in JavaScript

A Beginner’s Guide to JavaScript Variables

JavaScript variables are fundamental building blocks in programming. They are used to store and manipulate data throughout your code. Whether you're a beginner or brushing up on JavaScript, understanding variables and their behavior is essential.

What are Variables in JavaScript?

A variable is a container for storing information that you can use and manipulate in your program. In simpler terms, think of it as a way to store the information you need, such as numbers, strings, or other data types.

Key points about variables in JavaScript:

  • JavaScript is a dynamically typed language, meaning the type of a variable is determined at runtime.
  • There’s no need to explicitly define the type of a variable.

JavaScript allows storing variables in four ways:

  1. Automatically
  2. Using let
  3. Using var
  4. Using const

JavaScript Variable Naming Rules

Yes, there are rules for naming variables! Here’s what you should know:

  1. Allowed Characters: Variable names can only include letters (a-z, A-Z), numbers (0-9), $, and _.
    • Example: Name, data1, sum
  2. Start Rule: Variable names must not start with a number.
    • Invalid Example: 1data, 10Name
  3. Case-Sensitivity: Variable names are case-sensitive. For instance, result and Result are two different variables.
  4. Avoid Keywords: Do not use reserved words like let, return, or const as variable names.
  5. CamelCase Style: Use camelCase, e.g., phoneNumber instead of phonenumber or PhoneNumber.
  6. No Hyphens: Hyphens (-) are not allowed in variable names.
  7. Meaningful Names: Always use descriptive names that clearly indicate what the variable stores.
  8. Avoid Single Letters: Avoid single-letter names (e.g., x, a) unless necessary (e.g., in loops).

Types of Variables in JavaScript

1. Automatically

JavaScript can assign values to variables without explicitly declaring them:

x = 5; // Variable x stores integer 5.  
y = 10; // Variable y stores integer 10.  
z = x + y; // Variable z stores the sum of x and y (15).  
console.log(z); // Output: 15  
Enter fullscreen mode Exit fullscreen mode

2. Using var

  • Variables declared with var are function-scoped or global-scoped.
  • Introduced in the earliest versions of JavaScript. It’s now considered outdated and often replaced by let or const.

Syntax:

var variable_name = value;
Enter fullscreen mode Exit fullscreen mode

Example:

var numOne = 20;  
var numTwo = 30;  

var result = numOne + numTwo; // result = 20 + 30  
console.log('Result is:', result);  
Enter fullscreen mode Exit fullscreen mode

3. Using let

  • Introduced in ES6, let is block-scoped.
  • It allows variable values to be updated but not re-declared in the same scope.

Syntax:

let variable_name = value;
Enter fullscreen mode Exit fullscreen mode

Example:

let a = 10;  
a = 15; // Allowed: Updating the value  
console.log(a); // Output: 15  

let b = 20;  
// let b = 25; // Error: Cannot re-declare variable in the same scope  
Enter fullscreen mode Exit fullscreen mode

4. Using const

  • Introduced in ES6, const is also block-scoped.
  • Its value cannot be updated or re-declared.

Syntax:

const variable_name = value;
Enter fullscreen mode Exit fullscreen mode

Example:

const PI = 3.14;  
console.log(PI); // Output: 3.14  

// PI = 3.15; // Error: Cannot update value  
Enter fullscreen mode Exit fullscreen mode

Differences Between var, let, and const

Keyword Scope Can Update? Can Re-declare? Notes
var Function-scoped Yes Yes Does not respect block scope.
let Block-scoped Yes No Use for variables that need updating.
const Block-scoped No No Best for constants and immutable values.

JavaScript Scope

The scope of a variable determines where it can be accessed in your program.

Global Scope: Accessible everywhere.

var globalVar = "I am global";  
console.log(globalVar); // Output: I am global  
Enter fullscreen mode Exit fullscreen mode

Local Scope: Declared inside a function and accessible only within it.

function showLocal() {  
    var localVar = "I am local";  
    console.log(localVar);  
}  
showLocal(); // Output: I am local  
// console.log(localVar); // Error: localVar is not defined  
Enter fullscreen mode Exit fullscreen mode

Block Scope: Available only inside the block it’s declared in.

if (true) {  
    let blockVar = "I am block-scoped";  
    const blockConst = "I am also block-scoped";  
}  
// console.log(blockVar, blockConst); // Error: Not accessible outside the block  
Enter fullscreen mode Exit fullscreen mode

Function Scope: Specific to variables declared with var.


Important Notes

Hoisting:

  • Variables declared using var are hoisted to the top of their scope but remain uninitialized until execution.
  • Variables declared with let and const are also hoisted but are in a "temporal dead zone" until their declaration.

Example:

console.log(a); // Undefined due to hoisting  
var a = 10;  

// console.log(b); // ReferenceError: Cannot access 'b' before initialization  
let b = 20;  
Enter fullscreen mode Exit fullscreen mode

Best Practices

  1. Use const for values that do not change.
  2. Use let for variables that will be updated.
  3. Avoid using var in modern JavaScript.

Common Interview Questions

  1. What are the differences between var, let, and const?
  2. What is the scope of a variable in JavaScript?
  3. Explain variable hoisting with examples.
  4. Can you reassign values to a variable declared with const?
  5. What happens if you declare a variable without using var, let, or const?
  6. Why is it recommended to use let and const instead of var?
  7. What is the temporal dead zone in JavaScript?
  8. Write a code snippet to demonstrate block scope using let and const.
  9. What is dynamic typing in JavaScript?
  10. How does JavaScript handle variable re-declaration?

Top comments (0)