Output with Variables
Part of the Fundamentals section of Coddy's JavaScript journey — lesson 29 of 77.
As of now we learned how to print simple strings, but sometimes we need to insert variable values into the string.
For example:
let age = 10;
console.log("His age is: age");This will print "His age is: age" instead of "His age is: 10"
To make it work, we will use template literals:
let age = 10;
console.log(`His age is: ${age}`);This prints "His age is: 10"
We use backticks `` instead of quotation marks "" and inside the string wherever we put curly braces {} with a dollar sign $ before it, it will insert the value of what is written inside it.
Challenge
BeginnerYou are given a code that stores a random string as input to a variable named rnd.
Print to the console "The input is: " and the random string that is inside the variable rnd.
Check the test cases for examples!
Cheat sheet
To insert variable values into strings, use template literals with backticks `` and ${} syntax:
let age = 10;
console.log(`His age is: ${age}`);This prints "His age is: 10" instead of the literal text "His age is: age".
Template literals use:
- Backticks
``instead of quotation marks"" ${variable}to insert variable values
Try it yourself
let rnd = inp; // Don't change this line
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Type Coercion7Bill Split Calculator
Welcome MessageCalculating The Tip And Total2Variables
NumbersStringBooleanNaming ConventionsEmpty VariablesRecap - Initialize VariablesConstants3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsComparison OperatorsStrict vs Loose EqualityRecap - Simple Math6Basic IO
OutputOutput with VariablesType Conversion - Part 1Type Conversion - Part 2Recap - Till 120Recap - True or False