0
0
Javascriptprogramming~10 mins

Variable declaration using const in Javascript - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Variable declaration using const
Start
Declare const variable
Assign initial value
Use variable
Try to reassign?
YesError: Cannot reassign const
No
End
This flow shows declaring a constant variable, assigning it once, using it, and that reassignment causes an error.
Execution Sample
Javascript
const pi = 3.14;
console.log(pi);
pi = 3.14159; // Error
Declare a constant pi, print it, then try to change it which causes an error.
Execution Table
StepActionVariableValueResult/Output
1Declare const pipi3.14No output
2Print pipi3.143.14
3Try to reassign pipi3.14Error: Assignment to constant variable.
💡 Execution stops at step 3 due to error on reassignment of const variable.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3
piundefined3.143.143.14 (unchanged, error on reassignment)
Key Moments - 2 Insights
Why can't we change the value of a const variable after declaring it?
Because const variables are read-only after assignment. The execution_table step 3 shows an error when trying to reassign pi.
Does declaring a const variable require an initial value?
Yes, const must be assigned a value when declared. Step 1 shows pi assigned 3.14 immediately.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of pi after step 2?
A3.14159
Bundefined
C3.14
DError
💡 Hint
Check the 'Value' column for pi at step 2 in the execution_table.
At which step does the program stop due to an error?
AStep 1
BStep 3
CStep 2
DNo error
💡 Hint
Look at the 'Result/Output' column in the execution_table for error messages.
If we remove the reassignment line, what will be the output at step 2?
A3.14
Bundefined
CError
DNothing
💡 Hint
Refer to the output at step 2 in the execution_table when pi is printed.
Concept Snapshot
const variableName = value;
- Declares a constant variable.
- Must assign value at declaration.
- Cannot reassign later (error if tried).
- Use for values that should not change.
Full Transcript
This example shows how to declare a constant variable in JavaScript using const. First, we declare pi with the value 3.14. Then we print pi, which outputs 3.14. Finally, we try to change pi to 3.14159, but this causes an error because const variables cannot be reassigned. The execution stops at this error. Remember, const variables must be assigned a value when declared and cannot be changed later.