We've covered several introductory concepts for JavaScript programming in this course and how to debug your code. We'll review some coding guidelines and best practices you'll use as a JavaScript developer to ensure consistency, readability, security, and accessibility. Read this article to learn about some of the best practices for developing programs.
Variables
Variable naming
For variable names use lowerCamelCasing, and use concise, human-readable, semantic names where appropriate.
Do this:
let playerScore = 0; let speed = distance / time;
Not this:
let thisIsaveryLONGVariableThatRecordsPlayerscore345654 = 0; let s = d/t;
Note: The only place where it is OK to not use human-readable semantic names is where a very common recognized convention exists, such as using i
, j
, etc. for loop iterators.
Declaring variables
When declaring variables and constants, use the let
and const
keywords, not
var
.
If a variable will not be reassigned, prefer const
:
const myName = 'Chris'; console.log(myName);
Otherwise, use let
:
let myAge = '40'; myAge++; console.log('Happy birthday!');
This example uses let
where it should prefer const
. It will work but should be avoided in MDN code examples:
let myName = 'Chris'; console.log(myName);
This example uses const for a variable that gets reassigned. The reassignment will throw an error:
const myAge = '40'; myAge++; console.log('Happy birthday!');
This example uses var
, which should be avoided in MDN code examples unless it is really needed:
var myAge = '40'; var myName = 'Chris';