Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 18

JavaScript Variables and Data Types

Recommended resources

Hello! Welcome to the fourth module of our course.

In the previous modules, we've focused on building the "look" of our AI Writing Assistant. We created the structure with HTML and styled it using CSS and the Bootstrap framework. Our page looks good, but it's completely static—clicking the "Analyze Text" button does nothing. That's about to change.

In this module, we will dive into JavaScript, the programming language that brings web pages to life. JavaScript allows us to add interactivity, manipulate content, and communicate with servers. It's the "engine" of our web application.

Today's lesson is our first step into this new world. We will cover the most fundamental building blocks of any programming language: declaring variables and working with basic data types. You'll learn how to create "containers" to store information like user input, and you'll get familiar with the different kinds of data you'll be working with, such as text and numbers.

Getting Started: Your JavaScript Playground

Before we start writing code for our application, you need a place to experiment and see instant results. The best place for this is your web browser's built-in developer console.

To learn how to open and use the console, let's watch a short video. This is a crucial tool you'll be using every day as a web developer.

JavaScript Variables & JavaScript Data Types explained | JavaScript Tutorial #2

This clip from the 'JavaScript Variables & JavaScript Data Types explained' video by TechWorld with Nana will show you how to open the developer tools and use the console tab to write your very first lines of JavaScript.

Watch from 00:42 to 01:59. Follow along by opening the developer console in your own browser (Chrome or Firefox is recommended).

Keep the console open as you go through this lesson. It's your space to practice!


What is a Variable?

In programming, a variable is like a labeled box or container where you can store a piece of information. You give the box a name, and later, you can look up that name to see what's inside, or even replace it with something new. This is essential for writing any program, as you constantly need to store and manage data, such as a user's name, the text from an input field, or the result of a calculation.

This next video provides a great analogy to help you understand this core concept.

JavaScript VARIABLES are easy! 📦

This clip from 'JavaScript VARIABLES are easy! 📦' by Bro Code explains what variables are and the two steps to creating them: declaration and assignment.

Watch the first minute of the video (00:00 to 01:00). Pay attention to the idea of a variable as a 'container' for a value.


Declaring and Naming Variables

As the video mentioned, creating a variable involves two steps:

  1. Declaration: Creating the variable and giving it a name.
  2. Assignment: Putting a value into the variable.

You can do these on separate lines or together on one line.

// Declaration and assignment in two steps
let message;
message = "Hello, world!";

// Declaration and assignment in one step
let userAge = 25;

Using let and const

In modern JavaScript, you'll use two keywords to declare variables: let and const.

  • let: Use let when you expect the value of the variable to change later in your program.

    let score = 0;
    score = score + 10; // The value of score is now 10
    console.log(score);
    
  • const: Use const (short for constant) when you know the value will not change. If you try to change it, JavaScript will give you an error. This is useful for preventing accidental changes to important values.

    const name = "Alice";
    // name = "Bob"; // This would cause an error!
    console.log(name);
    

A simple rule of thumb: Always start by declaring variables with const. If you later realize you need to change the variable's value, switch it to let. You will almost never use the older var keyword, but it's good to know it exists as you might see it in older code examples online.

For a more detailed explanation of let, const, and the rules for naming variables, please read the following sections from the article "JavaScript Variables and Data Types".

JavaScript Variables and Data Types: Complete Beginner ...

This article provides a thorough guide to variables. We'll focus on the sections explaining how to declare them and the conventions for naming them.

Read the sections titled 'Declare, then assign', 'var, let, const', and 'How to write a variable'. Focus on understanding the difference between let and const, and the camelCase naming convention.

Test your understanding!

Based on the naming rules, which of the following variable names are valid and which are invalid?

  1. let user name;
  2. const 1stPlace;
  3. let user_age;
  4. const favoriteColor;
Show answer
  1. Invalid: Variable names cannot contain spaces. It should be userName.
  2. Invalid: Variable names cannot start with a number.
  3. Valid: This is called snake_case and is valid, but camelCase (userAge) is the standard convention in JavaScript.
  4. Valid: This follows the camelCase convention and is a perfect variable name.

Basic Data Types

Variables can hold different types of data. For now, we will focus on the three most common "primitive" data types: Strings, Numbers, and Booleans.

JavaScript Data Types Flowchart
This chart illustrates the different kinds of data in JavaScript. We are focusing on Numbers, Strings, and Booleans for now.

Let's watch a video that introduces each of these types with clear examples. As you watch, try typing the examples into your developer console!

JavaScript VARIABLES are easy! 📦

This video from Bro Code will walk you through the Number, String, and Boolean data types.

Watch from 01:55 to 09:11. Pay attention to the syntax for each type (e.g., quotes for strings) and how they can be used.

Let's summarize these data types:

1. String

A string is used to store text. You create a string by wrapping text in either single (') or double (") quotes.

  • Use Case for our App: The text the user types into the <textarea> will be a string.
const greeting = "Hello, welcome to the AI Writing Assistant!";
const userName = 'Alice';
console.log(greeting);

2. Number

A number is used for numerical values, both integers (like 10) and decimals (like 3.14). You do not use quotes around numbers.

  • Use Case for our App: We can use numbers to store the word count, character count, or a readability score.
const wordCount = 150;
const readingScore = 85.5;
console.log(wordCount);

Important: A number inside quotes, like "150", is a string, not a number. You cannot perform mathematical calculations with it.

3. Boolean

A boolean represents a state of true or false. It's like a simple on/off switch.

  • Use Case for our App: We could use a boolean to track if the text analysis is currently in progress.
const isOnline = true;
let isAnalysisComplete = false;
console.log(isAnalysisComplete); // This will print false

Checking Your Work with console.log and typeof

As you've seen in the examples, console.log() is your best friend. It lets you print the value of any variable to the console to check if your code is working as expected.

Sometimes, you might also want to check the data type of a variable. You can do this with the typeof operator.

Try this in your console:

const name = "Bob";
const age = 42;
const aStringNumber = "42";

console.log(typeof name);          // Output: "string"
console.log(typeof age);           // Output: "number"
console.log(typeof aStringNumber); // Output: "string"

This is very useful for debugging when your code isn't behaving as you expect.

Test your understanding!

Declare three variables in your console:

  1. A const variable named appName with the value "AI Writing Assistant".
  2. A let variable named characterLimit with the value 5000.
  3. A const variable named isProUser with the value false.

After declaring them, use console.log() to print the value of each one. Then, use typeof to check the data type of appName and characterLimit.

Show answer

Here's the code you would type into your console:

const appName = "AI Writing Assistant";
let characterLimit = 5000;
const isProUser = false;

console.log(appName);
console.log(characterLimit);
console.log(isProUser);

console.log(typeof appName);        // Should print "string"
console.log(typeof characterLimit); // Should print "number"

Conclusion

Fantastic work on your first lesson in JavaScript! You've learned the absolute fundamentals that every other concept will build upon.

Key Takeaways:

  • JavaScript is the language that adds interactivity to web pages.
  • The developer console is your playground for testing and debugging code.
  • Variables are named containers for storing data, declared with let (for values that can change) and const (for values that won't).
  • The three basic data types are String (text), Number (numeric values), and Boolean (true or false).
  • console.log() is used to print values to the console, and typeof can tell you the data type of a variable.

In our next lesson, we'll take the next crucial step: you will write JavaScript code in a separate file and connect it to your HTML page. This will allow us to start building the logic that will eventually power our "Analyze Text" button.