JavaScript - Variables

-

Declaring Variables

In JavaScript, you can declare variables using three keywords: var, let, and const. Each keyword has its syntax and behavior for variable scope.

Using the var keyword

The var keyword is the oldest way to declare variables in JavaScript.

Example: Declaring a variable with var

var variableName;

Example: Declaring and assigning a variable with var

var variableName = value;

Variables declared with var have function or global scope. If a variable is declared inside a function using var, it is only accessible within that function. If a variable is declared outside any function, it has global scope and can be accessed from anywhere in the code.

Using the let keyword

The let keyword was introduced in ECMAScript 2015 (ES6) and provides block scope for variables.

Example: Declaring a variable with let

let variableName;

Example: Declaring and assigning a variable with let

let variableName = value;

Variables declared with let have block scope, which means they are only accessible within the nearest block (defined by curly braces {}). This includes if statements, for loops, and other block statements.

The main difference between var and let is that variables declared with var can be re-declared in the same scope, while let does not allow redeclaration in the same scope. Also, variables declared with let are not hoisted to the top of their scope, unlike var.

Using the const keyword

The const keyword, also introduced in ES6, is used to declare constants - variables that cannot be reassigned.

Example: Declaring a constant with const

const CONSTANT_NAME = value;

Constants declared with const must be assigned a value during declaration, and that value cannot be changed later in the code.

Like let, constants declared with const have block scope. They are only accessible within the nearest block.

Tip: When to use const

Use const when you have a value that should not be reassigned throughout the lifecycle of your program. For example, you might use const for mathematical constants, configuration values, or references to DOM elements that won't change.

Choose the appropriate keyword (var, let, or const) based on your needs for variable scope and reassignment.

Assigning Values to Variables

In JavaScript, you can assign values to variables during declaration or after declaration. You can also reassign values to variables throughout your program.

Assigning a value to a variable during declaration

You can assign a value to a variable when you declare it using the = operator. This initializes the variable with the value.

Example

let message = "Hello, world!";

Assigning a value to a variable after declaration

You can also declare a variable first and then assign a value to it later in your code.

Example

let count;
count = 5;

Reassigning values to variables

Variables declared with var and let can be reassigned with new values throughout your program.

Example

let score = 0;
score = score + 10;

Tip

Remember that variables declared with const cannot be reassigned after their initial assignment during declaration.

const PI = 3.14159;
PI = 3.14; // Error: Assignment to constant variable

Assigning values to variables allows you to store and update data throughout your JavaScript program. Choose the way to assign values based on your needs and the use of the variable.

Variable Naming Conventions

When declaring variables in JavaScript, follow naming conventions to keep your code readable, maintainable, and consistent. Here are the rules and best practices for naming variables in JavaScript:

  1. Variable names should indicate the purpose or content of the variable. Avoid single-letter names or abbreviations unless commonly understood.

Example: Good variable names

let firstName = "John";
let age = 25;
let isStudent = true;

Example: Bad variable names

let a = "John";
let b = 25;
let c = true;
  1. Variable names should start with a letter, underscore (_), or dollar sign ($). They cannot start with a number.

Example: Valid variable names

let _privateVar = "private";
let $price = 9.99;
let name1 = "John";

Example: Invalid variable names

let 1name = "John"; // Cannot start with a number
let @email = "john@example.com"; // Cannot start with @
  1. Variable names are case-sensitive. For example, myVariable and myvariable are different variables.

  2. Use camelCase for variable names with multiple words. Start with a lowercase letter and capitalize the first letter of each subsequent word.

Example: Variable names in camelCase

let firstName = "John";
let lastLoginDate = "2023-05-15";
let isLoggedIn = true;
  1. For constants declared with const and have a fixed value, use uppercase with underscores (_) to separate words.

Example: Constant names in uppercase

const PI = 3.14159;
const MAX_USERS = 100;
const API_URL = "https://api.example.com";
  1. Avoid using JavaScript reserved keywords as variable names, such as var, let, const, if, for, function, etc.

Example: Invalid variable names using reserved keywords

let let = "value"; // Cannot use "let" as a variable name
let for = 10; // Cannot use "for" as a variable name

By following these naming conventions, your JavaScript code will be more readable, understandable, and aligned with common practices. It helps prevent naming conflicts and makes it easier for other developers to work with your code.

Variable Scope

Variable scope refers to the visibility and accessibility of variables in different parts of your JavaScript code. Understanding variable scope is important for writing clean, maintainable, and bug-free code. In JavaScript, there are three types of variable scope: function scope, block scope, and global scope.

Function Scope

Variables declared with the var keyword inside a function have function scope. They are accessible only within the function where they are declared. Function-scoped variables are not accessible outside the function.

Example: Function Scope

function sayHello() {
  var message = "Hello, world!";
  console.log(message); // Output: Hello, world!
}

sayHello();
console.log(message); // Error: message is not defined

Block Scope (introduced in ES6)

With the introduction of let and const in ECMAScript 2015 (ES6), JavaScript gained block scope. Block scope means that variables declared inside a block (defined by curly braces {}) are only accessible within that block.

Example: Block Scope

if (true) {
  let score = 100;
  const PI = 3.14159;
  console.log(score); // Output: 100
  console.log(PI); // Output: 3.14159
}
console.log(score); // Error: score is not defined
console.log(PI); // Error: PI is not defined

Global Scope

Variables declared outside any function or block have global scope. They are accessible from anywhere in your JavaScript code, including inside functions and blocks.

Example: Global Scope

var globalVar = "I am global";

function accessGlobal() {
  console.log(globalVar); // Output: I am global
}

if (true) {
  console.log(globalVar); // Output: I am global
}

Hoisting and its effects on variable scope

Hoisting is a behavior in JavaScript where variable and function declarations are moved to the top of their respective scopes during the compilation phase, before the code is executed.

Variables declared with var are hoisted to the top of their scope, but only their declaration is hoisted, not their assignment. This means you can reference a variable before it is declared, but its value will be undefined until it is assigned.

Example: Hoisting with var

console.log(hoistedVar); // Output: undefined
var hoistedVar = 10;

Variables declared with let and const are also hoisted, but unlike var, they are not initialized with undefined. Accessing a block-scoped variable before its declaration results in a ReferenceError.

Example: Hoisting with let

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

Tip: Avoiding confusion and unexpected behavior

To avoid confusion and unexpected behavior, it's best to declare variables before using them and to understand the scoping rules for var, let, and const.