How to Use JavaScript Variables Effectively in Your Projects

As a beginner in web development, you may have heard of the term JavaScript variables. But what exactly are  JavaScript variables, and why are they important? A JavaScript variable is a container that holds a value. You can use variables to store data and manipulate it in your code. Variables are easy to create and use in JavaScript.

In this blog post, we’ll look into:

  • What are JavaScript variables?
  • Different types of variable declaration
  • Allowed characters in variable names
  • Default values for primitive data types
  • Primitive data type’s size limit
  • How do you pass variables to HTML?
  • Return two or more variables from functions
  • How to modify them in real time using the browser DevTools.

Let’s get started!

What is variables in JavaScript?

Variables are containers for storing data values in JavaScript. They are an essential part of any programming language and are used to store information that can be manipulated and reused throughout your code.

In JavaScript, you can declare variables using three different keywords var, let, and const.

JavaScript Variables var vs let vs const
Types of variables in JavaScript (var, let and const)

In this example, we declared a variable named "name" and assigned it the value "John Doe" using three different JavaScript variable types.

Do JavaScript variables have to be declared?

In JavaScript, you don’t always have to declare a variable before using it. If you assign a value to a variable without declaring it first, JavaScript will automatically consider it a global variable.

number = 10
console.log(number)
// Output: 10

However, this is not a best practice and can lead to issues like naming conflicts and bugs in your code. Here’s an example of how to declare a variable in JavaScript:

let number;
number = 10
console.log(number)
// Output: 10

In this example, we declared a variable named number without assigning it a value. We then assigned it the value 10 later in our code.

JavaScript variables allowed characters

In JavaScript, variables can contain:

  • Letters
  • Digits (However, it should not be the first character in the variable name)
  • Underscores
  • Dollar signs

JavaScript keywords are also not allowed as variable names, such as const, class, and array. Here are some examples of valid and invalid JavaScript variable names:

Valid variable names ✅:

let age;
let _privateVariable;
let $currencyAmount;
let phone1;

Invalid variable names ❌:

let 1phone; // starts with a digit
let home-address; // contains a hyphen
let var#1; // contains a special character other than underscore or dollar sign
let const; // JavaScript keyword

JavaScript variable default value

In JavaScript, variables are automatically assigned a default value of undefined when they are declared but not initialized with a value.

However, the default values for each primitive data type are as follows:

TypeDefault Value
nullThe value is null, which represents a deliberate non-value or empty value.
undefinedThe value is undefined, which represents an uninitialized value or an absence of a value.
booleanThe value is false.
numberThe value is 0
stringThe value is an empty string (“”).

JavaScript variables are case sensitive

JavaScript variables names are case-sensitive, which means that variables with different capitalizations are considered distinct. Here’s an example to illustrate this:

let greet = "hello, JavaScript!";
console.log(greet); 
// Outut: "hello, JavaScript!"

let Greet = "JavaScript is awesome!";
console.log(Greet); 
// Output: "JavaScript is awesome!"
JavaScript toUpperCase() method

Variables in JavaScript are case-sensitive, meaning that greet and Greet are not the same. They have different values and can cause errors if used incorrectly.

Variable size limit

In JavaScript, the size limit for primitive data types depends on the data type itself. Here are the size limits for each primitive data type:

Data TypeSize
nullThere is no size limit for null. It represents a deliberate non-value or empty value.
undefinedThere is no size limit for undefined. It represents an uninitialized value or an absence of a value.
booleanA boolean value takes up 1 byte of memory, which can only store a value of true or false.
numberA number value takes up 8 bytes of memory, which can store a range of values from -9007199254740991 to 9007199254740991.
stringThe size limit for a JavaScript string variable depends on the amount of available memory in the system.
Non-primitive data typesThe size limit for non-primitive data types like arrays and objects can vary depending on their contents and structure.

It’s important to note that the actual size of a variable in memory may vary depending on the implementation of JavaScript and the system it is running on. 

JavaScript variables in HTML Code

We can also declare variables directly in HTML code by using the script tag. This is useful when we want to write small scripts that are specific to a single HTML page.

Here’s an example of how to declare a JavaScript variable in HTML code:

<!DOCTYPE html>
<html>
  <head>
    <title>JS Variables in HTML Code</title>
  </head>
  <body>
    <p id="username"></p>
    <script>
      let userName = "John";
      document.getElementById("username").innerHTML = `Hello ${userName}`;
    </script>
  </body>
</html>

In this example, we declared a JavaScript variable named userName inside a script tag in our HTML code. We then used JavaScript to modify an HTML element with the id "username" to display the value of our variable.

How to declare multiple variables in JavaScript

In JavaScript, we can declare multiple variables at once by separating them with a comma. Here’s an example of how to declare multiple variables in JavaScript:

JavaScript Multiple Variable Declarations
JavaScript Multiple Variable Declarations
let firstName = "John", lastName = "Doe", age = 30;

In this example, we declared three variables (firstName, lastName, and age) and assigned them values in a single line of code using commas.

How to return multiple variables in JavaScript?

JavaScript functions can only return a single value by default. However, you can use an array, an object, or destructuring to return multiple values from a function.Here’s how to return two variables in JavaScript using an array:
function getFullName() {
  let firstName = 'John', lastName = 'Doe';
  return [firstName, lastName];
}

let [firstName, lastName] = getFullName();

console.log(`Full name: ${firstName} ${lastName}`)
// Output: Full name: John Doe

In this example, the getFullName() function returns an array containing the firstName and lastName parameters. We then use JavaScript destructuring to assign the values of the array to two separate variables, firstName, and lastName.

Alternatively, we could use an object to return multiple values from our function:

function getValues(value1, value2) {
  let sum = value1 + value2;
  let multiply = value1 * value2;

  return {
    sum, multiply
  }
}

let { sum, multiply } = getValues(10, 20);

console.log(`Sum: ${sum}, Multiply: ${multiply}`)
// Output: Sum: 30, Multiply: 200

In this example, the getValues() function returns an object containing the sum, and multiply parameters. We use destructuring to assign the values of the object to two separate variables: sum, and multiply.

With this approach, you can return two or multiple values from a function.

Modify JavaScript variables value in real time in browser

In addition to viewing the values of JavaScript variables in the Chrome DevTools, you can also modify the values of your variables in real time while your code is running. This is useful for debugging and testing your code since you can quickly try out different values and see how they affect your code.

Here’s how to modify JavaScript variables in real time in the browser:

  • Set a breakpoint in your code at the point where you want to modify your variable.
  • Refresh the page to trigger the breakpoint.
  • In the menu DevTools, select the "Console" tab.
  • Type the name of your variable and press Enter to view its current value.
  • Type the name of your variable followed by an equal sign and the new value you want to assign to it, and press Enter to update its value.

Continue running your code to see how the new value affects your program.

Modify JavaScript variables in real time in browser
Modify JavaScript variables in real time in browser

In this approach, you can view and change variables in the Chrome browser.

Conclusion

In conclusion, JavaScript variables are essential for creating dynamic and interactive web pages. They allow you to store and manipulate data, perform calculations, and control the flow of your code.

By understanding the different types of variables, their scope, and their behavior, you can write more efficient and error-free JavaScript code.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Scroll to Top