Declaring and Assigning Variables

Variables are a key concept in programming as they allow us to store, retrieve, and manipulate data. Variables act as containers for storing data values. Think of a variable as a box where you can store a value, label it, and retrieve or change it later.

This section will introduce the concept of variables and how to use them in JavaScript.

Variables help manage and organize data by:

  • Storing Values: Hold data that can be used later in the program.
  • Reusability: You can use the same value in different parts of the code without repeating it.
  • Readability: Make code more readable and easier to understand using meaningful names instead of hard-coded values.

Understanding Variables as Boxes

Imagine a variable as a box. You can put a value inside the box and give it a name. Later, you can look inside the box (retrieve the value) or replace its contents (reassign a new value).

  1. Declaring a Variable: Creating the box.
  2. Assigning a Value: Putting something inside the box.
  3. Accessing the Value: Looking inside the box to see what's there.
  4. Reassigning a Value: Replacing the box's contents with something new.

Now let's go through how we do each of these in code:

Declaring Variables

In JavaScript, variables can be declared using the let and const keywords.

The let keyword declares a variable that can be reassigned. It’s like a box you can open and put new items into.

Example: Declare a variable called message:

let message; 

The const keyword declares a variable with a value that cannot be reassigned after its initial assignment. It’s like a box you seal after putting something inside; you cannot change its contents later. This will make sense a little later.

Example: Declare a variable called greeting with const:

const greeting;

Assigning Values to Variables

Assigning a value to a variable involves using the assignment operator (=) to set the variable's value. It’s like placing an item inside the box and labeling it.

Here's how you use it:

let age = 25; // The 'age' box now contains the number 25
const name = 'John Doe'; // The 'name' box now contains the string 'John Doe'

Accessing Variables

Once a variable is declared and assigned a value, you can access and use the value stored in the variable. It’s like looking inside the box to see what’s stored there.

One of the most common ways you'll find yourself printing the values to the console when you are building apps is using something called console.log and passing it a value or expression.

Here's an example of declaring and using a variable with a console.log:

let age = 25;
console.log(age); // Outputs: 25

const name = 'John Doe';
console.log(name); // Outputs: John Doe

We will combine variables and use them outside of a console.log a little later, but for now, it's the easiest way to look inside your box.

Reassigning Variables

Variables declared with let can be reassigned to new values. However, variables declared with const cannot be reassigned.

Here's an example:

let age = 25;
age = 26; // The 'age' box now contains the number 26

const name = 'John Doe';
// name = 'Jane Doe'; // This will cause an error because you cannot change the content of a 'const' box

Best Practices for Using Variables

Use meaningful names: Choose variable names that describe the data they hold, making it easier to understand what is stored in each box.

let userName = 'John Doe';
let userAge = 30;

Use const by default: Use const for variables that should not change to ensure immutability. You usually do not want your value to change accidentally, so use let only when you expect the variable to change.

const pi = 3.14159; // The value of pi doesn't change
let counter = 0; // The value of the counter will change as we count

Combining and Using Variables in Your Code

Once you understand how to declare, assign, and access variables, you can combine these concepts to create more dynamic and flexible code. Here’s how you can use variables together in practical scenarios:

Example: Calculating Age

Suppose you want to calculate someone's age based on their birth year and the current year. You can use variables to store these values and perform the calculation.

Step-by-Step: Run each step in your browser console.

  1. Declare Variables for Birth Year and Current Year:
const birthYear = 1990; // The year of birth
let currentYear = 2024; // The current year
  1. Calculate Age:
let age = currentYear - birthYear; // Subtract birth year from the current year to get the age
  1. Display the Result:
console.log('Your age is: ' + age); // Outputs: Your age is: 34

Example: Updating and Using Variables

Suppose you have a variable that needs to change over time, such as a counter that increments every time a button is clicked.

Step-by-Step: Run each step in your browser console.

  1. Declare and Initialize a Counter Variable:
let counter = 0; // Start the counter at 0
  1. Increment the Counter:
counter = counter + 1; // Add 1 to the current value of counter
  1. Display the Counter Value:
console.log('The counter value is: ' + counter); // Outputs the current counter value

Example: Combining Strings

You can also use variables to combine strings and create more complex messages.

Step-by-Step: Run each step in your browser console.

  1. Declare Variables for Parts of a Message:
const greeting = 'Hello';
const name = 'Alice';
const exclamation = '!';
  1. Combine the Strings:
let completeMessage = greeting + ', ' + name + exclamation; // Combine the parts into a full message
  1. Display the Message:
console.log(completeMessage); // Outputs: Hello, Alice!

Putting It All Together

Here’s a more comprehensive example that combines all these concepts:

Scenario: Calculate the years until a user can retire. Assume the retirement age is 65.

  1. Declare and Assign Variables:
const birthYear = 1990;
let currentYear = 2024;
const retirementAge = 65;
  1. Calculate Current Age:
let currentAge = currentYear - birthYear;
  1. Calculate Years Until Retirement:
let yearsUntilRetirement = retirementAge - currentAge;
  1. Display the Result:
console.log('You have ' + yearsUntilRetirement + ' years until retirement.');

Here's what you should see as the output in your console if you run each step:

'You have 31 years until retirement.'

By combining variables, you can create more complex and functional JavaScript programs. This foundational skill will be essential as you move on to more advanced topics and build more interactive web applications.

Next, we will explore arrays, allowing us to store multiple values in a single variable.

BeginnerJavaScript
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.