JavaScript: Difference between revisions

Content deleted Content added
Added logo and explained difference between var and let / const
Variable declaration: removed differences between var and let / const as it is better explained in the main article
Line 204:
changeableVariable = 'I can be changed.'; // Will change value of 'changeableVariable'
constantVariable = 'I cannot be changed!!'; // Will throw 'TypeError' for reassigning a constant
</syntaxhighlight>
 
===== Difference between <code>var</code> and <code>let</code> /<code>const</code> =====
<syntaxhighlight lang="javascript">
 
let letOutsideBlock = 'letOutsideBlock'; // defines a variable which is only accessable in the block that it has been defined in
const constOutsideBlock = 'constOutsideBlock'; // defines a constant which is only accessable in the block that it has been defined in
var varOutsideBlock = 'varOutsideBlock'; // defines variable which is accessable in the entire function scope, even if defined in a block
 
if(true) { // Block which will always run for demonstration
let letInBlock = 'letInBlock'; // Will expire after the block ends
const constInBlock = 'constInBlock'; // Will expire after the block ends
var varInBlock = 'varInBlock'; // Will remain after the block ends
// Printing of values to the console, these will all work:
console.log('-- Inside Block:')
console.log(letOutsideBlock);
console.log(letInBlock);
console.log(constOutsideBlock);
console.log(constInBlock);
console.log(varOutsideBlock);
console.log(varInBlock);
}
 
// Printing of values to the console:
console.log('-- Outside Block:')
console.log(letOutsideBlock); // will run
console.log(constOutsideBlock); // will run
console.log(varOutsideBlock); // will run
console.log(varInBlock); // will run
 
console.log(letInBlock); // will throw 'ReferenceError' as it is no longer defined
console.log(constInBlock); // will throw 'ReferenceError' as it is no longer defined
</syntaxhighlight>