Interview Series — JavaScript Fundamentals for Test Automation
Q1. What is the difference between slice() and substring() in JavaScript?
Both slice() and substring() are used to extract part of a string. At first, they look like they work the same — but they behave differently when negative values or reversed start–end values are involved.
Let’s use one example string:
let str = "Playwright";
Basic Extraction
console.log(str.slice(0, 4)); // "Play"
console.log(str.substring(0, 4)); // "Play"
In normal cases, both give the same output.
Key Difference 1: Handling Negative Indices
console.log(str.slice(-5)); // "right"
console.log(str.substring(-5)); // "Playwright"
| Behavior | Result |
|---|---|
slice(-5) → Counts from end |
✅ Returns "right"
|
substring(-5) → Converts -5 to 0
|
❌ Returns entire string |
So:
-
slice()understands negative indexing -
substring()ignores negative indexing
Key Difference 2: If Start > End
console.log(str.slice(5, 2)); // "" (empty string)
console.log(str.substring(5, 2)); // "ayw"
| Method | Behavior |
|---|---|
slice() returns empty when start > end |
Keeps order exactly |
substring() automatically swaps the values
|
Makes it work anyway |
Comparison Table
| Feature | slice(start, end) |
substring(start, end) |
|---|---|---|
| Negative index support | ✅ Yes (counts from end) | ❌ No (converted to 0) |
| If start > end | ❌ Returns empty | ✅ Automatically swaps values |
| Works on | Strings + Arrays | Strings only |
| Best Use | Flexible slicing | Safe string extraction when values are uncertain |
Internal Explanation (Simple Words)
- slice() adjusts negative index by adding it to string length.
- substring() treats any negative value as 0, and auto-reorders parameters.
This is why:
str.slice(-5) → last 5 chars
str.substring(-5) → treats -5 as 0 → returns whole string
How to Answer in an Interview (Simple Version)
“
slice()supports negative indexing and keeps start/end order.substring()does not support negative indexing and swaps start and end if needed.
Soslice()is more flexible, whilesubstring()is safer for simple extractions.”
Real QA Usage (Why Testers Should Know This)
When parsing API responses, log messages, or dynamic text:
- Use slice() when taking values from end of string
- Use substring() when taking values from beginning range safely
Example: Extract last 4 digits of an ID:
id.slice(-4);
Related Interview Follow-Up Questions (Highly Asked)
- What is the difference between
slice()andsplice()? - How is
substr()different fromslice()? Why issubstr()deprecated? - How do you reverse a string without using built-in reverse() method?
- How do you extract numbers from a string?
- What happens if
slice()receives floating number arguments?
Quick Summary (Easy to Remember)
| Ask Yourself | Which One to Use |
|---|---|
| Need to slice from the end? | ✅ Use slice()
|
| Index values might be reversed? | ✅ Use substring()
|
| Working with arrays? | ✅ Use slice()
|
| Simple safe string cut? | ✅ Use substring()
|
