JS Variable Keywords - kimschles/schlesinger-knowledge GitHub Wiki
const
, let
, var
Resources
Variables
- Variables provide developers a way to store a value
- Once a variable is declared, the name of the variable is called an identifier
- For example,
const name = 'kim';
`name is the identifier - In JavaScript, variable identifiers can contain the letters (
a-z
), numbers (0-9
), underscores (_
) and the dollar sign ($
)
Explanations and Use Cases
const
- Used when the value of the variable will stay the same
- Throws an error if there is an attempt at updating the value
- Block scope: can see/has access to only what is inside the curly braces. Can be a function, loop or conditional
- Need to be declared and initialized at the same time because you cannot reassign a value
ALL_CAPS
orlowercase
? Application level constants yes, not when you use const for declaring immutable variables in function scope.- Use
const
as often as possible to minizimize mutable state
Example:
const API_URL = asdlkfjasldkfjasdf.com/v1/plants;
function filterData(){
const result = {};
// code here
return resut;
}
let
- Used when the value of the variable will be reassigned
- Most commonly used in
for
loops - Block scope: can see/access what is inside the curly braces. can be a function, loop or conditional.
var
- In
ES5
and prior versions of ECMAScript,var
was the only variable declaration keyword - Avoid
var
- When is
var
used in ES6? - function scope: can see/has access to anything within the curly braces of a function