javascript · level 3 · unit 7 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Professionals let tools catch mistakes before code even runs.
Real projects lean on tools. A such as ESLint reads code without running it and flags slips like == or unused variables. A such as Prettier fixes the layout automatically, so reviews can focus on ideas, not spaces.
Code you install with npm is a , listed in package.json with versions in : major.minor.patch. The range ^1.4.0 accepts any later 1.x version but never 2.0.0, because a new major number means things may break. Below is a tiny linter of your own.
const source = ["var total = 0;", "if (total == 0) { total = 1; }", "const done = true;"];
const rules = [
{ name: "no-var", broken: (line) => line.includes("var ") },
{ name: "eqeqeq", broken: (line) => line.includes(" == ") }
];
for (let i = 0; i < source.length; i++) {
for (const rule of rules) {
if (rule.broken(source[i])) { console.log(`line ${i + 1}: ${rule.name}`); }
}
}
console.log("Lint finished"); Real linters understand the structure of code, not only its text, so they never mistake a string for code.
guess first
Which updates does ^1.4.0 allow? What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
function allowsCaret(base, next) {
if (next.major !== base.major) { return false; }
if (next.minor !== base.minor) { return next.minor > base.minor; }
return next.patch >= base.patch;
}
const base = { major: 1, minor: 4, patch: 0 };
console.log(allowsCaret(base, { major: 1, minor: 9, patch: 2 }));
console.log(allowsCaret(base, { major: 2, minor: 0, patch: 0 }));
console.log(allowsCaret(base, { major: 1, minor: 3, patch: 9 }));
your turn
Your turn. Write a lint rule.
Invent a second rule: give it a name, like no-alert, and the text it should hunt for, like alert(. Make sure it flags at least one line.
fix it
The package file will not load. Can you fix it?
- JavaScript forgives a comma after the last item. Is JSON as forgiving?
- JSON forbids a comma after the last item in an object, and
package.jsonis JSON. - Remove the comma after
"^5.3.0"and the one after the closing curly bracket on line 4.
nailed it
you know the tools professionals reach for. :D
- Linters warn about mistakes before your code ever runs.
- Formatters keep the layout of every file the same.
- Semantic versions: major breaks, minor adds, patch fixes.
new words in your collection
- linter
- formatter
- dependency
- semantic versioning
This lesson isn’t saved. A free account remembers every lesson you finish.