Reading — step 1 of 5
Learn
Strings
Text in TypeScript is the string primitive: an immutable sequence of characters with the same rich method set as JavaScript. One type note up front: always write lowercase string in annotations. The capitalized String is the legacy wrapper object — almost never what you want.
Three quoting styles
const single = 'hello';
const double = "hello";
const tick = `hello`;
Single and double quotes are interchangeable — pick one and be consistent. Backticks create template literals, which have two superpowers: interpolation and multi-line text.
const name: string = "Alice";
const age: number = 30;
console.log(`${name} is ${age} years old`); // Alice is 30 years old
Anything inside the braces is a real expression, and TypeScript type-checks it like any other code.
The everyday methods
const s: string = "hello, world";
s.length; // 12 — a property, not a method (no parentheses)
s.toUpperCase(); // "HELLO, WORLD"
s.includes("world"); // true
s.slice(0, 5); // "hello"
s.split(", "); // ["hello", "world"]
s.replace("world", "TS"); // "hello, TS"
s[0]; // "h" — indexing works
The trap: strings are immutable
No string method ever changes the string in place — every method returns a NEW string:
let s = "hello";
s.toUpperCase();
console.log(s); // still "hello" — the result was thrown away!
s = s.toUpperCase();
console.log(s); // "HELLO" — you must keep the return value
There is also no s.reverse() — arrays can reverse themselves, strings cannot.
The reverse idiom
Since a string cannot reverse itself, hop through an array and back:
const reversed = s.split('').reverse().join('');
Step by step:
split('')explodes the string into an array of one-character strings (string[]).reverse()reverses that array in place.join('')glues the characters back together with no separator.
(A caveat for later: split('') cuts along UTF-16 code units, so emoji and some non-Latin characters get mangled. For plain ASCII text — like this exercise — it is exactly right.)
Your exercise
The starter reads one full line from stdin:
const word: string = require('fs').readFileSync(0, 'utf-8').trim();
Print that line reversed, using the split/reverse/join idiom.
Watch out for the hidden test: the input line can contain a space — hello world must become dlrow olleh. The exact mistake the grader will catch is reversing the words instead of the characters: splitting on ' ' and reversing gives world hello, which fails. Reverse every character of the entire line, spaces included, and print only the result.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…