9. JavaScript: Data Types

9. JavaScript: Data Types

Welcome to your first JavaScript lesson: data types!

What Is JavaScript?

JavaScript is the language of the internet. It is commonly confused with Java, but they are two very different languages. As of now, we can build great looking websites, but they don’t do much. JavaScript is what allows our pages to be dynamic - show your name in the top corner to indicate you are signed in, change information on the screen based on what you type in a form, etc.
If we compare a web app to a human body, we can think of HTML as a skeleton, CSS as clothes and accessories, and JavaScript as the muscle.
 

🎯 Learning Goals

  • Use variables to store strings and numbers
  • Use string interpolation to write sentences using variables

📗 Technical Vocabulary

  • Console
  • Interpolation
  • Number
  • String
  • Variable
  • Assignment Operator
  • Data Type
Warm-up
Avatar: The Last Airbender Element Training Game (created by Kode With Klossy Alum, Riya Patel!). Choose any element you’d like!
As you play, consider these questions:
  1. What kinds of information does the game track?
  1. What information changes over time?

Data Types

Throughout camp, you will learn about several different data types in JavaScript. A data type is a specific kind of information or data. Based on the type of data we write in our code, the program will interpret it differently. In this lesson, we will learn about Strings and Numbers.
🐚
Here is a sample CodeSandbox for you to fork and use throughout this lesson → Lesson 10: JavaScript: Data Types Starter

Strings

A string is a primitive JavaScript data type. You can think of a string as a series of characters (alpha, numeric, spaces, and special characters) between two quotation marks, like so:
'Hello, World!' "Hi, coding scholar!" "✨ 🎩 💖 "
In JavaScript, strings can be either double-quoted (“like this”) or single-quoted (‘like this’).
console.log()
Right now, we can see the strings we type in when we hit enter. However, we won’t always be writing our code in the console, so let’s move to a more realistic way of writing our JavaScript.
In the editor, type the following:
console.log('Hello, World!');
You should see “Hello, World!” appear in the console. This isn’t super exciting right now, but we will build on it.
 

console.log

In JavaScript, console.log() is a built-in function that lets you print messages to the console (a tool that developers use to see what their code is doing).
It’s like saying, “Hey JavaScript, show me this so I can check it!”

Why use it?

  • To see the value of a variable
  • To check if your code is running
  • To debug (figure out what’s going wrong)
So if you're ever wondering what your code is doing, console.log() is your best friend!
👉
The image to the right will show you how to toggle your console in CodeSandbox if you aren’t seeing the output.
 
notion image
✏️
Try-It | Strings and console.log
  1. Type console.log("your first name");. Instead of the words "your first name", type your actual name! You do need to include the quotes.
  1. Output your age.
  1. Output your full name.
  1. Output any text you want! Try to use some characters from your keyboard that are not numbers or letters. Make sure your text is enclosed in quotes.
💼
Takeaways
  • Strings can hold any type of character, including spaces
  • The way we type a string will be the exact way a computer sees it (it won’t assume we meant to capitalize that first letter, catch if we misspell something, etc.)
 
💡
Note: JavaScript code will usually run without a semicolon at the end of each line. This is due to JavaScript Automatic Semicolon Insertion. However, it is good practice to learn to use semicolons in order for coding skills to transfer to other languages.

Variables

