Back
Activity 1.3 Strings
Introduction
Topics
- The String data type
-
String Formatting
- String concatenation
- String templates
The String data type
The string data type represents a sequence of characters used for
text.
Double Quotes: "Hello friend."
Single Quotes: 'Mortimer rules'
Backticks: `Go Eagles!`
I am happy!
"I am sad!
"I said "don't" do it."
Demo: Print Strings with
Different Quotes
console.log("Hey, how's it going?");
console.log('Wildcats have hairballs.');
console.log(`Pizza Hut > Dominos. Fight me.`);
String Formatting
The process of inserting variables or values into a string to
create a complete, readable message.
String Concatenation
Use addition sign (+
) to combine strings.
console.log("Mortimer " + "rules");
console.log("You owe me $" + 1000);
String Concatenation
Use addition sign (+
) to combine strings.
console.log("Mortimer " + "rules");
console.log("You owe me $" + 1000);
String Template
Special strings that let you easily insert code inside text by
using backticks (`
) and ${ }
placeholders.
console.log(`I am 35 years old, which is ${35 * 12} months.`);
String Template
Special strings that let you easily insert code inside text by
using backticks (`
) and ${ }
placeholders.
console.log(`I am 35 years old, which is ${35 * 12} months.`);
I am 35 years old, which is 420 months. I am an old fart.
'F' → Fullscreen
Objectives
-
Using string concatenation for formatted output -
Using string string templates for formatted output
Activity Tasks
-
Create a new project named 1-3-string.js.
-
Complete each task individually.
Task 1: Use string
concatenation
-
Use string concatenation to append math expressions to your strings.
console.log("10 squared is " + (10 * 10));
console.log("I'm 5 foot 10 inches. That's " + (5 * 12 + 10) + "inches.");
Task 2: Use String Templates
-
Use string templates to insert math expressions directly into your
strings.
console.log("10 squared is " + (10 * 10));
console.log("I'm 5 foot 10 inches. That's " + (5 * 12 + 10) + "inches.");
console.log(`If I take out a $1000 loan, and pay $25 each month, I will pay off my loan in ${1000 / 25} months.`);
console.log("A woodchuck can chuck 32 wood panels every minute.");
console.log(`Therefore, a woodchuck can chuck ${32 * 60} wood panels every hour.`);
Sample Output
Your program output should something similar to the sample output
below.
I'm 5 foot 10 inches. That's 70inches.
If I take out a $1000 loan, and pay $25 each month, I will pay off my loan in 40 months.
A woodchuck can chuck 32 wood panels every minute.
Therefore, a woodchuck can chuck 1920 wood panels every hour.
Reflection Questions
You may write your reflection answers as comments at the bottom of
your code.
-
Do you have a preference for string concatenation or string
templates?
-
When would you consider using one string formatting technique over
the other?
Submission
Submit your activity and reflection answers to the appropriate
dropbox.
Activity Complete