Template Literal (Template string)
We can easily write the string and variables without using concatenation
const userName = "Ram";
const age = 25;
console.log(`My name is ${userName} and I am ${age} years old.`);
Tasks -
What are guard clauses ?
&& is used. If first value is true , it will return the second expression. Otherwise it will return false.
const isLoggedIn = true;
isLoggedIn && console.log("YOu are logged in");
Tasks -
What are Default Value pattern or fallback ?
|| is used. If left side is true then the same left side is used and if it is false, then only right side is used.
let name = "Ram";
const userName = name || "Krishna";
console.log(userName);
Tasks-
We can also use multiline string in template string
const words = `Hello
sdafsdafsda
sdafsdafsda
sdafsdafasd`;
console.log(words);
String Index
Starts with zero.
const word = "hello";
console.log(word[1]);
String slicing
str.slice(startIndex, endIndex);
//note - startIndex is included while endIndex is excluded
endIndex is optional and if it is not put, then the slicing occurs till last.
Negative index means counting from last. eg. str.slice(-6,-3);
Some Useful String methods
Finding length of string - string.length
toUpperCase() or toLowerCase()
string.includes(”find”)
string.startsWith() endsWith()
.trim()
.split(”,”)
.replace(”whatNeedsToBeReplaced”,”WhatNeedsToBePut”)
charAt(index)
Create arrow function orderSummary that takes product, qty, and price and returns:
"You bought {qty} {product} for Rs. {qty * price}."
Create arrow function meetingNotice that takes topic, date, duration and returns:
"Meeting on {topic} is scheduled for {date} and will last {duration} hours."
Create arrow function ageMessage that takes personName, birthYear, and currentYear and returns:
"{personName} is {currentYear - birthYear} years old."
Create arrow function studentStatus that takes name, age, school, and hasGraduated and returns:
"{name} is {age} years old and studies at {school}."
If hasGraduated is true, add " {name} graduated from {school}." (use ternary or &&).
canDrive that takes age and logs "You can drive" only if age >= 18.greetUser that logs "Good evening" only if isUserLoggedIn is true.showDiscount that takes totalAmount and logs "10% discount applied" only if totalAmount > 5000.showAccess that logs "Access granted" only if both isLoggedIn and hasAccessRights are true.sendNotification that logs "Notification sent" only if isVerified is true and email equals "[email protected]".getLanguage that takes language and returns it or "English" if falsy.getBackgroundColor that returns userColor or defaultColor or "white".getStatusMessage that returns message or "No new notifications" if empty.getDescription that returns shortDesc || longDesc || "No description available".getPriorityColor that returns primaryColor || secondaryColor || tertiaryColor || "black".secondChar that returns the second character of a string.removeFirstChar that removes the first character of a string.removeLastChar that removes the last character of a string.sliceMiddle that returns characters from index 1 to 4 of a string.sliceLastThree that returns last 3 characters of a string (using negative index).getLength that returns length of the string.toLowerCaseStr that converts string to lowercase.toUpperCaseStr that converts string to uppercase.includesWord that returns true if string includes given word.startsWithLetter that returns true if string starts with given letter.endsWithLetter that returns true if string ends with given letter.trimSpaces that trims leading and trailing spaces.splitByComma that splits a string by commas and returns array.replaceWord that replaces first occurrence of a word with another word.charAtIndex that returns character at given index.isValidName that returns true if trimmed name length > 0.countWords that counts number of words in a string (split by space).capitalizeFirstChar that capitalizes only the first character of string.isEmail that returns true if string includes "@".getFirstWord that returns the first word from a sentence.lastCharToUpper that returns last character in uppercase.replaceSpacesWithDash that replaces all spaces with .startsWithHello that returns true if string starts with "Hello".endsWithDot that returns true if string ends with ".".multiLineMessage that returns a 3-line multiline string using template literals.inviteMessage that takes event and date and returns multiline invite message:pgsql
CopyEdit
You are invited to {event}
Date: {date}
Please join us online.