All 'var' declarations must be at the top of the function scope
13 .withCapabilities(webdriver.Capabilities.chrome())
14 .build();
15 driver.get('http://www.google.com');
16 var searchBox = driver.findElement(webdriver.By.name('q'));17 searchBox.sendKeys('selenium node automation');
18 searchBox.getAttribute('value').then(function (value) {
19 assert.equal(value, 'selenium node automation');
Description
Declare variables at the top of their scope as it improves code readability, performance and also helps in code navigation.
The vars-on-top
rule generates warnings when variable declarations are not used serially at the top of a function scope or the top of a program. By default variable declarations are always moved (“hoisted”) invisibly to the top of their containing scope by the JavaScript interpreter. This rule forces the programmer to represent that behavior by manually moving the variable declaration to the top of its containing scope.
Bad Practice
// Variable declarations in a block:
function doSomething() {
var first;
if (true) {
first = true;
}
var second;
}
// Variable declaration in for initializer:
function doSomething() {
for (var i=0; i<10; i++) {}
}
Recommended
function doSomething() {
var first;
var second; //multiple declarations are allowed at the top
if (true) {
first = true;
}
}
function doSomething() {
var i;
for (i=0; i<10; i++) {}
}