How to Store Initial Value in JavaScript

JavaScript offers multiple ways to store initial values, depending on your use case. This tutorial will guide you through different methods, complete with examples.

Hre are different methods with examples:

1. Using Variables

Variables are the most basic way to store values in JavaScript. You can declare variables using let or const.

Using let

let initialValue = 10; // Allows reassignment
console.log(initialValue); // Output: 10

initialValue = 20; // Reassigned
console.log(initialValue); // Output: 20

Using const

const initialValueConstant = 20; // Cannot be reassigned
console.log(initialValueConstant); // Output: 20

// initialValueConstant = 30; // This will cause an error

2. Using Objects

Objects are great for storing multiple related values as key-value pairs.

const initialValues = {
    value1: 10,
    value2: 20,
    value3: 30,
};

console.log(initialValues.value1); // Output: 10

You can easily access and update values within the object.

initialValues.value1 = 15;
console.log(initialValues.value1); // Output: 15

3. Using Arrays

Arrays are suitable for storing ordered lists of values.

const initialValuesArray = [10, 20, 30];

console.log(initialValuesArray[0]); // Output: 10

You can add or remove values from the array.

initialValuesArray.push(40); // Adds 40 to the end
console.log(initialValuesArray); // Output: [10, 20, 30, 40]

4. Storing Values in Function Scope

If you need a value only within a specific function, you can declare it inside that function.

function calculateArea(radius) {
    const pi = 3.14; // Initial value for pi
    return pi * radius * radius;
}

const area = calculateArea(5);
console.log(area); // Outputs the area: 78.5

5. Using Classes

When working with objects that have state, classes are a great way to encapsulate initial values.

class MyClass {
    constructor(initialValue) {
        this.initialValue = initialValue;
    }

    getValue() {
        return this.initialValue;
    }
}

const myInstance = new MyClass(10);
console.log(myInstance.getValue()); // Output: 10

6. Persistent Storage with Local Storage

To store values that persist even after the page is refreshed, use localStorage.

// Storing a value
localStorage.setItem("initialValue", 10);

// Retrieving the value later
const storedValue = localStorage.getItem("initialValue");
console.log(storedValue); // Output: "10"

// Note: Values retrieved from localStorage are always strings
const numericValue = Number(storedValue);
console.log(numericValue); // Output: 10 (as a number)