patternjavascriptModerate
poh-tay-toh poh-tah-toh, does writing the same code a different way affect readability?
Viewed 0 times
pohsamethereadabilitywritingwayaffectdifferenttaytah
Problem
I have a particular if statement that could be written in different ways, and I'm curious as to whether there's any significant difference in readability that I should prefer one over the other:
The flow can be boiled down to
Some different ways of writing the
The flow can be boiled down to
if string does not begin with '_'
do stuff
else
throw errorSome different ways of writing the
if condition:str[0] !== '_'
str.indexOf('_')
!/^_/.test(str)
/^[^_]/.test(str)Solution
I think the first is the simplest and the most readable one from the list but I'd prefer the
Furthermore, I'd reverse the condition:
Reference:
charAt function:x.charAt(0) !== '_'Furthermore, I'd reverse the condition:
if string begins with '_' {
throw error
}
do stuffReference:
- How to get first character of string?
- Flattening Arrow Code
Code Snippets
x.charAt(0) !== '_'if string begins with '_' {
throw error
}
do stuffContext
StackExchange Code Review Q#12352, answer score: 12
Revisions (0)
No revisions yet.