Strings and Text Operations
Strings and Text Operations
Strings are immutable text values. trim returns a new string rather than editing the original name, so a school input can be normalized before checking whether it is empty.
Before this topic, review Run Once with do...while if its terms are unfamiliar.
What you’ll learn
- Explain strings and text operations through the school example.
- Trace the shown operations and distinguish their result from displayed output.
- Make the practice change and explain its consequence: The longer name is trimmed into a new value while the original spaced input keeps its length.
Work through the school example
This is JavaScript using language features and the host console. Read the initial values, then follow each operation to its displayed result. A declaration names a value, a function call performs an operation, and console.log displays its arguments.
JavaScript · school.js · complete example
const input = " Diya ";
const name = input.trim();
console.log(name);
console.log(input.length);
Expected output
Diya
6Run in JavaScript compiler →Recognize the important boundary
String length counts UTF-16 code units, not always visible characters. Case conversion and comparison require care with real names and locales.
Try a small variation
JavaScript · original source for practice
const input = " Diya ";
const name = input.trim();
console.log(name);
console.log(input.length);
Your task: Replace Diya with Saira . Predict the result before running the edited program.
The source is repeated here. If the edit targets the HTML rather than the script, use the markup repeated below; the worked answer also repeats the changed markup.
Worked answer and reasoning
The longer name is trimmed into a new value while the original spaced input keeps its length.
JavaScript · complete worked variation
const input = " Saira ";
const name = input.trim();
console.log(name);
console.log(input.length);
Expected output
Saira
7Run in JavaScript compiler →Predict the original program
JavaScript · original program for this question
const input = " Diya ";
const name = input.trim();
console.log(name);
console.log(input.length);
Keep the useful idea
Strings are immutable text values. trim returns a new string rather than editing the original name, so a school input can be normalized before checking whether it is empty.
Check your variation against this explanation: The longer name is trimmed into a new value while the original spaced input keeps its length.
Use the JavaScript array reference library for individual array operations and boundary tests to check a rule independently.
Reaching the recap and completing the quizzes are separate milestones.