tezvyn:

Why use path.join over string concatenation

AI-drafted, machine-checkedSource: interviewbeginner
WHAT IT TESTS

awareness of cross-platform path handling.

OUTLINE

path.join uses the correct OS separator, collapses duplicate slashes, normalizes . and .. segments.

RED FLAG

hardcoding forward slashes and assuming concatenation always works.

WHAT THIS TESTS This probes whether you understand cross-platform portability and the subtle bugs that arise from building paths by hand. It separates people who have shipped code across operating systems from those who only test on one.

A GOOD ANSWER COVERS path.join takes path segments and joins them with the separator appropriate for the current platform: a forward slash on Linux and macOS, a backslash on Windows. It also normalizes the result, collapsing repeated separators and resolving interior . and .. segments. String concatenation does none of this. If you write base + '/uploads/images/profile.jpg' and base already ends with a slash, you get a double slash; on Windows the forward slashes may be inconsistent with the native separator. path.join handles all these edge cases so the same code runs correctly everywhere.

COMMON WRONG ANSWERS Claiming concatenation is fine because modern filesystems accept forward slashes everywhere, which ignores Windows quirks and double-separator bugs. Another weak answer is confusing path.join with path.resolve, which behaves differently when given absolute segments.

LIKELY FOLLOW-UPS How does path.join differ from path.resolve. How do you safely prevent directory traversal attacks when joining user input. What does __dirname give you and why use it as the base.

ONE CONCRETE EXAMPLE Given base = '/var/data/' and you concatenate base + '/uploads/profile.jpg', you produce '/var/data//uploads/profile.jpg' with a double slash. path.join(base, 'uploads', 'profile.jpg') yields the clean '/var/data/uploads/profile.jpg' on POSIX and the correct backslash form on Windows, with no duplicate separators.

Read the original → nodejs.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.