Skip to main content

JavaScript Variables

Summary

Introdution to variables in JavaScript using let and const. Differences between let, const, and var. Variable naming conventions and best practices. Introduction to data types.

Introduction to Variables in JavaScript #

In modern JavaScript (ES6 or higher), variables (identifiers) are declared using the let and const keywords, providing block-level scoping and immutable binding respectively.

Examples #

// Using let
let x = 10;
x = 20; // Valid

// Using const
const y = 5;
y = 8; // Invalid, attempting to reassign a constant variable

// With both let and const, block scoping applies
{
    let z = 15;
    console.log(z); // Output: 15
}
console.log(z); // Error: z is not defined

// const for objects and arrays doesn't prevent mutation of their properties or elements
const person = { name: 'Alice' };
person.name = 'Bob'; // Valid, mutating a property of the object

Differences between let, const, and var #

The main differences between let, const, and var in JavaScript are related to scoping, re-assignment, and immutability:

  1. Scoping
    • var has function-level scope. Variables declared with var are function-scoped, meaning they are visible throughout the entire function in which they are declared.
    • let and const have block-level scope. They are limited to the block (enclosed within curly braces {}) in which they are defined, such as loops or conditionals.
  2. Re-assignment
    • Variables declared with var and let can be reassigned.
    • Variables declared with const cannot be reassigned. For objects and arrays, while you cannot reassign the variable itself, you can still modify the properties or elements of the object or array.
  3. Hoisting
    • Variables declared with var are hoisted to the top of their scope. This means that you can access them before they are declared, but they will have an initial value of undefined.
    • let and const are also hoisted, but they are not initialized until the actual declaration statement is evaluated during runtime. Accessing them before their declaration results in a ReferenceError.
  4. Global Object Property
    • Variables declared with var become properties of the global object (window in browsers). This can lead to unintended consequences and conflicts.
    • Variables declared with let and const do not become properties of the global object.

let and const provide more predictable behavior and better support for writing modular and maintainable code compared to var. It is generally recommended to use let for variables that may be reassigned, and const for variables that will not be reassigned after initialization.

With the introduction of let and const in ECMAScript 6 (ES6), it is generally recommended to avoid using var in modern JavaScript codebases in favor of let and const.

Naming variables in JavaScript #

Reserved names #

Modern JavaScript has a list of reserved words that cannot be used as variable names, as they have special meanings within the language:

Using any of these words as variable names would result in a syntax error. It is a good practice to choose descriptive variable names that clearly convey the purpose of the variable in your code.

Variable nameing best practices #

Variable names that should be avoided or will cause issues due to their special meanings or conventions within the language:

Following these guidelines will help ensure that your variable names are clear, meaningful, and free from potential conflicts or issues.

Loosly typed #

In loosely typed languages like JavaScript, variables are not bound to a specific data type. This means that a variable can hold different types of values over its lifetime.

Type coercion is common in loosely typed languages, where the interpreter automatically converts data from one type to another when needed. For example, “5” + 3 would result in the string “53” because the number 3 is coerced into a string and concatenated with “5”.

JavaScript’s loosely typed nature can lead to unexpected behaviors if not used carefully, as types can be coerced implicitly during operations.

Data types #

In JavaScript, the typeof operator is used to determine the type of a given value or expression. It returns a string indicating the data type of the operand.

typeof 42;  // "number"
typeof "Hello";  // "string"
typeof true;  // "boolean"
typeof {};  // "object"
typeof [];  // "object"
typeof function(){};  // "function"
typeof undefined;  // "undefined"
typeof null;  // "object" (historical quirk)

typeof null returns "object", which is often considered a historical mistake in JavaScript, but it is maintained for backward compatibility.

Primitive data types #

For primitive types, typeof returns the actual type as a string:

Objects #

For objects, typeof returns “object”, though you can use other methods (like Array.isArray()) to differentiate between array and non-array objects.

Type Detection #

typeof is particularly useful when you need to perform different actions based on the type of a variable or value:

function displayType(value) {
    console.log(typeof value);
}

displayType(42);  // "number"
displayType("Hello");  // "string"

typeof is not always foolproof, especially for complex objects and arrays. For example, it can not differentiate between different kinds of objects (like a regular object and an instance of a class), nor can it distinguish between different types of objects (like a function and a plain object).

It may not always provide the granularity needed for type checking. For more complex type checking scenarios other methods and libraries may be more appropriate.


Further readings #

Sources and recommended, further resources on the topic:

Author

Jonas Jared Jacek • J15k

Jonas Jared Jacek (J15k)

Jonas works as project manager, web designer, and web developer since 2001. On top of that, he is a Linux system administrator with a broad interest in things related to programming, architecture, and design. See: https://www.j15k.com/

License

License: JavaScript Variables by Jonas Jared Jacek is licensed under CC BY-NC-SA 4.0.

This license requires that reusers give credit to the creator. It allows reusers to distribute, remix, adapt, and build upon the material in any medium or format, for noncommercial purposes only. If others modify or adapt the material, they must license the modified material under identical terms. To give credit, provide a link back to the original source, the author, and the license e.g. like this:

<p xmlns:cc="http://creativecommons.org/ns#" xmlns:dct="http://purl.org/dc/terms/"><a property="dct:title" rel="cc:attributionURL" href="https://www.ditig.com/publications/javascript-variables">JavaScript Variables</a> by <a rel="cc:attributionURL dct:creator" property="cc:attributionName" href="https://www.j15k.com/">Jonas Jared Jacek</a> is licensed under <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank" rel="license noopener noreferrer">CC BY-NC-SA 4.0</a>.</p>

For more information see the DITig legal page.


“Learning from conventions will make your site better.”

Jeffrey Veen, American designer and design strategistThe Art & Science of Web Design, - IT quotes