2.4 Variable Declarations: let, const, and var

14 min read
67

In this section, we’ll dive into the world of variable declarations in JavaScript. You’ve already learned about JavaScript data types in the previous lesson, and now it’s time to understand how to declare and manage variables.

Variable Declarations

In JavaScript, variables are used to store and manage data. The choice of which keyword to use when declaring variables—let, const, or var—depends on the intended use and behavior of the variable within your program.

Up until now, we’ve primarily used the let keyword to declare variables, but JavaScript offers two more options: const and var.

let and const are modern additions introduced in ES6, while var is an older way to declare variables. Now, let’s explore the differences between them and when to use each.

1. let

The let keyword is used to declare variables that can be reassigned later in the program’s execution. It is block-scoped, which means it’s only accessible within the block (a set of code enclosed in curly braces) where it’s defined.

Here are some key points about let:

  • Use let when you need a variable that can change its value during program execution.
  • You can declare a variable with let without immediately assigning a value to it, making it suitable for cases where the initial value is unknown but will be assigned later.
  • It allows for reassignment, which means you can change the value of a let variable at any point in your code.
  • For example, you can use let to declare a variable like myAge and update it as needed:
let myAge = 34; // Declare and assign a value
myAge = "twenty-four"; // Reassign the variable

Consider this scenario: when a person reaches the age of 35, we update the person’s age from 34 to 35, like this:

myAge = 35;

It is entirely acceptable in programming to declare a variable using let at one point in the program and then later assign a new value to it. In technical terminology, this is referred to as reassigning a value to a variable or mutating the variable. In this case, the age was initially 34, but now it’s 35, so we’ve effectively mutated the myAge variable. This concept is commonly used in the JavaScript programming world.

ALSO READ:  1.1 The Hello World Program: Launching Your Journey

Whenever we need to change the value of a variable, using let is the appropriate choice. This also applies when we want to declare an initially empty variable, like so:

let year;

In this example, we’ve declared an empty year variable, which we can later assign the value 1989 to. This practice is often employed when we wish to define all the variables at the beginning of a file and only assign actual values to them later in the program, based on specific conditions.

year = 1989;

2. const

The const keyword is used to declare variables that should never change their value after being assigned. It is also block-scoped.

Here’s what you need to know about const:

  • Use const for variables whose values should remain constant throughout your program.
  • You must assign a value to a const variable when declaring it, and you cannot change that value later in the code.
  • Attempting to reassign a const variable will result in an error.
  • Example:
const birthYear = 1989; // Declare and assign a constant value

Let’s explore the scenario where you attempt to declare a variable with the same name as one that’s already been declared:

birthYear = 2017; // This line will result in an 'Uncaught TypeError: Assignment to constant variable.'

Indeed, this code snippet triggers a type error. This behavior aligns with the purpose of the const keyword, which is to create an immutable variable. In other words, a variable that cannot be reassigned or, in technical terms, a variable that remains unaltered. The concept becomes clear when we consider the example of “birthYear.” The birth year of an individual, in reality, never changes, whereas their age can certainly vary over time. This is why we employ let for the age variable and const for the birthYear variable. Does this explanation make sense?

Furthermore, it’s essential to note that variables created with the “const” keyword must have an initial value; otherwise, it’s not a valid declaration. For instance, the following code is not permissible:

const myFirstJob; // This line results in an 'Uncaught SyntaxError: Missing initializer in const declaration.'

The error message indicates that when using const, you must provide an initial value, just as demonstrated in the example.

ALSO READ:  2.10 Coding Challenge-2: Calculate Grade Average

Advise

Now, when it comes to declaring variables using these two different methods, you might be wondering whether to opt for let or const when creating a new variable.

As a best practice for maintaining clean and reliable code, I consistently advise using const as the default choice. Reserve let for situations where you are absolutely certain that the variable will need to change at some point in the future. For instance, if you have a variable like “birthYear” that is intended to remain constant throughout your program, it should always be declared using const. Similarly, if you are confident that the “myAge” variable will never undergo changes within your program, it’s a good practice to declare it using const as well.

The rationale behind this recommendation is that it’s generally wise to minimize variable mutations or alterations, as modifying variables can introduce the potential for bugs or errors in your code. In summary, default to const and only opt for let when you are certain that the variable will require modification at some point in your code.

3. var (for legacy purposes)

The var keyword is an older way of declaring variables in JavaScript. It is function-scoped, which means its accessibility is limited to the function it’s declared in or, if declared outside of any function, it becomes globally scoped.

