JavaScript: Changing a variable
The very word "variable" suggests that its value can change. This is one of the main reasons variables exist at all.
Here is a simple example:
// greeting means a salutation
let greeting = 'Father!';
console.log(greeting); // => Father!
greeting = 'Mother!';
console.log(greeting); // => Mother!Here we first stored one string (Father!) in the variable, then another (Mother!). The variable name did not change, but the value inside became different.
Before: greeting ──→ 'Father!'
╳
After: greeting ──→ 'Mother!'Note: the keyword let is written only at the first declaration of a variable. On reassignment, let is no longer needed — the variable already exists, and we are only changing its value.
Why change a value at all?
In real programs, variables change all the time. Here are a few reasons:
- The program reacts to user actions. For example, while you are entering data into a form on a website, the variables that hold this data are being updated constantly at that moment.
- Intermediate results. Often data passes through a series of transformations, and at each stage a variable is updated with a new value. There is even a similar mechanism in calculators, when intermediate values are saved using the
m+orm-keys. - Storing state. If you are writing a game, then the character's position, health, score, and current level are variables that change constantly.
const does not change
Not every variable can be reassigned. If a variable is declared with const, its value cannot be changed:
const greeting = 'Father!';
greeting = 'Mother!'; // TypeError: Assignment to constant variable.That is why let is used for values that will change, and const for constant ones. This is how most modern programming languages work: a value that should not change is marked separately.
Why this matters
Variables are a flexible way to store data that can change during program execution. Thanks to this, you can write programs that behave differently depending on conditions, user actions, or the results of computations.
But flexibility has a downside. Sometimes it is hard to immediately tell what exactly is stored in a variable at one moment or another. The developer has to track where and how it changed, especially if the code is long.
This is exactly what is done during debugging: trying to figure out why the program works differently than intended. They check the values of variables, trace the order of code execution, and look for where something went wrong.
Instructions
The order status is updated as the order moves along. At the beginning, the order is in the 'in transit' status, then it changes to the 'delivered' status.
The exercise already defines a variable deliveryStatus with the value 'in transit'. Reassign its value to 'delivered' and print it to the screen.
An example of reassigning a variable:
let someVar = 'old value';
someVar = 'new value';
console.log(someVar); // => new valueIf you've reached a deadlock it's time to ask your question in the «Discussions». How ask a question correctly:
- Be sure to attach the test output, without it it's almost impossible to figure out what went wrong, even if you show your code. It's complicated for developers to execute code in their heads, but having a mistake before their eyes most probably will be helpful.
Tests are designed so that they test the solution in different ways and against different data. Often the solution works with one kind of input data but doesn't work with others. Check the «Tests» tab to figure this out, you can find hints at the error output.
It's fine. 🙆 One task in programming can be solved in many different ways. If your code passed all tests, it complies with the task conditions.
In some rare cases, the solution may be adjusted to the tests, but this can be seen immediately.
It's hard to make educational materials that will suit everyone. We do our best but there is always something to improve. If you see a material that is not clear to you, describe the problem in “Discussions”. It will be great if you'll write unclear points in the question form. Usually, we need a few days for corrections.
By the way, you can participate in courses improvement. There is a link below to the lessons course code which you can edit right in your browser.
Создавать обучающие материалы, понятные для всех без исключения, довольно сложно. Мы очень стараемся, но всегда есть что улучшать. Если вы встретили материал, который вам непонятен, опишите проблему в обратной связи нашего сообщества
Your exercise will be checked with these tests:
// @ts-check
import { expect, test, vi } from 'vitest';
test('hello world', async () => {
const consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
await import('./index.js');
const firstArg = consoleLogSpy.mock.calls.join('\n');
expect(firstArg).toBe('delivered');
});Teacher's solution will be available in:
20:00
