DEV Community

AKIRI FEJIRO
AKIRI FEJIRO

Posted on

The Complete Guide to JavaScript Variables for Beginners

Image descriptionImagine you’re a chef, and you’re preparing a dish that requires many ingredients. You carefully measure and combine each ingredient to create a delicious and balanced flavor. Without the right ingredients, your dish wouldn’t taste the way you wanted it to.

In the same way, when it comes to building a website or application, it’s important to have the right tools and programming language to create a user experience that stands out. Just like a recipe, each line of code serves a specific purpose in creating the result.

JavaScript is one of the most crucial ingredients in modern web development, allowing developers to create dynamic and interactive user experiences. And at the core of JavaScript programming are variables—the containers that hold and manipulate data.

In this guide, we’ll dive into everything you need to know about JavaScript variables and how to use them to create powerful and dynamic user experiences. Whether you’re a seasoned developer or just starting, this guide will provide a complete introduction to JavaScript variables and give you the foundational knowledge you need to use them effectively in your code.
So, let’s start cooking up some amazing web applications with JavaScript!

Declaring and Initializing Variables

Just as a chef carefully measures and combines different ingredients to create a delicious dish, a developer uses variables to store and manipulate different types of data in their code.

In JavaScript, variables are containers that hold values, such as strings, numbers, or booleans, and can be used to store data or perform calculations. Before you can use a variable, you need to declare it, which involves creating a name for the variable and specifying its data type.

To declare a variable in JavaScript, you use one of three keywords: var, let, or const. The var keyword was used in older versions of JavaScript, but now it's recommended to use either let or const, which provides more predictable behavior and better scope control.

Once you’ve declared a variable, you can then assign a value to it using the assignment operator (=). For example, you could declare and initialize a variable called myName with the value "Alice" like this:

let myName = "Alice";
Enter fullscreen mode Exit fullscreen mode

In this example, the variable myName is declared using the let keyword, and its value is initialized to the string “Alice.”
In addition to strings, variables can also hold other types of data, such as numbers or booleans. For example, you could declare and initialize a variable called myAge with the value 25 like this:


let myAge = 25;
Enter fullscreen mode Exit fullscreen mode

Or you could declare and initialize a boolean variable called isStudent with the value true like this:

const isStudent = true;
Enter fullscreen mode Exit fullscreen mode

In each of these examples, the variable is declared using a different keyword (let or const) and is assigned a different data type (string, number, or boolean).

Understanding how to declare and initialize variables is a critical skill in JavaScript programming, and it provides the foundation for working with more complex data structures and functions.

In the next section, we’ll explore how to use variables in more advanced ways to create dynamic and interactive web applications.

Variable scopes and Hoisting

As we’ve seen, variables are like ingredients in a recipe—they allow you to store and manipulate data to create amazing web applications. But there’s more to variables than just declaring and initializing them. In JavaScript, variables have different scopes, which determine where and how they can be accessed.
Let’s take a closer look at variable scopes and hoisting in JavaScript.

Variable Scopes

In JavaScript, variables can be either global or local. A global variable is declared outside of any function and can be accessed from anywhere in your code. A local variable, on the other hand, is declared inside a function and can only be accessed within that function.

Here’s an example of declaring a global variable:


let globalVar = 'I am a global variable';

function logGlobal() {
  console.log(globalVar);
}

logGlobal(); // output: "I am a global variable"
Enter fullscreen mode Exit fullscreen mode

And here’s an example of declaring a local variable:


function logLocal() {
  let localVar = 'I am a local variable';
  console.log(localVar);
}

logLocal(); // output: "I am a local variable"
console.log(localVar); // ReferenceError: localVar is not defined
Enter fullscreen mode Exit fullscreen mode

As you can see, the global variable globalVar can be accessed from both the logGlobal() function and outside of it, while the local variable localVar can only be accessed within the **logLocal() **function.

For example:


console.log(myVar); // output: undefined
var myVar = 'I am hoisted';

console.log(myVar2); // ReferenceError: myVar2 is not defined
let myVar2 = 'I am not hoisted';
Enter fullscreen mode Exit fullscreen mode

In the first example, the variable myVar is declared and assigned a value after it’s called in the console.log() statement. However, because of hoisting, the variable declaration is moved to the top of its scope, so the variable is defined but has a value of undefined

In the second example, we’re trying to use the variable myVar2 before it’s declared. However, because** let** declarations are not hoisted, we get a ReferenceError

Understanding variable scopes and hoisting is critical for writing efficient and bug-free JavaScript code. With this knowledge in hand, you’ll be well on your way to becoming a master chef of web development!

Types of Variables in JavaScript

Just as a chef has different types of ingredients to choose from, JavaScript developers have different types of variables to use in their code. In JavaScript, there are three main types of variables: let, var, and const. Each type of variable has its unique characteristics and use cases.

let Variables

The let keyword is used to declare a variable that can be reassigned to a new value. This type of variable is block-scoped, meaning it is only accessible within the block of code where it is defined.

Here’s an example:


let ingredient = "flour";
console.log(ingredient); // output: flour

ingredient = "sugar";
console.log(ingredient); // output: sugar
Enter fullscreen mode Exit fullscreen mode

In this example, we declare a variable called ingredient using the let keyword and assign it the value "flour." We then log the value of the variable to the console, which outputs "flour." We then reassign the variable to the value "sugar" and log it to the console again, which outputs "sugar."