Here’s what to keep in mind about var:

  • While var behaves similarly to let regarding reassignment (at first glance, it behaves quite similarly to let), particularly in how it’s scoped. Understanding these differences is important, but for modern development, it’s generally recommended to use let and const instead of var.
  • Let’s delve into its functionality. For instance:
var job = "Programmer"; // Declare and assign a value

You can also change the variable’s value later, just like with let:

job = "Teacher"; // Reassign the variable

Surprisingly, no errors occur when mutating the “job” variable with var. This means that var allows variable mutation.

However, despite their superficial similarities, var and let have significant differences beneath the surface. In fact, there are numerous distinctions between let, const, and var. You will explore these differences in detail later in the tutorial, as they are crucial concepts.

ALSO READ:  1.2 Introduction to JavaScript

I understand that I’ve mentioned deferring the explanation of certain topics to later tutorials, but it’s essential to recognize that the learning process isn’t always linear. It doesn’t unfold step by step. Sometimes, you might encounter more advanced concepts even before fully grasping the fundamentals. This is because understanding often evolves over time.

So, at this moment, delving into the distinctions between “let” being block-scoped and “var” being function-scoped may not be particularly beneficial. After all, you might not yet comprehend what blocks and functions truly entail. We’ll explore these distinctions in later tutorials. What’s crucial for now is to avoid using var. Alright?

Some might argue

Before wrapping up, some might argue that declaring variables is unnecessary because it’s not mandatory. You can simply do this:

lastName = "Kumar";

Then, you can use the variable without declaring it:

console.log(lastName); // Kumar

JavaScript will execute this script without error, even without let, const, or var. However, this practice is discouraged because it doesn’t create a variable within the current scope. Instead, JavaScript creates a property on the global object. You’ll learn more about this concept later, but the essential point is always to declare variables properly.

You’re making excellent progress, even though our code isn’t performing any substantial tasks yet, and we haven’t started building real applications. However, it’s crucial to establish a solid foundation before diving into those more complex topics. That’s why I’m emphasizing the finer details here. I hope you recognize the significance of this for your overall progress, okay? Please rest assured that we will continue to explore this topic and its broader implications throughout the course of the tutorial.

Discussion of JavaScript variables FAQs

Please keep in mind that the learning process is fluid, and it’s entirely natural to have questions. As you embark on your educational journey, you may encounter queries or uncertainties. To assist you in navigating this learning path, we’ve assembled a collection of Frequently Asked Questions (FAQs) concerning any scenarios related to JavaScript variables. If you have any doubts or need clarification on variable usage, you’ll likely find the answers in the following FAQs. Feel free to explore and expand your understanding of JavaScript variables.

Avatar for Amit

Amit (16)

Hello! I'm Amit Kumar, a passionate teacher specializing in web development and digital marketing. With several years of experience in the industry, I am dedicated to sharing my knowledge and expertise to empower aspiring learners like you.

Teaching Philosophy:

I believe in creating a dynamic and engaging learning environment where students can thrive. My teaching approach focuses on hands-on experience, practical applications, and real-world examples. I strive to make complex concepts understandable and enjoyable, ensuring that you not only grasp the fundamentals but also develop the skills necessary to excel in web development and digital marketing.

Web Development Expertise:

As a web development instructor, I am well-versed in HTML, CSS, JavaScript, and various frameworks such as React and Angular. I will guide you through the process of building responsive and user-friendly websites, exploring topics like front-end development, back-end integration, database management, and more. Together, we will delve into the latest trends and best practices in web development, equipping you with the tools to create stunning online experiences.

Digital Marketing Mastery:

In the rapidly evolving digital landscape, digital marketing is crucial for businesses to thrive. Through my digital marketing courses, I will help you navigate the intricacies of search engine optimization (SEO), social media marketing, content strategy, email marketing, and analytics. Gain insights into effective marketing techniques, harness the power of data-driven decision-making, and learn how to craft compelling campaigns that drive results.

Passion for Teaching:

Teaching is not just a profession for me; it's my passion. I find great joy in witnessing my students grow and succeed. I am committed to fostering a supportive learning community where questions are encouraged, ideas are shared, and challenges are overcome together. I am here to guide you every step of the way and provide the necessary resources for your personal and professional development.

Join me on this exciting journey of learning and discovery. Let's unlock your potential in web development and digital marketing together. Enroll in my courses today and embark on a transformative educational experience that will propel your career forward.
Start Learning Today!

5 1 vote
Article Rating
Subscribe
Notify of

guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
Scroll to Top