Aim of the puzzle: Use the ++ and -- operators to change the value of a variable.
Walk through of solution: On the first line, the x variable is defined with the value 5. The next line increments (adds 1 to) the x variable. You can see the results printed by the next line.
Now, tap on the x on the next line all by itself. Tap the -- button to decrement (subtract 1 from) the x variable. When you run the code now you will see that the value of x went back down by 1.
Sample code solution:
(Tap below to reveal)
let x = 5;
x++;
print('x is ' + x);
x--;
print('x is now ' + x);
I cannot add to a string inside a bracket . When I type âx is nowâ I cannot add + x between the end of the string and the bracket.
Hope I have explained my problem so that it can be understood!
OK, no need to reply. I fixed it by not doing this by myself, rather just reverting to the original and adding one operator, which I see now was the intention.
The strings 'x is' and 'x is now' are not special. We could have used 'The value of the variable is ' and 'After updating x, it has a value of ', or any other string. Those strings are being combined with value of x using the + symbol. When you use + with a string and a variable, it will try to convert the variable into a string and then combine them to create a single string. In this puzzle, the strings donât actually change the value of the x variable; theyâre just used to help us know what the number being printed out is representing.
With this puzzle, a let and var would behave the same way because there are no separate code blocks {} as you mentioned. If you use let in your code, it doesnât mean that you need to add curly brackets {}; it only means that if there is a code block, then the let canât leave it. If a let variable is created and itâs not inside of any curly brackets, then there is no boundary on where that variable can be used, except that you canât use it before youâve created it.
In this example code, Iâve written 'yes' where the x can be used, and 'no' where it cannot be used:
'no'
{ //Beginning of the let's code block
'no, not created yet'
let x = 0;
'yes, same block'
{
'yes, still inside the bigger block'
}
'yes'
} // End of the let's code block
'no'
{
'no'
}
'no'
Once we introduce let in Fundamentals II, we use that instead of var in the lessons.
For many years, var was the only way to declare a variable in JavaScript. It is still widely used in many older programs and browsers, so itâs important to know.
In 2015 (I thinkâŚ), the let and const keywords were added to JavaScript to replace var, so var is not used in newer code.
We donât have any lessons yet that use const, but const is used to declare a âconstantâ variable, meaning you canât give it a new value.
For example:
const num = 5
num = 7 // this will cause an error, because it's assigning a new value to num
Hope this explains things! Let me know if you have any questions.
Ben