In most programming languages, including JavaScript, values can be saved to variables. Unlike in math class, where we would use x or y and a number, variables in programming are much more flexible. Below are three variables that help define a nation in the Avatar universe:
var nation = "Air Nomads"; var nationDescription = "peaceful and spiritual"; var ally = "Aang";
To define a variable, we use the var keyword, followed by a descriptive name we choose for the variable. Notice that all of the variables start with a lowercase letter. If you are selecting a variable name that has two words, make the first letter of the second word uppercase. This pattern is called camelCase.
After naming the variable, we use the = sign to show what value the variable will hold. In programming, we refer to the = as the assignment operator rather than the equals sign. It’s still frequently called the equals sign, though, so you’ll hear it, and people will know what you are referring to if you use that terminology.
We can now print any of these variables we have defined out to the console. The example below defines three variables, but only one will be logged to the console.
var nation = "Air Nomads"; var nationDescription = "peaceful and spiritual"; var ally = "Aang"; console.log(nation); //=> "Air Nomads"
💡
Pro Tip
Have you noticed that sometimes lines of code in example are greyed out and start with two forward slashes //?
Comments are a way we can take notes in plain english, or use snippets of code that aren't complete. They appear in a shade less obvious that most lines of code and will not be read by the interpreter!
To write a comment in your JavaScript code, start the line with two forward slashes //. Or, you can use the keyboard shortcut cmd + / on a Mac or ctrl + / on a PC!
✏️
Try-It | Variables and Assignment
Type your code on the left side of the page, save it, and then observe the results in the console on the right side of the page.
Declare a variable for each prompt below. Then, print each variable to the console.
  • A variable called favoriteColor that holds your favorite color
  • A variable called pet that holds the name of a pet
  • A variable called friend that holds the name of a friend
  • A variable called goal that holds one of your goals. Remember, you can include spaces in a string!
  • A variable called hobby that holds one of your hobbies

Reassigning Variables and Interpolation

Re-assigning Variables

Sometimes, things in life change! We might change our names, move cities, or our ages will certainly change. In the Avatar world, the characters are constantly traveling across the map. As they move from region to region, we might need to re-assign the nation variable to track their current location.
JavaScript gives us the ability to re-assign a variable so that its value can change. Here is the syntax:
// The line below declares the variable house and assigns it to "Air Nomads" var nation = "Air Nomads"; console.log(nation); //=> "Air Nomads" // The line below re-assigns the variable house to "Fire Nation" nation = "Fire Nation"; console.log(nation); //=> "Fire Nation"
Notice that when we re-assign a variable, we do not use the keyword var.

Interpolation

We can also insert variable data into a longer string. This is called interpolation:
var nation = "Air Nomads"; var nationDescription = "peaceful and spiritual"; var ally = "Aang"; console.log(`Welcome to the ${nationDescription} ${nation}! Once you master this training path, you’ll work alongside powerful allies like ${ally}.`); //=> Welcome to the peaceful and spiritual Air Nomads! Once you master this training path, you’ll work alongside powerful allies like Aang.
Make sure to use the backticks when you are using string interpolation (image below); it will not work with regular single or double quotes.
notion image
✏️
Try-It | Interpolation
If you have the strings "Karlie" and "Kloss" in the following variables:
var first = "Karlie"; var last = "Kloss";
Use string interpolation to complete the following:
  • What code can you write to output the string "KarlieKloss"?
  • What code can you write to output the string "KlossKarlie"?
  • What code can you write to output the string "Karlie Kloss"?
  • What code can you write to output the string "Kloss Karlie Kloss Karlie"?
  • What code can you write to output the string "Karlie rocks!"?

Numbers

Numbers are another primitive JavaScript data type. Unlike strings, which store text, numbers allow us to perform math and count things. This is perfect for tracking stats in a game!
For example, mastering the elements in the Avatar world is messy work! Let’s use numbers to track stats from a skills training session. We need variables to count your total attempts, but since beginners often miss their target, we also need a variable to track collateral damage. We’ll use the variable cabbagesDestroyed, a nod to the unlucky merchant whose cart gets smashed in almost every episode.
var attempts = 0; var cabbagesDestroyed = 0; // A running joke in the series!
We can also re-assign variables that store numbers. In this example, we need to update the attempts count every time the character tries a move.
console.log(attempts); //=> 0 // The line below re-assigns points to its previous value (0) plus 1. attempts = attempts + 1; console.log(attempts); //=> 1 // The line below re-assigns points to its previous value (1) plus 1. // It is a shortcut that does the exact thing as the example above! attempts += 1; console.log(attempts); //=> 2
💭
Think About It: Write It Down
Incrementing numbers like what we just looked at above is something developers do very frequently. Brainstorm some examples of numbers incrementing in real apps that you use.
Open the toggle to compare your ideas with some examples!
  • On a user's birthday, an app should increment their age
  • Social media apps use incrementing to keep track of the number of likes, replies, followers, etc.
  • Apps that involve scheduling - calendar events, flights, live video classes, etc. usually have a countdown timer to keep the user informed on the amount of time until something will happen
