Avoid using global variables, the new keyword, ==, and eval().
Minimize the use of global variables, including data types, objects, and functions.
Global variables and functions can be overwritten by other scripts.
Instead, use local variables and leverage closures to manage scope effectively.
All variables used within a function should be declared as local variables.
Local variables must be declared using the var, let, or const keyword; otherwise, they will become global variables.
It is a good practice to place all declarations at the top of each script or function.
This approach will:
// Declare at the beginning let firstName, lastName, price, discount, fullPrice; // Use later firstName = “John”; lastName = “Doe”; price = 19.90; discount = 0.10; fullPrice = price – discount; |
This also applies to loop variables.
for (let i = 0; i < 5; i++) { |
It is good practice to initialize variables when declaring them.
This will:
// Declare and initiate at the beginning let firstName = “”; let lastName = “”; let price = 0; let discount = 0; let fullPrice = 0, const myArray = []; const myObject = {}; |
Declaring objects with const
prevents unintentional changes to their type.
let car = {type:“Fiat”, model:“500”, color:“white”}; car = “Fiat”; // Changes object to string |
const car = {type:“Fiat”, model:“500”, color:“white”}; car = “Fiat”; // Not possible |
Declaring arrays with const prevents accidental changes to their type.
let cars = [“Saab”, “Volvo”, “BMW”]; cars = 3; // Changes array to number |
const cars = [“Saab”, “Volvo”, “BMW”]; cars = 3; // Not possible |
let x1 = “”; // new primitive string let x2 = 0; // new primitive number let x3 = false; // new primitive boolean const x4 = {}; // new object const x5 = []; // new array object const x6 = /()/; // new regexp object const x7 = function(){}; // new function object |
JavaScript is loosely typed, meaning:
let x = “Hello”; // typeof x is a string x = 5; // changes typeof x to a number |
Be cautious, as numbers can unintentionally be converted to strings or result in NaN (Not a Number).
During mathematical operations, JavaScript may automatically convert numbers into strings.
let x = 5 + 7; // x.valueOf() is 12, typeof x is a number let x = 5 + “7”; // x.valueOf() is 57, typeof x is a string let x = “5” + 7; // x.valueOf() is 57, typeof x is a string let x = 5 – 7; // x.valueOf() is -2, typeof x is a number let x = 5 – “7”; // x.valueOf() is -2, typeof x is a number let x = “5” – 7; // x.valueOf() is -2, typeof x is a number let x = 5 – “x”; // x.valueOf() is NaN, typeof x is a number |
Subtracting one string from another does not produce an error, but instead returns NaN (Not a Number).
“Hello” – “Dolly” // returns NaN |