You can run the
For example, if you create a variable called first, then start a new line without closing it with a semi-colon, the semi-colon will be inserted after the line break, just before the declaration of your second variable. This causes your first variable to be assigned the value "undefined" instead of the value you intended, whilst the second variable becomes a global variable.
Make sure you always use the strict equality operator (===) instead of the less strict equality operator (==).
If you compare the string '1' with the number 1 using ==, the result is true. If you compare the number 1 with the string '1.0', then the result is also true. However, if you compare the string '1' with the string '1.0' then the result is false.
If you try to compare two values of different types (string and number), the == operator will perform a type conversion first before converting them. If you are comparing two values of the same type (number and number), then the == will do a direct comparison, so '1' is not equal to '1.0'.
So, only use the == operator if you specifically want to do type conversions before checking for equality. Do the same for the != and !== operators.
Make sure you always declare varibles using let or const. If you don't declare variables inside of a function (you assign a value to a name without a declaration), then that variable will become a global variable automatically.
Use strict mode to avoid most of these traps.
'use strict';. It doesn't tolerate undeclared variables. You can use this directive at the top of your file to make your whole file run in strict mode, or inside a function to make only the function run in strict mode. This is useful when you are refactoring legacy code, where using strict mode at the top could overwhelm you with error messages. This way, you can refactor one function at a time.
Setting up eslint
npm install eslint --savedev
npx eslint --init
npm eslint yourfile.js
Const and Let
Only use const and let, never var.
A constant variable is a read-only variable.
A let variable can't be redeclared, but it's value can be modified.
Use Object.freeze(); to make objects immutable (like const variables can't be changed). However, if an object's property refers to another object, the nested object is not frozen by the freeze method.
- Always add semi-colons to the end of your statements.
- Favor the strict equality operator (===, !==) over the type conversion equality operator (!=, ==).
- As a general rule, add the 'use strict' directive to the top of your script.
- Use ESLint to catch standard-compliance errors. Install locally to your project with: npm install eslint --savedev
- Only use const and let, never var or undeclared variables.
- Use Object.freeze(); to make objects immutable (like const variables can't be changed).
- However, if an object's property refers to another object, the nested object is not frozen by the freeze method.