2.1 Introduction to JavaScript Values and Variables

21 min read
87

Welcome back to our journey into the “JavaScript Values and Variables”!

In this lesson, we’re diving headfirst into the foundational concepts of “JavaScript: values and variables”.

JavaScript Values and Variables

Imagine values as pieces of information, and variables as containers that hold these valuable pieces. Throughout this lesson, we’ll use real-world examples involving people, such as names, ages, and occupations, to make these concepts tangible.

Understanding Values

At its core, a value in JavaScript is like a data nugget. It’s the smallest unit of information in programming. For instance, when we see the word “Amit,” we’re looking at a value:

"Amit";

To visualize this value, we can use console.log(), a tool that helps us to see this actually in the console. Let’s say:

console.log("Amit"); // Amit

So here, “Amit” is a value, and values can come in various forms, from simple numbers to complex calculations. Here are a few more examples:

console.log(34); // 34

And same is here:

console.log(45 + 9 + 27 - 18); // 63

These four are different values. And then this mathematical operators, here, joined them together to form just one value and that value is then 63.

Each of these is a unique value in JavaScript, and we can manipulate and use them in our code as needed.

Introducing Variables

Now, one extremely useful things that we can do with values is to store them into variables. And this way we can reuse them over and over again.

Values are valuable on their own, but they become truly powerful when we can store and reuse them. This is where variables come into play. In JavaScript, a variable is like a labeled box where we can stash a value for safekeeping. We give this box a name, and it helps us remember what’s inside. Let’s observe how this works:

let firstName = "Amit";

In this context, we’ve created a variable named firstName and placed the value “Amit” inside it. This action is commonly referred to as “declaring a variable.” When we declare a variable, it creates a real variable in your computer’s memory, and it’ll store the value inside of that variable.

Think of firstName as the label on a box that contains the name “Amit.” I like to visualize a variable as if it were a box. In the real world, a box has the capacity to hold an object, such as a book, and we can affix a label to the box to describe its contents. Later, we can easily locate the object within the box by referring to that label.

Variables function in a very similar manner. In the given example, we essentially have a box called “firstName,” and we place the value “Amit” inside this box. When we wish to utilize this value, all we need to do is utilize the label, or in other words, the variable name “firstName.” Like this:

console.log(firstName); // Amit

Instead of using direct literal values as we did in the following examples:

console.log("Amit"); // Amit
console.log(34); // 34
console.log(45 + 9 + 27 - 18); // 63

We can now substitute the variable name, in this case, “firstName.”

ALSO READ:  1.4 Inline JavaScript

One of the best things about variables is their reusability. If we want to change the first name to “Aaradhya,” we only need to do it in one place:

firstName = "Aaradhya"; // Reassigning the variable
console.log(firstName); // Aaradhya

This characteristic of variables makes our code flexible and easier to maintain.

What is “Reassigning the variable” in JavaScript?

Reassigning the Variable in JavaScript refers to the process of changing the value stored in an existing variable. In JavaScript, variables can be declared and assigned initial values, but these values are not fixed; they can be modified or updated as needed during the execution of a program.

Here’s a breakdown of how reassigning variables works in JavaScript:

Variable Declaration: Initially, you declare a variable using the let, const, or var keyword, followed by the variable name. For example:

let age = 27; // Declaring a variable 'age' and assigning an initial value of 27.

Variable Reassignment: At any point in your code, you can change the value stored in the variable by simply using the variable name followed by the assignment operator (=) and a new value. For example:

age = 32; // Reassigning the variable 'age' with a new value of 32.

After this reassignment, the variable age no longer holds the value 27; it now holds the value 32.

Dynamic Nature: JavaScript is a dynamically typed language, meaning variables are not bound to a specific data type. You can reassign a variable to a value of a different data type:

age = "Twenty-nine"; // Reassigning 'age' to a string value.

The variable age initially held a numeric value, but it has now been reassigned to a string.

Reassigning variables is a fundamental concept in programming, allowing you to update and manipulate data as your program runs. It’s important to note that the use of let and var allows variables to be reassigned, while const declares variables as constants, meaning they cannot be reassigned after their initial value is set.

Naming Conventions and Rules

Naming conventions and rules are essential in JavaScript to ensure that your code is readable, maintainable, and follows best practices. While you’re free to be creative with variable names, there are some conventions and rules to follow in JavaScript:

