With statement¶
ID: js/with-statementKind: problemSecurity severity: Severity: warningPrecision: very-highTags: - quality - maintainability - complexity - language-featuresQuery suites: - javascript-security-and-quality.qls
Click to see the query in the CodeQL repository
Thewith statement provides a shorthand when accessing many properties of the same object. If a property is not found on that object, enclosing scopes are searched for a variable of the same name. This is confusing and makes code brittle and hard to read. For this reason,with is best avoided.
Recommendation¶
Eliminatewith statements by introducing explicit property accesses.
Example¶
The following code snippet reads propertiesfirstName,lastName andemail from the object stored inrecord by means of awith statement. It also invokes theaddRecord function, which is presumably defined in an enclosing scope.
functionprocess(record){with(record){addRecord(firstName+" "+lastName,email);}}
Note that ifrecord does not have any of the propertiesfirstName,lastName oremail, they will be looked up as variables in enclosing scopes. Conversely, if it should happen to have a propertyaddRecord, the function call will attempt to invoke the value of this property as a method.
To clarify the intended meaning of the code, thewith statement should be removed and property accesses should be introduced to make it explicit which names are intended to be read fromrecord, and which ones are intended to be looked up in enclosing scopes:
functionprocess(record){addRecord(record.firstName+" "+record.lastName,record.email);}
Note thatwith statements are not allowed in strict mode code.
References¶
D. Crockford,#"https://twitter.com/github" title="GitHub on Twitter">