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_CAPSorlowercase? Application level constants yes, not when you use const for declaring immutable variables in function scope.- Use
constas 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
forloops - Block scope: can see/access what is inside the curly braces. can be a function, loop or conditional.
var
- In
ES5and prior versions of ECMAScript,varwas the only variable declaration keyword - Avoid
var - When is
varused in ES6? - function scope: can see/has access to anything within the curly braces of a function