let vs const vs var - mmedrano9438/peripheral-brain GitHub Wiki
- var declarations are globally scoped or function/locally scoped.
- if declared outside a function block then it is available for use in the whole window
- var is function scoped when it is declared within a function.
var tester = "hey hi"; //gloablly scoped
function newFunction() {
var hello = "hello";
//function scoped, not available outside this function
}
console.log(hello); // error: hello is not defined
-
var variables can be re-declared and updated: var greeter = "hey hi"; var greeter = "say Hello instead"; // or the following is also valid: var greeter = "hey hi"; greeter = "say Hello instead";
-
let is now preferred for variable declaration, it is block scoped.... variable declared in a block with let is only available for use within that block, and can be updated but not re-declared.
let greeting = "say Hi"; let times = 4;
if (times > 3) { let hello = "say Hello instead"; console.log(hello);// "say Hello instead" } console.log(hello) // hello is not defined
////can be updated but not redeclared; let greeting = "say Hi"; let greeting = "say Hello instead"; // error: Identifier 'greeting' has already been declared
////same variable is defined in different scopes, there will be no error: let greeting = "say Hi"; if (true) { let greeting = "say Hello instead"; console.log(greeting); // "say Hello instead" } console.log(greeting); // "say Hi"
Const Variables declared with the const maintain constant values, can only be accessed within the block they were declared, It cannot be updated or re-declared. For example -->
do this... const greeting = { message: "say Hi", times: 4 }
but cant do this.... greeting = { words: "Hello", number: "five" } // error: Assignment to constant variable.
but you can do this without returning errors.... greeting.message = "say Hello instead";