jsvariables.md - brainchildservices/curriculum GitHub Wiki
A variable is a container for a value, like a number we might use in a sum, or a string that we might use as part of a sentence. But one special thing about variables is that their contained values can change. Let's look at a simple example:
Example:- Click Here
In this example pressing the button runs a couple of lines of code. The first line pops a box up on the screen that asks the reader to enter their name, and then stores the value in a variable. The second line displays a welcome message that includes their name, taken from the variable value.
To understand why this is so useful, let's think about how we'd write this example without using a variable. It would end up looking something like this:
let name = prompt('What is your name?');
if (name === 'Adam') {
alert('Hello Adam, nice to see you!');
} else if (name === 'Alan') {
alert('Hello Alan, nice to see you!');
} else if (name === 'Bella') {
alert('Hello Bella, nice to see you!');
} else if (name === 'Bianca') {
alert('Hello Bianca, nice to see you!');
} else if (name === 'Chris') {
alert('Hello Chris, nice to see you!');
}
// ... and so on ...
You may not fully understand the syntax we are using (yet!), but you should be able to get the idea — if we didn't have variables available, we'd have to implement a giant code block that checked what the entered name was, and then display the appropriate message for any name. This is obviously really inefficient (the code is a lot bigger, even for only five choices), and it just wouldn't work — you couldn't possibly store all possible choices.
Variables just make sense, and as you learn more about JavaScript they will start to become second nature.
Another special thing about variables is that they can contain just about anything — not just strings and numbers. Variables can also contain complex data and even entire functions to do amazing things. You'll learn more about this as you go along.
Note: We say variables contain values. This is an important distinction to make. Variables aren't the values themselves; they are containers for values. You can think of them being like little cardboard boxes that you can store things in.
Ref:- https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Variables