Module 2: Language Fundamentals
Strings and Template Literals
Combine strings, access characters, and use common string methods safely.
Strings are immutable sequences of characters. Operations such as toUpperCase return a new string rather than changing the original.
const language = "JavaScript";
console.log(language.length); // 10
console.log(language.toLowerCase()); // "javascript"
console.log(language.includes("Script")); // true
console.log(language.slice(0, 4)); // "Java"
String indexing uses UTF-16 code units, not necessarily user-perceived characters. For most introductory tasks, indexing and slice are convenient; applications that process complex international text may need to consider Unicode code points and grapheme clusters.
Template literals#
Backticks allow interpolation and multi-line strings:
const learner = "Mina";
const lessons = 5;
const message = `${learner} completed ${lessons} lessons.`;
Template literals are not an HTML sanitizer. Avoid inserting untrusted values into innerHTML; use textContent for plain text or a trusted sanitization strategy when rendering markup is truly required.
Search and cleanup#
Useful methods include trim, includes, startsWith, endsWith, replace, split, slice, and substring. trim removes whitespace at the ends, while split can turn a string into an array.
const rawTags = " js, html, css ";
const tags = rawTags.split(",").map((tag) => tag.trim());
console.log(tags); // ["js", "html", "css"]
Practice#
Take a full name with extra spaces, clean it, and produce a greeting with a template literal.