var Variables

The var keyword is similar to let in that, it is used to declare a variable, but it has some important differences. var Variables are function-scoped, meaning they are accessible throughout the entire function where they are defined.

Here’s an example:


function cookDish() {
  var ingredient = "olive oil";
  console.log(ingredient); // output: olive oil
}

cookDish();
console.log(ingredient); // output: ReferenceError: ingredient is not defined
Enter fullscreen mode Exit fullscreen mode

In this example, we declare a variable called ingredient using the var keyword inside a function called cookDish(). We then log the value of the variable to the console, which outputs "olive oil." Since var variables are function-scoped, the variable is only accessible within the function where it is defined. When we try to log the variable outside of the function, we get a ReferenceError because the variable is not defined in that scope.

const Variables

The const keyword is used to declare a variable that cannot be reassigned to a new value. This type of variable is also block-scoped, like let.

Here’s an example:


const ingredient = "butter";
console.log(ingredient); // output: butter

ingredient = "oil"; // TypeError: Assignment to constant variable.
Enter fullscreen mode Exit fullscreen mode

In this example, we declare a variable called ingredient using the const keyword and assign it the value "butter". We then log the value of the variable to the console, which outputs "butter". When we try to reassign the value of the variable to "oil", we get a TypeError because** const** variables cannot be reassigned.

Differences between the Types of Variables

Now that we’ve explored the different types of variables in JavaScript, let’s discuss their differences.

The main differences between let, var, and const variables are their scope and mutability. let and const variables are block-scoped, meaning they are only accessible within the block of code where they are defined. var Variables are function-scoped, meaning they are accessible throughout the entire function where they are defined.

let and var variables can be reassigned to new values, while const variables cannot. This makes const variables useful for defining constants in your code that you do not want to be changed.

In summary, let, var, and const, variables all have their unique characteristics and use cases. As a JavaScript developer, it’s important to understand the differences between these various types of variables so you can use them effectively in your code. By understanding the different types of variables and their characteristics, you can write cleaner, more efficient, and more maintainable code in your JavaScript applications.

Best Practices for Using Variables in JavaScript

When working with variables in JavaScript, following best practices can make your code cleaner, more efficient, and easier to understand. Here are a few key best practices to keep in mind:

  1. Use Descriptive Variable Names Choosing clear and descriptive variable names is essential for writing readable and maintainable code. Good naming conventions include using descriptive names that reflect the purpose of the variable, avoiding abbreviations and acronyms, and using camel cases to make names easier to read.

// Example of good variable naming conventions
let userName = "John Smith";
let numberOfUsers = 10;
let isLoggedIn = true;
Enter fullscreen mode Exit fullscreen mode

2.Initialize Variables When Declared

Initializing variables when they are declared can help you avoid unexpected errors and make it easier to keep track of the data being stored in the variable.


// Example of initializing a variable when it's declared
let message = "Hello World!";
Enter fullscreen mode Exit fullscreen mode

3.Avoid Common Mistakes

When working with variables, it’s important to avoid common mistakes. Two common mistakes are declaring a variable with the wrong data type and using global variables unnecessarily.


// Example of declaring a variable with the wrong data type
let price = "10.99"; // should be a number

// Example of using global variables unnecessarily
let counter = 0; // should be a local variable within a function
Enter fullscreen mode Exit fullscreen mode

By following these best practices and avoiding common mistakes, you can create cleaner, more efficient code and become a better JavaScript developer. Just like a chef who follows best practices in the kitchen, a JavaScript developer who follows best practices for using variables can create more reliable, functional, and visually appealing web applications.

Case study

Now we will move on to a case study on using variables in a shopping cart application. In this example, we’ll explore how variables are used to store product information and calculate order totals, and how they can be used to enhance the functionality and user experience of the application.

Imagine you’re building an e-commerce website that allows customers to add items to their shopping cart and place orders. To create a shopping cart, you’ll need to use variables to store information about each product, such as its name, price, and quantity.

Here’s an example of how you might use variables to store product information:


const product1 = {
  name: "T-shirt",
  price: 20,
  quantity: 2
};

const product2 = {
  name: "Jeans",
  price: 50,
  quantity: 1
};
Enter fullscreen mode Exit fullscreen mode

In this example, we’re using objects to store information about each product. The name, price, and quantity properties are all variables that store specific information about each product.

To calculate the order total, we can use variables to keep track of the total price of each product, and then add them together to get the final total. Here’s an example of how you might do that:


const total1 = product1.price * product1.quantity;
const total2 = product2.price * product2.quantity;
const orderTotal = total1 + total2;
Enter fullscreen mode Exit fullscreen mode

In this example, we’re using variables to calculate the total price of each product and then add them together to get the order total.

Using variables in this way can help to make your shopping cart application more dynamic and interactive. For example, you could use variables to update the order total in real-time as the customer adds or removes items from their cart.

Conclusion

Just like a chef needs to understand the ingredients and techniques to create a delicious dish, a JavaScript developer needs to understand variables to write clean and efficient code. I covered the different types of variables, scopes, and best practices for using them.

I applied this knowledge to a shopping cart application, demonstrating how variables can enhance functionality and user experience. I encourage readers to practice using variables in their code and explore additional resources to improve their craft. Understanding variables are fundamental to programming in JavaScript, and I hope this guide has helped demystify them. Happy coding!

Top comments (0)