1. 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 -

    1. You bought 5kg of mangoes at rate of Rs. 150 per kg. Then show it in format - You bought 5 kg mangoes with total price Rs. 750 while price per kg is Rs. 150. Show fruit, kg, rate and total price as variables in template string.
    2. event - React Class, Starting date - 5th August, mode - Online zoom, time 2 hours. You need to show it in format. You are invited to the {event} which starts from {starting date}. It will be {mode} class {time} daily.
    3. name - Ram, birthYear = 1995, currentYear = 2025. Show it in format - Ram is 30 yrs old.
    4. name = Hari, age = 20, college = Trinity, isGraduated = true/false. Print - Hari is 20 yrs old and studies at Trinity college. (If isGraduated is true) Hari graduated from Trinity college. (note - Either use ternary or use && operator - this concept is vary useful in react).

    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 -

    1. Use && operator to show You can vote only if you are more than or equal to 18 yrs old.
    2. Make a simple function to greet a person like Good Morning. Then run the function only if the user is logged in using &&. (Hint - You can create variable named isLoggedIn.)
    3. Calculate discount and display it only if the total purchase is more than Rs. 3000. Lets say 10% discount.
    4. Create two variables isLoggedIn and isPremiumUser and if both are true then only show - Welcome to Premium Content. (hint - use && twice).
    5. Send email if user isVerified as well as his email is [email protected]. Then send him email saying - You are a verified user Ram.

    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-

    1. If country is selected then its fine, if not show the default country Nepal.
    2. Create a variable named selectedTheme and whether it is assigned or not, give default value of light theme.
    3. If message is not empty return the message while if message is empty return No new messages.
    4. Imagine a product has Short Description and Long description. Try to show short as far as possible than long. If by chance both are not available then display No Description Available. (Hint - use two ||)
    5. Lets say there are three variables called userColor, savedColor and systemDefault as white. Now our first priority is userColor, if not savedColor and at last systemDefault.

    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)

HomeWorks

Template Literals & Basic Expressions (new examples)

  1. Create arrow function orderSummary that takes product, qty, and price and returns:

    "You bought {qty} {product} for Rs. {qty * price}."

  2. Create arrow function meetingNotice that takes topic, date, duration and returns:

    "Meeting on {topic} is scheduled for {date} and will last {duration} hours."

  3. Create arrow function ageMessage that takes personName, birthYear, and currentYear and returns:

    "{personName} is {currentYear - birthYear} years old."

  4. 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 &&).


Guard Clauses with && (new scenarios)

  1. Create arrow function canDrive that takes age and logs "You can drive" only if age >= 18.
  2. Create arrow function greetUser that logs "Good evening" only if isUserLoggedIn is true.
  3. Create arrow function showDiscount that takes totalAmount and logs "10% discount applied" only if totalAmount > 5000.
  4. Create arrow function showAccess that logs "Access granted" only if both isLoggedIn and hasAccessRights are true.
  5. Create arrow function sendNotification that logs "Notification sent" only if isVerified is true and email equals "[email protected]".

Default Values with || (new scenarios)

  1. Create arrow function getLanguage that takes language and returns it or "English" if falsy.
  2. Create arrow function getBackgroundColor that returns userColor or defaultColor or "white".
  3. Create arrow function getStatusMessage that returns message or "No new notifications" if empty.
  4. Create arrow function getDescription that returns shortDesc || longDesc || "No description available".
  5. Create arrow function getPriorityColor that returns primaryColor || secondaryColor || tertiaryColor || "black".

String Indexing & Slicing (fresh practice)

  1. Create arrow function secondChar that returns the second character of a string.
  2. Create arrow function removeFirstChar that removes the first character of a string.
  3. Create arrow function removeLastChar that removes the last character of a string.
  4. Create arrow function sliceMiddle that returns characters from index 1 to 4 of a string.
  5. Create arrow function sliceLastThree that returns last 3 characters of a string (using negative index).

String Methods (new uses)

  1. Create arrow function getLength that returns length of the string.
  2. Create arrow function toLowerCaseStr that converts string to lowercase.
  3. Create arrow function toUpperCaseStr that converts string to uppercase.
  4. Create arrow function includesWord that returns true if string includes given word.
  5. Create arrow function startsWithLetter that returns true if string starts with given letter.
  6. Create arrow function endsWithLetter that returns true if string ends with given letter.
  7. Create arrow function trimSpaces that trims leading and trailing spaces.
  8. Create arrow function splitByComma that splits a string by commas and returns array.
  9. Create arrow function replaceWord that replaces first occurrence of a word with another word.
  10. Create arrow function charAtIndex that returns character at given index.

Simple Combined Practice

  1. Create arrow function isValidName that returns true if trimmed name length > 0.
  2. Create arrow function countWords that counts number of words in a string (split by space).
  3. Create arrow function capitalizeFirstChar that capitalizes only the first character of string.
  4. Create arrow function isEmail that returns true if string includes "@".
  5. Create arrow function getFirstWord that returns the first word from a sentence.
  6. Create arrow function lastCharToUpper that returns last character in uppercase.
  7. Create arrow function replaceSpacesWithDash that replaces all spaces with .
  8. Create arrow function startsWithHello that returns true if string starts with "Hello".
  9. Create arrow function endsWithDot that returns true if string ends with ".".

Multiline & Template Literal Practice

  1. Create arrow function multiLineMessage that returns a 3-line multiline string using template literals.
  2. Create arrow function inviteMessage that takes event and date and returns multiline invite message:
pgsql
CopyEdit
You are invited to {event}
Date: {date}
Please join us online.