Introduction to JavaScript Variables

Variables in JavaScript are containers that hold data values. They are fundamental to programming as they allow us to store, retrieve, and manipulate data. Understanding variables is crucial for anyone looking to write effective and efficient JavaScript code.


Declaring Variables

In JavaScript, variables can be declared using three keywords: var, let, and const. Each keyword has specific scoping rules and usage scenarios.


Using var

The var keyword was the original way to declare variables in JavaScript. Variables declared with var are function-scoped, which means they are accessible within the function they are declared in.

 

function example() {
    var x = 10;
    console.log(x); // 10
}
example();
 
  • console.log(x); // ReferenceError: x is not defined
  • In the example above, x is only accessible within the example function.


Using let

The let keyword, introduced in ECMAScript 2015 (ES6), allows for block-scoped variable declarations. A block is defined by curly braces {}.

 


{
    let y = 20;
    console.log(y); // 20
}
console.log(y); // ReferenceError: y is not defined
 

 

Here, y is only accessible within the block where it is declared.


Using const

The const keyword, also introduced in ES6, is used to declare variables that cannot be reassigned. Like let, const is block-scoped.

 


const z = 30;
console.log(z); // 30
z = 40; // TypeError: Assignment to constant variable.
 

 

While the value of a const variable cannot be changed, its properties can be modified if it is an object.

 


const person = { name: 'John', age: 25 };
person.age = 26;
console.log(person.age); // 26
 



Variable Naming Rules

When naming variables in JavaScript, follow these rules:

 

  • Variables must begin with a letter, underscore _, or dollar sign $.
  • Subsequent characters can be letters, digits, underscores, or dollar signs.
  • Variable names are case-sensitive (e.g., myVar and myvar are different variables).
  • Reserved words cannot be used as variable names (e.g., class, return, function).



Examples of Valid and Invalid Variable Names
 


// Valid variable names
let myVar;
let _myVar;
let $myVar;
let myVar1;

// Invalid variable names
let 1myVar; // Cannot start with a digit
let my-Var; // Cannot contain hyphens
let var; // Cannot use reserved keywords
 



Variable Initialization

Variables in JavaScript can be declared without initialization. If a variable is declared without being initialized, it has the value undefined.

 

 

let a;
console.log(a); // undefined



Variables can be initialized at the time of declaration.
 

let b = 5;
console.log(b); // 5

 

Multiple variables can be declared and initialized in a single statement.

 


let c = 3, d = 4, e = 5;
console.log(c, d, e); // 3 4 5
 



Scope and Hoisting

Global Scope

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

 


var globalVar = "I am global";

function checkGlobal() {
    console.log(globalVar); // I am global
}

checkGlobal();
console.log(globalVar); // I am global
 



Local Scope

Variables declared within a function or block are in the local scope and can only be accessed within that function or block.

 


function localScopeExample() {
    var localVar = "I am local";
    console.log(localVar); // I am local
}

localScopeExample();
console.log(localVar); // ReferenceError: localVar is not defined
 



Hoisting

JavaScript's default behavior of moving declarations to the top of the current scope is called hoisting. Only the declaration is hoisted, not the initialization.

 


console.log(hoistedVar); // undefined
var hoistedVar = "This variable is hoisted";

// Equivalent to:
var hoistedVar;
console.log(hoistedVar); // undefined
hoistedVar = "This variable is hoisted";
 

 

Variables declared with let and const are not hoisted in the same way as var.

 
console.log(notHoistedVar); // ReferenceError: notHoistedVar is not defined
let notHoistedVar = "This variable is not hoisted";



Data Types and Variables
 

JavaScript variables can hold different data types, including:

 

  • Primitive types: string, number, boolean, null, undefined, symbol, and bigint.
  • Reference types: object, array, and function.



Primitive Types
String

Strings are sequences of characters and can be defined using single quotes, double quotes, or backticks (template literals).


 

let str1 = 'Hello';
let str2 = "World";
let str3 = `Hello, ${str2}!`;
console.log(str3); // Hello, World!


Number

Numbers can be integers or floating-point values.

 

let intNum = 100;
let floatNum = 12.34;


Boolean

Booleans represent logical values: true or false.

 

let isTrue = true;
let isFalse = false;
 


Null

null represents the intentional absence of any object value.

 

let emptyValue = null;


Undefined

undefined indicates that a variable has not been assigned a value.

 

let notAssigned;
console.log(notAssigned); // undefined



Symbol

Symbols are unique and immutable primitive values and can be used as object property identifiers.

 

let sym1 = Symbol('description');
let sym2 = Symbol('description');
console.log(sym1 === sym2); // false


BigInt

BigInt is used for integers larger than the maximum safe integer in JavaScript (2^53 - 1).

 

let bigIntNum = 123456789012345678901234567890n;
console.log(bigIntNum); // 123456789012345678901234567890n


Reference Types

Objects

Objects are collections of key-value pairs.

 


let person = {
    name: 'Alice',
    age: 30,
    greet: function() {
        console.log('Hello, ' + this.name);
    }
};

console.log(person.name); // Alice
person.greet(); // Hello, Alice
 


Arrays

Arrays are ordered collections of values.

 

let fruits = ['Apple', 'Banana', 'Cherry'];
console.log(fruits[1]); // Banana
 


Functions

Functions are blocks of code designed to perform a particular task.

 

function add(a, b) {
    return a + b;
}

let sum = add(5, 7);
console.log(sum); // 12


Variable Best Practices

Use let and const Instead of var

Using let and const helps avoid issues related to variable hoisting and improves code readability.

 


// Use const for variables that won't be reassigned
const PI = 3.14;

// Use let for variables that may change
let radius = 5;
let area = PI * radius * radius;
console.log(area); // 78.5
 


Descriptive Variable Names

Choose meaningful and descriptive names for variables to make your code more understandable.

 

// Bad
let a = 10;
let b = 20;

// Good
let width = 10;
let height = 20;


Avoid Global Variables

Global variables can be modified from anywhere in the code, which can lead to unexpected behaviors. Use local variables as much as possible.

 

function calculateArea() {
    let length = 10;
    let breadth = 5;
    return length * breadth;
}

let area = calculateArea();
console.log(area); // 50



Use const for Constants

If a value should not change throughout the program, declare it with const.

 

const MAX_USERS = 100;
 

Variables are essential to JavaScript programming. They allow you to store, manipulate, and retrieve data within your code. Understanding the differences between var, let, and const, as well as their scoping rules and hoisting behavior, is crucial for writing clean and efficient code. Always use descriptive names for variables, prefer let and const over var, and minimize the use of global variables to avoid unintended side effects. 


 



Practice Excercise Practice now