Imagine you want to store your friend's name and use it later in your program. Why is it helpful to use a variable for this?
Think about how you remember things in real life to use later.
Variables act like labeled boxes where you can keep information. This helps you reuse and update data easily in your program.
Look at this JavaScript code. What will it print?
let name = 'Alice'; let greeting = 'Hello, ' + name + '!'; console.log(greeting);
Variables hold values that can be combined to make new messages.
The variable name stores 'Alice'. The variable greeting combines 'Hello, ' with the value of name and '!'. So the output is 'Hello, Alice!'.
Consider this JavaScript code. What is the final value of x?
let a = 5; let b = 3; let x = a + b; a = 10; x = x + a;
Remember that changing a after calculating x does not change the old value of x unless you update it.
Initially, x = 5 + 3 = 8. Then a changes to 10. Finally, x = 8 + 10 = 18.
Which code snippet will cause an error because the variable is used before it is declared?
Think about when variables are ready to be used in JavaScript.
In option A, score is logged before it is declared with let, causing a ReferenceError. Other options declare before use.
Imagine you write a program that uses the number 7 many times. Why is it better to store 7 in a variable and use the variable instead of writing 7 everywhere?
Think about how changing one place is easier than many places.
Using variables means if you want to change the number, you only change it once in the variable. It also makes the code clearer by giving the number a name.