The const
and let
declarations are a more advanced concept.
The var
declaration defines a variable within function scope. Everywhere within the function can see that variable. If you’re not inside of a function then it defines it within global scope instead.
The const
declaration defines a variable within block scope, where it can’t be seen outside of the block that it was defined. Also as it’s a constant, primitive types (such as number or string) can’t be changed, which is a good thing for reliability and is also good for the JavaScript interpreter. If the constant is an array or an object, its contents can still be changed.
The let
declaration also defines a variable within block scope, but it’s contents can change. It’s usually best to avoid the let
statement because that’s like saying “Warning! This will change soon!”, so the code that you had before is more appropriately written with a const declaration instead of the let one.
const logSkyColor = () => {
const color = "blue";
console.log(color); // blue
};
However, arrow notation is also usually best reserved for when using single liners, with more complex functions being defined using normal function notation instead.
When dealing with multiple statements, use a function declaration.
function logSkyColor () {
const color = "blue";
console.log(color); // blue
}
That variable assignment doesn’t need to be there with such a simple function.
function logSkyColor () {
console.log("blue");
}
And because there’s just one statement in the function, that’s a good time to use arrow-notation instead.
const logSkyColor = () => console.log("blue");