JavaScript Basics: Bindings
When running a program in JavaScript, it remembers what values go where and when to update them. It updates values by replacing old values with new ones, but how does it do that? JavaScript will have to attach the value to something or the value is meaningless.
That is when binding or variables come in.
let num = 4 + 3;
The special keyword let
tells JavaScript that you are going to define a variable. It is followed by the name of the variable num
and an =
operator to tell JavaScript what you want to attach to num
. In this case, we want to add 4
and 3
. The total is now tied to the num
variable.
Instead of writing 4 + 3
multiple times in your program, you can mention only num
. If you want to change the +
operator to a *
and multiply it, you can go to the original mention of the variable and change it. This is better than writing 4 + 3
multiple times in your code.
You can update num
by adding another variable to it:
let inches = 20;
console.log(num + inches);
Since num + inches
isn’t tied to a variable, the value is gone once the program is done. If it was attached to a variable, you could reuse that variable elsewhere in the code. As long as you mention the variable before you use it.
If you try to mention a variable that you didn’t initate, JavaScript will throw the following error:
Uncaught ReferenceError: [variable name] is not defined
When you define a variable without a value, JavaScript will give it a value of undefined
.
When a variable has a value, it remains with it until the variable is updated to something else. You can use the =
operator any time to bind an existing variable to another value. This will disconnect the variable from whatever old value and update with a new one.
So if later down the program, I change num
:
let num = 4 + 7;
num = 50;
The variable num
no longer equals to 7
. It is now 50
.
You can also update num
by taking its current value and subtracting a few values from it:
num = num - 2;