Define and Use Variables in JavaScript

HTMLHTMLBeginner
Practice Now

Introduction

In this lab, participants will explore the fundamental concepts of defining and using variables in JavaScript, a critical skill for web development. The lab guides learners through understanding JavaScript's role in creating interactive web experiences, setting up an HTML environment, and mastering variable declaration and manipulation techniques.

Participants will learn how to declare variables using the var keyword, assign values to these variables, and display them dynamically on web pages. By following step-by-step instructions, students will gain practical experience with JavaScript's core programming principles, including variable naming conventions and basic scripting techniques that form the foundation of modern web development.

Understand JavaScript and Its Role in Web Development

In this step, you'll learn about JavaScript and its crucial role in web development. JavaScript is a powerful, versatile programming language that brings interactivity and dynamic functionality to websites.

JavaScript is a client-side scripting language primarily used in web browsers. It allows developers to create interactive and dynamic web pages by manipulating HTML and CSS, handling user events, and performing complex calculations in real-time.

Key characteristics of JavaScript include:

  • Runs directly in web browsers
  • Enables interactive web experiences
  • Can modify HTML and CSS dynamically
  • Supports event-driven programming
  • Used for both front-end and back-end development (with Node.js)

Here's a simple example to demonstrate JavaScript's basic functionality:

<!doctype html>
<html>
  <head>
    <title>JavaScript Introduction</title>
  </head>
  <body>
    <h1 id="greeting">Hello, Web Development!</h1>
    <script>
      // JavaScript can dynamically change page content
      document.getElementById("greeting").innerHTML = "Welcome to JavaScript!";
    </script>
  </body>
</html>

Example output in browser:

Welcome to JavaScript!

This example shows how JavaScript can instantly modify webpage content, demonstrating its power in creating dynamic web experiences.

Set Up HTML File for JavaScript

In this step, you'll learn how to create an HTML file that can include and execute JavaScript code. HTML provides the structure for web pages, and JavaScript adds interactivity and dynamic functionality.

First, navigate to the project directory:

cd ~/project

Create a new HTML file called variables.html using the WebIDE:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>JavaScript Variables</title>
  </head>
  <body>
    <h1>Learning JavaScript Variables</h1>

    <!-- We'll add JavaScript here in the next steps -->
    <script>
      // JavaScript code will go here
    </script>
  </body>
</html>

Key points about the HTML structure:

  • <!DOCTYPE html> declares this is an HTML5 document
  • <script> tag is where JavaScript code will be written
  • You can place the <script> tag in the <head> or <body> section

Example output when opened in a browser:

Learning JavaScript Variables

The <script> tag allows you to write JavaScript directly in the HTML file or link to an external JavaScript file. In the upcoming steps, we'll add JavaScript code to this file to work with variables.

Declare Variables Using var Keyword

In this step, you'll learn how to declare variables in JavaScript using the var keyword. Variables are containers for storing data values that can be used and manipulated throughout your code.

Open the variables.html file in the WebIDE and modify the <script> section to add variable declarations:

<!doctype html>
<html lang="en">
  <body>
    <script>
      // Declaring variables using var keyword
      var firstName = "John";
      var age = 25;
      var isStudent = true;

      // You can also declare a variable without initial value
      var lastName;
    </script>
  </body>
</html>

Key points about variable declaration:

  • var is used to declare variables in JavaScript
  • Variables can store different types of data:
    • Strings (text): "John"
    • Numbers: 25
    • Boolean values: true or false
  • You can declare a variable without an initial value

To see the variables in action, you can use console.log() to display their values:

<script>
  var firstName = "John";
  console.log(firstName); // Outputs: John
</script>

Example output in browser's developer console:

John

Assign and Display Variable Values

In this step, you'll learn how to assign values to variables and display them using different methods in JavaScript. Building on the previous step, we'll explore how to work with variable values.

Open the variables.html file and update the <script> section with the following code:

<!doctype html>
<html lang="en">
  <body>
    <div id="output"></div>
    <script>
      // Declaring and assigning variables
      var firstName = "John";
      var age = 25;
      var isStudent = true;

      // Reassigning variable values
      age = 26;
      firstName = "Jane";

      // Displaying values using console.log()
      console.log("Name: " + firstName);
      console.log("Age: " + age);
      console.log("Is Student: " + isStudent);

      // Displaying values on the webpage
      var outputElement = document.getElementById("output");
      outputElement.innerHTML =
        "Name: " +
        firstName +
        "<br>Age: " +
        age +
        "<br>Is Student: " +
        isStudent;
    </script>
  </body>
</html>

Key points about assigning and displaying variables:

  • Use = to assign or reassign values to variables
  • console.log() displays values in the browser's developer console
  • document.getElementById().innerHTML can display values directly on the webpage
  • You can concatenate strings and variables using +

Example output in browser's developer console:

Name: Jane
Age: 26
Is Student: true

Example output on webpage:

Name: Jane
Age: 26
Is Student: true

Practice Variable Naming Conventions

In this step, you'll learn about best practices for naming variables in JavaScript. Good variable naming is crucial for writing clean, readable, and maintainable code.

Open the variables.html file and update the <script> section with the following examples:

<!doctype html>
<html lang="en">
  <body>
    <div id="output"></div>
    <script>
      // Good variable naming conventions

      // Use camelCase for variable names
      var firstName = "John";
      var lastName = "Doe";
      var age = 25;
      var isStudent = true;

      // Descriptive and meaningful names
      var totalPrice = 99.99;
      var discountPercentage = 10;
      var calculatedDiscount = totalPrice * (discountPercentage / 100);

      // Avoid single-letter variables (except in specific cases like loops)
      var x = 10; // Bad
      var width = 10; // Good

      // Display the results
      console.log("Full Name: " + firstName + " " + lastName);
      console.log("Discounted Price: $" + calculatedDiscount);

      var outputElement = document.getElementById("output");
      outputElement.innerHTML =
        "Full Name: " +
        firstName +
        " " +
        lastName +
        "<br>Age: " +
        age +
        "<br>Discounted Price: $" +
        calculatedDiscount;
    </script>
  </body>
</html>

Key variable naming conventions:

  • Use camelCase (e.g., firstName, lastName)
  • Choose descriptive and meaningful names
  • Avoid single-letter variable names
  • Be consistent in your naming style
  • Use nouns for variables
  • Use meaningful prefixes like is for boolean variables

Example output in browser's developer console:

Full Name: John Doe
Discounted Price: $9.999

Example output on webpage:

Full Name: John Doe
Age: 25
Discounted Price: $9.999

Summary

In this lab, participants explore the fundamental concepts of JavaScript variables and their role in web development. The lab begins by introducing JavaScript as a powerful client-side scripting language that enables interactive and dynamic web experiences, highlighting its ability to manipulate HTML and CSS, handle user events, and perform real-time calculations.

Through a step-by-step approach, learners set up an HTML file and begin practicing variable declaration using the var keyword, understanding the importance of proper variable naming conventions and how to assign and display variable values. The hands-on exercises provide practical insights into creating dynamic web content, demonstrating JavaScript's versatility in transforming static web pages into interactive and engaging user experiences.