- Learn by example
Make an RPG
Vue Implementations

Examples of Let and Const

let prevents you from accessing a variable outside of the block it was declared in. Why would you want this? It's good to keep things contained. The fewer places a variable can affect, the fewer places it can cause a side effect or bug. It's the same reason why you avoid using globals.

if( true ) { let a = 'Letter A '; var b = 'Letter B '; log(a); log(b); } //log(a); log('Second ' + b);

If you uncomment the log(a) function outside of the if(true) block, you'll see that there is an error in the console. That's because "a" was declared with let, thus it is only accessible within the code block.


const is used to define a variable that should not change. Think of it as a rule that you're setting up: this variable shall not change. For example, this code will error out:

const a = "hello"; a = "hi";

Why would you want to use a const? It can help you prevent bugs. Let's say you have a variable called num_of_wheels and you know the car will only ever have 4 wheels. In this case you want to use a const to prevent the variable from changing.

const arrays

An array reference can not change. Hence this will be an error:

const colors = [ "red", "blue" ]; colors = "green";

But, the array itself can still change. This is not an error.

const colors = [ "red", "blue" ]; colors.push( "green" );

This is a bit confusing. Think of it this way. colors points to the address of the array. The address of the array can NOT change. But, the memory after the address or the memory after that memory (thats part of that array), can change.

Zen buddhists would sit for hours a day contemplating koans, to help them understand the world around them. If you're still confused, ponder this Zen koan:

"The finger pointing at the moon is not the moon."

In the next lesson, we will learn about Examples of Functions and Parameters

Get the Latest Tutorial Updates
<< >>