camelCase Convention

Variable names with multiple words should follow the camelCase convention. camelCase is a widely adopted convention for naming variables with multiple words. It helps improve the readability of your code. In CamelCase, the first word starts with a lowercase letter, and subsequent words begin with uppercase letters.

Example: firstNamePerson. In this, “firstNamePerson” is a variable name following the camelCase convention. It suggests that this variable likely holds a person’s first name. The use of camelCase makes it clear where one word ends and the next begins, enhancing code readability.

Character Rules

JavaScript allows variable names to include letters, numbers, underscores (_), or dollar signs ($).

ALSO READ:  2.11 Type Conversion and Coercion in JavaScript

Variables cannot begin with a number, as this might be confused with numeric values. For example, 3years is not a valid variable name.

let 3years = 3; // Uncaught SyntaxError: Invalid or unexpected token

Forthermore, for example, if we try to write Amit & Aaradhya equals AA, we would once again get a syntax error.

let amit&aaradhya = 'AA'; // Uncaught SyntaxError: Unexpected token '&'

Example: firstNamePersonmyVariable, _privateVar, ⁣first_name_person, $price. These examples showcase valid variable names in JavaScript. “_privateVar“, ⁣”first_name_person“, and “$price” demonstrate the use of underscores and dollar signs, which are allowed characters in variable names.

For example, would be allowed:

let amit_aaradhya = "AA";
let $amit_aaradhya = "AA";
let $amit2aaradhya = "AA";

And we get no more errors here.

Reserved Keywords

Avoid using JavaScript reserved keywords like new, function, and let as variable names.

JavaScript has a set of reserved keywords that serve specific purposes within the language. It’s crucial to avoid using these reserved keywords as variable names to prevent conflicts and ensure code correctness.

Examples of reserved keywords include new, function, let, if, and many more. Attempting to use reserved keywords as variable names, like let = 42;, will result in a syntax error. It’s essential to choose variable names that are distinct from these reserved terms.

Another variable name that’s kind of reserved but still actually allowed to use is the name:

let name = "Amit"; // Amit

It would actually work. But in some cases, this create some problems. Because again, this is kind of a reserved keyword but it’s legal to use. But since it is a keyword never call your variables just “name“. That’s why always call them like this firstName.

Uppercase letter

Now, another convention that we should not start a variable name with an uppercase letter, so we should not do this:

let Person = "Amit";

So, now again, it’s a convention, so that’s not illegal. It’s just that we use this kind of variable names with an uppercase letter for a specific use case in JavaScript, which is object-oriented programming, as we see later in this JavaScript tutorial. So, for now, never do this.

But instead you should write it like this, with a lower case letter starting:

let person = "Amit";

Descriptive Names

Descriptive variable names are key to writing clean and maintainable code. When naming variables, select names that clearly convey the purpose or content of the variable.

Example: myFirstJob vs. job1

Use descriptive variable names that clearly convey what the variable represents. For example, myFirstJob is more informative than job1.

// Example 1:
let myFirstJob = "Programmer";
let myCurrentJob = "Teacher";

// Example 2:
let job1 = "programmer";
let job2 = "teacher";

Which set of variables do you think is more descriptive?, and I hope that you agree with me that’s much easier that what programmer and teacher are in this case here by simply looking at the variable name.

So, we know that, in the first set of variable example, my first job was programmer and that my current job is teacher. “myFirstJob” provides meaningful information about the variable’s purpose, making it easier for developers (including yourself) to understand its role in the code.

ALSO READ:  2.8 Working with Strings and Template Literals

In contrast, well, we would simply know that these are two different jobs, and we don’t know anything about them. “job1” is less informative and might lead to confusion about its significance.

So the first example approach is a lot better. Keep that in mind whenever you write own variable names and actually keep all of these in mind, that we just discussed for naming our variables.

Constants

Uppercase variable names (e.g., PI) are often used for constants that should never change.

Constants are variables that should not change their value throughout the program’s execution. By convention, constant variable names are written in uppercase letters to distinguish them from regular variables.

Example: PI

The number PI which is like 3.1415 and so on so forth:

let PI = 3.1415;

Constants like “PI” (representing the mathematical constant π) are typically assigned a value that remains constant throughout the program. Writing them in uppercase letters alerts developers that these variables are not intended to change during execution.

