JavaScript variables and constants in depth with Scope and naming conventions.

JavaScript variables and constants in depth with Scope and naming conventions.

·

4 min read

What is a variable?

A variable is a named storage location that holds a value. It's like a container that can store different types of data, such as numbers, strings, booleans, or even more complex objects, arrays, functions, etc. Variables enable us to refer to these data items using their names instead of repeatedly typing out the actual values.

Declaring and Initializing Variables

To create a variable in JavaScript, we use the var, let, or const keyword. The var keyword was used in all JavaScript code from 1995 to 2015.

The let and const keywords were added to JavaScript in 2015.

        let v; // Declare a variable.
        v = 25; // Assign a value to that variable.
        console.log(v); // Display it in the console.

Let Keyword

The let a keyword is used for variables whose value may change later in the program. e.g

     let a = 10;
        console.log(a); // Its Output is 10.
        // But you can change it later in the program
        a = 20;
        console.log(a); // Now Its Output is 20.

Const Keyword

The const keyword, on the other hand, declares a constant variable whose value cannot be altered once assigned. e.g.

     const a = 10;
        console.log(a); // Its Output is 10.
        // now it is a constant you cannot change it later in the program
        a = 20;
        console.log(a); // Its give an error.

Why do we need to store values in variables?

Suppose we have to print the same value many times in the program. We can print the value like this:

         console.log(20);
         console.log(20);
         console.log(20);
         console.log(20);

In the future, if we need to change this value, we need to update the value wherever we use it. But if we store it in a variable, then we need to change only where the variable is declared. e.g.

     let value = 20;
         console.log(value);
         console.log(value);
         console.log(value);
         console.log(value);

Now, whenever we need to change the value, we just change it in one place, and it will automatically update itself wherever it is used.

Variable Scope

Scope determines the accessibility of a variable within a program. JavaScript has two primary scopes:

Block Scope/Local Scope

Variables declared within functions or blocks are accessible only within that specific scope. For example, I will tell you the easy way to understand the block scope variable. The variable that is declared within {} these brackets has blocked scope.

        {
            let x = 10;
            const y = 20;
        }
        console.log(x);  // It gives an error
        console.log(y);  // It gives an error
        // We cannot access the variable x here because of block scope.
        // It can only be access within the brackets. 

        // We do not use var because it doesn't have any block scope. 
        {
            var a = 30;
        }
        console.log(a); // It will print 30 as an output.
        // It can be accessible here because it doesn't have block scope.

Global scope

Variables declared outside of functions or blocks are accessible throughout the program.

    let x = 30;
        {
            let x = 10;
        }
        console.log(x);  // It Print output 30. not 10.
        // We can access the variable x = 30 anywhere in the program 
        // because of global scope.

Variable Naming Conventions

Variable names should clearly reflect the purpose or value they represent. Avoid vague or generic names like x, y, or temp. Instead, use descriptive names like customerName, productPrice, or temporaryStorage.

JavaScript prefers camelCase for variable names. This means the first word starts with a lowercase letter and subsequent words start with uppercase letters. For example, firstName, lastName, emailAddress.

JavaScript is case-sensitive, so firstName is different from firstName. Be consistent with the case throughout your code.

Don't use JavaScript-reserved keywords for variable names. These keywords are special words with specific meanings in the language and cannot be used as variable names. Examples include if, else, function, var, let, const.

Function names should also follow camelCase and use descriptive prefixes that indicate their purpose. For example, calculateProductTotal, validateUserInput, sendNotification.

Constants, which are variables with unchanging values, should be written in uppercase with underscores between words. For example, MAX_UPLOAD_SIZE, DEFAULT_CURRENCY, API_URL.

Hungarian Notation

While not strictly enforced in JavaScript, some developers use Hungarian notation, where variable names start with a prefix indicating their data type. For example, strName, intAge, dblPrice.

By following these naming conventions, JavaScript developers can improve code readability, maintainability, and collaboration among team members. Consistent and meaningful variable names make code easier to understand, debug, and modify, leading to more efficient development and higher-quality software.

Best Practices for Using Variables

Use meaningful variable names.

Use the let keyword for variables that may change.

Use the const keyword for constant values.

Avoid global variables unless necessary.

Declare variables at the top of their scope.

Initialize variables to avoid undefined values.

Use consistent naming conventions.

Â