What is the difference between substring and substr methods?
Assesses fundamental understanding of JavaScript conventions, runtime behavior, and memory/performance considerations.
Hiring managers look for precision, avoidance of ambiguous jargon, and ability to explain trade-offs under real production conditions.
Both substring and substr are used to extract parts of a string, but there are subtle differences between the substring() and substr() methods in terms of syntax and behavior.
substring(start, end)
- Parameters:
start: The index to start extracting (inclusive).end: The index to stop extracting (exclusive).- Behavior:
- If
start > end, it swaps the arguments. - Negative values are treated as
0.
let str = "Hello World";
console.log(str.substring(0, 5)); // "Hello"
console.log(str.substring(5, 0)); // "Hello" (swapped)
console.log(str.substring(-3, 4)); // "Hell" (negative = 0)
substr(start, length)_(Deprecated)_
- Parameters:
start: The index to start extracting.length: The number of characters to extract.- Behavior:
- If
startis negative, it counts from the end of the string. - If
lengthis omitted, it extracts to the end of the string.
let str = "Hello World"; console.log(str.substr(0, 5)); // "Hello"
console.log(str.substr(-5, 3)); // "Wor" (starts from 'W')`
Note: substr() is considered a legacy feature in ECMAScript, so it is best to avoid using it if possible.
Candidate Response Strategy & Interview Tips
- Start with a concise one-sentence summary: Deliver a direct, confident answer first before expanding into nuances.
- Demonstrate real-world trade-offs: Discuss where this approach excels and when you would avoid it in production systems.
- Discuss complexity & edge cases: Proactively explain time/space complexity or boundary conditions (null values, scale limits).
- Prepare for interviewer follow-ups: Technical hiring panels frequently probe deeper into concurrency, backward compatibility, or alternative libraries.