And of course we can write like this:

let pi = 3.1415;

But then this would be kind of weird actually. So, if it’s a real constant, write it in uppercase, So, that’s a pretty normal convention there in programming as a whole.

Conclusion

In summary, values and variables are the fundamental building blocks of JavaScript. Values are individual pieces of data, while variables are containers that hold these values. By adhering to naming conventions and rules, we can write clean, readable, and maintainable code.

To quickly summarize the concept of a variable, think of it as a container where we can store values. We assign a name to this container, such as ‘firstName’ or ‘myFirstJob’ in the examples given. We can then place a value into this container with the specified label.

For instance, in the case of “firstName,” the value might be “Amit,” and for “myFirstJob,” it could be “Programmer.” Subsequently, we can refer to these variables repeatedly, as shown in the following code:

console.log(firstName); // Amit
console.log(myFirstJob); // Programmer

When we execute this code, we will see “Amit” and “Programmer” displayed in the console. If we decide to change the value, let’s say to “Coder”:

myFirstJob = "Coder";
console.log(myFirstJob); // Coder

The change will propagate throughout the entire program, and we will now see “Coder” in the console. This is the fundamental purpose of variables. They are a fundamental concept in programming and should be thoroughly understood before progressing to our next lesson.

Discussion Values and Variables FAQs

Remember that learning is a dynamic process, and it’s natural to have questions. In your learning journey, you might have questions or encounter uncertainties along the way. To assist you in navigating your learning path, we’ve put together a collection of Values and Variables FAQs. Embrace the opportunity to learn, explore, and grow as you progress through your lessons and interact with the FAQs.

Assignments for values and variables

Now that you've grasped these essential concepts, it's time to apply your knowledge. Check out the assignments for this lesson in the "assignments.js" file in your project folder. These exercises will help solidify your understanding of values, variables, and naming conventions. Happy coding!

I understand your concern. If you haven't covered the Document Object Model (DOM) yet, it's a good idea to focus on assignments that align with your current level of knowledge. Here's a simpler assignment that doesn't require working with the DOM:

Assignment: JavaScript Variables Practice

Objective: The goal of this assignment is to practice declaring variables and outputting information using console.log().

Instructions:

  1. Create an HTML file with the necessary structure, including <script> tags for JavaScript.
  2. In your JavaScript code, do the following:
    • Declare variables to represent the following information:
      • Your first name
      • Your last name
      • Your age
      • Your favorite color
    • Use console.log() to print each variable's value to the browser console.
  3. Test your code by opening the HTML file in a web browser and inspecting the browser console to verify that the values of your variables are displayed correctly.

Certainly! Here's an assignment you can give to your students after the "JavaScript Fundamentals for Beginners - Introduction to JavaScript Values and Variables" lesson:


2. Assignment: JavaScript Values and Variables

Objective: Practice working with JavaScript values and variables.

Instructions:

  1. Declare Variables: In a new JavaScript file named assignments.js, declare three variables: country, continent, and population. These variables represent information about a country.
  2. Assign Values: Assign values to each of these variables based on a country of your choice. For example:
    • country should contain the name of the country (e.g., "Canada").
    • continent should contain the continent where the country is located (e.g., "North America").
    • population should contain the population of the country in millions (e.g., 37.74 for Canada).
  3. Display Information: Use console.log() statements to display the values of these variables. For example:
    • Log the name of the country.
    • Log the continent where the country is located.
    • Log the population of the country.
  4. Update Variables: Now, update the population variable to reflect a hypothetical increase in population. You can choose any value for this increase (e.g., add 1 million to the population).
  5. Display Updated Information: Use console.log() statements again to display the updated values of the population variable.

Submission Guidelines:

  • Create a new HTML file (e.g., assignments.html) to test your JavaScript code. Include this line within the HTML <body> tag to link your assignments.js file:
  <script src="assignments.js"></script>
  • Open assignments.html in your web browser and open the browser's developer console to view the output.
  • Document your code with comments as needed to explain what each part of your code does.

Grading Criteria:

Your assignment will be evaluated based on the following criteria:

  • Correct declaration and assignment of variables.
  • Accurate display of variable values using console.log().
  • Proper updating of the population variable.
  • Clarity and readability of your code, including comments where necessary.

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