Again, as we did with strings, we can interpolate with variables that store numbers.
var element = "Water"; cabbagesDestroyed = 3; console.log(`Great work! You mastered the ${element} Whip technique after ${attempts} attempts, but you accidentally destroyed ${cabbagesDestroyed} cabbage carts.`);
We can also do math with numbers in JavaScript! The same math operators you know from math class work here.
3 + 5 //=> 8 12 / 2 //=> 6 18 - 8 //=> 10
We can also use parentheses, and the Order of Operations rule applies here as well.
(3 + 2) * 8 // 5 * 8 //=> 40
We can also use math on variables if those variables hold numbers.
var kyoshiWarriors = 42; var villagesToDefend = 12; var avgSquadSize = kyoshiWarriors / villagesToDefend; console.log(avgSquadSize); //=> 3.5 console.log(`The Kyoshi Warriors are brave, but they can't be everywhere at once. We have ${kyoshiWarriors} warriors available to protect ${villagesToDefend} different Earth Kingdom villages. That means we can deploy an average squad size of ${avgSquadSize} warriors per village!`); //=> "The Kyoshi Warriors are brave, but they can't be everywhere at once. We have 42 warriors available to protect 12 different Earth Kingdom villages. That means we can deploy an average squad size of 3.5 warriors per village!"
✏️
Try-It | Numbers & Operators
Use the same CodeSandbox project from previous try-its. You may need to comment out your previous code. Write code to find the average of the four numbers below:
var a = 12; var b = 65; var c = 31; var d = 98;
Click here for Medium Practice 🌶🌶
Find the answer to this problem using JavaScript. On average, there are 47.5 scholars at each Kode With Klossy camp this year. If there are 25 camps taking place, how many scholars are attending in total? Print your answer to the console in a complete sentence.
Click here for Spicy Practice 🌶🌶🌶
Modify your code to round the total number of scholars to the nearest whole number. Print the new number of scholars to the console in a complete sentence.
📝
Practice | JavaScript: Data Types
Create a profile for any character you like. It could be a superhero, a cartoon character, a historical figure, or even yourself.
You will need to define their Name and Role (e.g., "Firebender", "Point Guard", "Pop Star"). Then, pick two number stats that describe them (like "Strength", "Speed", "Creativity", or "Cuteness") and use math to calculate a total score. Finally, print it all out in a cool card format!
  1. Define your variables:
      • Create a variable for characterName (String)
      • Create a variable for characterRole (String - e.g. "Ninja", "Chef", "Athlete")
      • Create two variables for stats (Numbers - e.g. strength, speed, charm, cookingSkill)
      • Create a variable for specialMove (String)
  1. Do some math! Create a new variable called totalPower (or similar) that adds your two stat variables together.
  1. Use string interpolation to output your character’s "Trading Card” to the console. Update the variable names inside the ${} to match the ones you created above!
var characterProfile = ` ================================ | NAME: ${characterName} | ROLE: ${characterRole} | ------------------------------ | Stat 1: ${stat1} | Stat 2: ${stat2} | TOTAL POWER SCORE: ${totalPower} | ------------------------------ | Signature Move: "${specialMove}" ================================ `; console.log(characterProfile);
🌶️ Spicy Challenge: Add a boolean variable called isLegendary and assign it the appropriate value!
page icon
For a summary of this lesson, check out the 10. JavaScript: Data Types One-Pager!