var ;
- You can declare the variable "var" globally or locally. The var variable has no block scope.
For example ;
function sayHello() {
hey = "Hello";
console.log(hey);
var hey;
// The definition of the variables happens when the function starts.
}
- var = i; It is a global variable, so after the for loop it is assigned a value of 5. It loops again with the variable 5 each time.
for (var i = 0; i < 5; i++) {
setTimeout(function () {
console.log(i);
}, 1000);
}
// Answer 5
- The var keyword does not return an error when re-declared.
var a = 0;
var a;
console.log(a); // 0
let ;
With ES6 we can declare a variable using the let keyword. It has similar properties to the var keyword.
Variables are declared using the let keyword are block-scoped, are not attached to the global object.
let counter = 0;
let counter;
console.log(counter);
// SyntaxError...
In ES6, the let keyword declares a new variable in each loop iteration.
for (let i = 0; i < 5; i++) {
setTimeout(function () {
console.log(i);
}, 1000);
}
// Answer : 0,1,2,3,4
The let keyword cannot be used this way.
console.log(counter);
let counter = 10;
// Error
const ;
- Same as let but variables defined with const are defined as "constant". They cannot be changed, an error is received when trying to change them.
const myBirthDay = '28.11.1992';
myBirthDay = '01.01.1993'; // error , because the fixed value cannot be changed.
const QUANTITY = 0.5;
QUANTITY = 0.2; // TypeError
const BLACK; // SyntaxError
- Values in the referenced object can be changed.
const umut = { age: 20 };
umut.age = 28; // OK
console.log(person.age); // 28
umut = { age: 40 }; // TypeError
Thanks for reading.