# no-unexpected-multiline

Disallow confusing newlines in expressions.

JavaScript has automatic semicolon insertion, where newlines end statements, however, expressions can often span across newlines, therefore it can become a bit confusing at times and ambiguous. Take the following as an example:

let foo = bar
/bar/g.test("foo");

you would expect this to be a variable declaration and then a regex test, however, it is actually a division expression as such: `(bar / bar) / (g.test("foo")). This rule is aimed at preventing ambiguous and buggy expressions such like these. It disallows ambiguous tagged templates, property accesses, function calls, and division expressions.

# Invalid Code Examples

var foo = bar
(1 || 2).baz();
var foo = 'bar'
[1, 2, 3].forEach(addNumber);
let x = function() {}
`foo`
let x = function() {}
x
`bar`
let x = foo
/regex/g.test(bar)

# Correct Code Examples

var foo = bar;
(1 || 2).baz();
var foo = 'bar';
[1, 2, 3].forEach(addNumber);
let x = function() {};
`foo`
let x = function() {};
x;
`bar`
let x = foo;
/regex/g.test(bar)
More incorrect examples
var a = b
(x || y).doSomething()
var a = (a || b)
(x || y).doSomething()
var a = (a || b)
(x).doSomething()
var a = b
[a, b, c].forEach(doSomething)
var a = b
(x || y).doSomething()
var a = b
[a, b, c].forEach(doSomething)
let x = function() {}
`hello`
let x = function() {}
x
`hello`
x
.y
z
`Invalid Test Case`
foo
/ bar /gym
foo
/ bar /g
foo
/ bar /g.test(baz)
More correct examples
(x || y).aFunction()
[a, b, c].forEach(doSomething)
var a = b;
(x || y).doSomething()
var a = b
;(x || y).doSomething()
var a = b
void (x || y).doSomething()
var a = b;
[1, 2, 3].forEach(console.log)
var a = b
void [1, 2, 3].forEach(console.log)
"abc
(123)"
var a = (
(123)
)
f(
(x)
)
(
function () {}
)[1]
let x = function() {};
`hello`
let x = function() {}
x `hello`
String.raw `Hi
${2+3}!`;
x
.y
z `Valid Test Case`
f(x
)`Valid Test Case`
x.
y `Valid Test Case`
(x
)`Valid Test Case`
foo
/ bar /2
foo
/ bar / mgy
foo
/ bar /
gym
foo
/ bar
/ ygm
foo
/ bar /GYM
foo
/ bar / baz
foo /bar/g
foo
/denominator/
2
foo
/ /abc/
5 / (5
/ 5)
var a = b
?.(x || y).doSomething()
var a = b
?.[a, b, c].forEach(doSomething)

Source (opens new window)

Last Updated: 11/18/2020, 9:36:33 PM