Loading lesson path
Avoid global variables, avoid new, avoid ==, avoid eval()
Minimize the use of global variables.This includes all data types, objects, and functions. Global variables and functions can be overwritten by other scripts. Use local variables instead, and learn how to use closures.
All variables used in a function should be declared as local variables.
Local variables must be declared with the var, the let, or the const keyword, otherwise they will become global variables.Strict mode does not allow undeclared variables.
It is a good coding practice to put all declarations at the top of each script or function.
Provide a single place to look for local variables Make it easier to avoid unwanted (implied) global variables
// 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 goes for loop variables:
for (let i = 0; i < 5; i++)
{It is a good coding practice to initialize variables when you declare them.
// Declare and initiate at the beginning let firstName = "";
let lastName = "";
let price = 0;
let discount = 0;
let fullPrice = 0, const myArray = [];
const myObject = {};
Initializing variables provides an idea of the intended use (and intended data type).If you re-declare a JavaScript variable declared with var, it will not lose its value.
The variable carName will still have the value "Volvo" after the execution of these statements:Example (
var carName = "Volvo";
var carName;
You cannot re-declare a variable declared with let or const.let carName = "Volvo";
let carName;const carName = "Volvo";
const carName;Declaring objects with const will prevent any accidental change of 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 possibleDeclaring arrays with const will prevent any accidential change of type:
let cars = ["Saab", "Volvo", "BMW"];
cars = 3; // Changes array to number const cars = ["Saab", "Volvo", "BMW"];
cars = 3; // Not possible"" instead of new String()