IN THIS LESSON
What are Strings?
String manipulation is one of the cornerstones of programming. Which makes sense since so much of what we do on the internet is just some kind of text.
Dynamic Template Strings
It's common to only want a piece of a string to change. Instead we use Template Strings, which allow us to interpolate (meaning "insert") data directly. Template Strings can also be called Template Literals.
Creating template strings
When creating a template string instead of using " or ', you surround your text with backticks ``. You get those by hitting shift and the key above your tab key with your left pinky pink.
let greeting = `Hello!`
This template string is somewhat on the plain side, featuring static code throughout. To elevate its appeal, let's introduce a variable. How about a name? To seamlessly integrate a snippet of code into the template, enclose it within the ${ } operator. Spot the vibrant color change, and you'll know you've spiced things up successfully.
let name = "Jay"
let greeting = `Hello ${name}!`
You can interpolate multiple pieces into a single string, and I meant it when I said "chunks of code." You aren't limited to only variables. Try playing around with some templates to get the hang of it. Be careful about your spaces!
let hobbi = "Jay"
let emphasis = "!"
let greet = `Hello, ${name}${emphasis}`
console.log(greet)
let price = `$${4 + 2} dollars`
console.log(price)
Since a template is enclosed by backticks, you can use regular quotes inside without issue.
Concatenation
There's another method to make dynamic strings called concatenation. It literally adds strings together, but it's a little clunky. Templates are more common now, please do not use concatenation in your challenge submissions. We want to see how you handle interpolation.
let quotes = `"All quotes" 'work!'`
console.log(quotes)
🎉 Congratulations! You've successfully grasped the basic fundamentals of Strings. Now, let's reinforce your learnings with some hands-on practice. Below are prompts to help you strengthen your skills. Feel free to use the CodePen link provided to write and test your code, press Run Pen to activate the terminal:
Challenge 1: Create a variable called brand that states what type of computer you have, log to the “The computer I have is [brand]”
Challenge 2: Create two variables of your favorite food, then log “My two favorite foods are [food1][food2]
Challenge 3: Create two variables of your first and last name. Then log to the console “My first name is [first name] and my last is [last name]