Line Breaking in JavaScript

Question
What should you do when a line of code exceeds the max character length of 80?

Answer
You want to break (split) the line into two. The recommended best practice is to break after an operator and indent the next line two levels.

Comments
It’s important to break the line after an operator because JavaScript’s built-in automatic semicolon insertion mechanism won’t close the statement. Be sure to use the same line-breaking pattern for statements as well. There is an exception to the rule. When assigning a value to a variable, wrap lines directly under the first part of the assignment. See the examples below.

Examples

// Correct. Break after an operator and indent two levels.
doWork(argumentOne, argumentTwo, argumentThree, argumentFour, argumentFive, 
        argumentSix);

// Incorrect. Break before operator and indent only one level.
doWork(argumentOne, argumentTwo, argumentThree, argumentFour, argumentFive
    , argumentSix);

// Exception. Assigning a value to a variable.
let result = aValue + anotherValue + anAdditionalValue + yetAnotherValue + 
             someOtherValue;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s