In my project (browser context only) I want to use a JS code quality tool. I've tried both jslint
and eslint
. I want linter to help me make my code clean, clear, errorproof and improve its overall quality. What I don't want to do is I don't want to write some dirty hacks or use bad practices just to make linters happy.
I'm concerned about only one issue. Both of them reported a problem that I'm using a function before it was defined. Obviously in the following code snippet bar
won't be called before it's definition.
function foo() {
bar();
}
function bar() {
}
foo();
In this simplest scenario I can just move bar
before foo
. But there are cases when it's just impossible. First function uses the second, the second uses the third and the third uses the first.
It seems like I can make linters happy by declaring all functions before their definitions like this.
var foo;
var bar;
foo = function() {
bar();
};
bar = function() {
};
foo();
The questions are:
yes
I should stick to this practice, shouldn't I?no
what is the good practice regarding this issue?A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses (). Function names can contain letters, digits, underscores, and dollar signs (same rules as variables). The parentheses may include parameter names separated by commas: (parameter1, parameter2, ...)
There are 3 ways of writing a function in JavaScript: Function Declaration. Function Expression. Arrow Function.
A technical definition of a function is: a relation from a set of inputs to a set of possible outputs where each input is related to exactly one output.
We can create functions in JavaScript using the keyword function. Syntax: The basic syntax to create a function in JavaScript is shown below. To create a function in JavaScript, we have to first use the keyword function, separated by name of the function and parameters within parenthesis.
No, the snippets are not broken but not best practice either.
var foo = function(){
}
var bar = function(){
foo();
}
bar();
will actually become:
var foo, bar;
foo = function(){
}
bar = function(){
foo();
}
bar();
Hence you should define all variables and functions at the beginning of the scope. JavaScript uses Hoisting
which effectively moves all declarations for variables and functions to the top of the scope.
Doing it yourself is considered best practice and increases readability.
Eslint will check against the rule vars-on-top which is defined and documented here
https://www.reddit.com/r/learnjavascript/comments/3cq24a/crockford_says_hoisted_variable_declarations_are/ https://www.sitepoint.com/demystifying-javascript-variable-scope-hoisting/
Use strict mode always. "use strict"
have you functions inside scope like IIFE for not having global's variables
read more about IIFE
function foo() {
bar();
};
function bar() {
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With