HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptModerate

poh-tay-toh poh-tah-toh, does writing the same code a different way affect readability?

Submitted by: @import:stackexchange-codereview··
0
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

if string does not begin with '_'
    do stuff
else
    throw error


Some 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 charAt function:

x.charAt(0) !== '_'


Furthermore, I'd reverse the condition:

if string begins with '_' {
    throw error
}
do stuff


Reference:

  • How to get first character of string?



  • Flattening Arrow Code

Code Snippets

x.charAt(0) !== '_'
if string begins with '_' {
    throw error
}
do stuff

Context

StackExchange Code Review Q#12352, answer score: 12

Revisions (0)

No revisions yet.