Computer ScienceChapter 3: Programming Fundamentals
3.4.2 Variables
Variable:
Explanation level
This topic explains what variables are in JavaScript, how to declare and initialize them, the basic data types they can hold, and the rules for naming them.
Definition
Variable: A variable is an entity that stores some value for later use. In mathematics, a variable is generally represented by a single character, but not limited to. Similarly, in programming languages, variables should be named in a meaningful manner. Additionally, the type of values the said variable can store is another important aspect.
Core Concept
A variable is like a labeled box where you store information. Imagine you have a box labeled "reward" where you put a number, and another box labeled "name" where you put a word. Whenever you need that information, you just look inside the box by using its label. In programming, variables let you store data, give it a meaningful name, and use it later in your program. Just as you wouldn't want to write the same phone number everywhere, you store it once in a variable and use its name instead.
Detailed Explanation
What is a Variable?
A variable is an entity that stores some value for later use. In mathematics, a variable is generally represented by a single character, but not limited to. Similarly, in programming languages, variables should be named in a meaningful manner. Additionally, the type of values the said variable can store is another important aspect. Such that the developer after defining and assigning a variable, is later able to recall about the task and type of values the said variable holds.
- Stores a value for later use.
- Should have a meaningful name.
- Has a data type (what kind of value it can hold).
- Helps in recalling what the variable is for.
Basic Data Types in JavaScript
The basic value that a variable can hold in JavaScript is either a number or set of characters (called string) or a Boolean which is either 'true' or 'false'.
Table 3-3: Basic datatypes supported by Javascript with sample values.
| Data Type | Sample Value |
|---|---|
| Number | 7, 3, 5, 9 |
| String | J, A, V, A |
| Boolean | TRUE |
- Number: Any numeric value (integer or decimal).
- String: A sequence of characters (text), enclosed in quotes.
- Boolean: Either `true` or `false`.
Naming Rules for Variables
- Variable naming convention does not support a number to be the first character of the variable name.
- Since JavaScript is case sensitive, therefore 'reward' and 'Reward' are two different variables.
- `reward`
- `studentName`
- `_count`
- `$price`
- `1stPrize` (starts with a number)
- `my-name` (contains a hyphen)
- `my name` (contains a space)
Declaring and Initializing Variables
A variable is declared with the `var` keyword, and multiple variables can be declared in the same line of code.
The first ever assignment of a value to a variable in the life span of program is called 'initialization'.
A good programming practice is to declare and initialize the variable at the same time.
Example: Multiple Variables
```html <html> <body> <script type="text/javascript"> var a, b, reward; reward = 5555; a = reward % 10; b = reward / 10; document.write(a, " ---- ", b); </script> </body> </html> ```
Output: 5 ---- 555.5
- `var a, b, reward;` declares three variables.
- `reward = 5555;` initializes `reward` with the value 5555.
- `a = reward % 10;` assigns the remainder of 5555 divided by 10 (which is 5) to `a`.
- `b = reward / 10;` assigns 5555 divided by 10 (which is 555.5) to `b`.
- `document.write(a, " ---- ", b);` displays the values of `a` and `b`.
Example: Using Variables with Strings
```html <html> <body> <script type="text/javascript"> var name = "Ahsan"; // document.write(reward); var reward; reward = 5000; document.write(name, " gets a reward of Rupees ", reward); </script> </body> </html> ```
Output: Ahsan gets a reward of Rupees 5000
Example: Taking Input from the User
For input from the user, we can use the `prompt()` function, which pops up a message window like that of `alert()` function. This input will be assigned to a variable at the backend which can be used later.
Example: ```html <html> <body> <script type="text/javascript"> var ip = prompt("Input a number, please."); document.write("Input from the user was, number:", ip) </script> </body> </html> ```
Output: An alert window asks: "Input a number, please." After the user enters a number, the page displays: "Input from the user was, number: [entered number]"
The Importance of Sequence
It is important to note that the sequence of instructions in programming matters. For example, let's look at the following code, where we defined two variables and, keeping good practice in mind, declared and initialized variable `name` in line 4. However, just to highlight how things can be alternatively done, we declared the `reward` variable in line 6 but assigned an initial value to it in the next line. In line 8, we print the statement using both the variables.
Note that, if you take line 4 and put it after line 8, then the following message is displayed.
This is due to the reason that the variable is defined after the write statement is using the variable. Unless the variable is declared and holds a value, only then it can be used as per the programming sequence. Hence, sequence of instructions is important and though you might have written a program syntax-wise correctly, but the change of sequence might lead you to unexpected bugs.
Intermediate Level
Variables in JavaScript store values for later use. They are declared with `var` and can hold Number, String, or Boolean values. Variable names should be meaningful and cannot start with a number; JavaScript is case-sensitive. The first assignment of a value is called initialization. It's good practice to declare and initialize at the same time. The `prompt()` function can take user input and assign it to a variable. The sequence of instructions matters—a variable must be declared and initialized before it is used, or you may get unexpected results.
Important Points
- - Variable = entity that stores a value.
- - Declared with `var`.
- - Data types: Number, String, Boolean.
- - Cannot start with a number.
- - Case-sensitive (`reward` ≠ `Reward`).
- - Initialization = first assignment.
- - Declare and initialize together (good practice).
- - `prompt()` takes user input.
- - Sequence of instructions matters.
Remember
- - Variable: Stores a value.
- - Declare: `var x;`.
- - Initialize: `x = 5;`.
- - Declare + Initialize: `var x = 5;`.
- - Types: Number, String, Boolean.
- - Naming: No leading number, case-sensitive.
- - Input: `prompt("message")`.
- - Sequence matters.
Common Mistakes
- - Starting a variable name with a number: `1stPrize` is invalid.
- - Forgetting `var`: Always declare variables.
- - Case sensitivity: `reward` and `Reward` are different.
- - Using a variable before declaration: Can cause `undefined` or errors.
- - Confusing `=` (assignment) with `==` (comparison).
- - Forgetting that `prompt()` returns a string: Convert to number if needed.
Quick Revision
Variables in JavaScript store values for later use. They are declared with `var` and can hold Number, String, or Boolean values. Variable names should be meaningful, cannot start with a number, and are case-sensitive. The first assignment is called initialization; it's good practice to declare and initialize at the same time. The `prompt()` function takes user input. The sequence of instructions matters—a variable must be declared and initialized before use.
60-Second Revision
- Variable: Stores value.
- Declare: `var x;`.
- Initialize: `x = 5;`.
- Declare + Initialize: `var x = 5;`.
- Types: Number, String, Boolean.
- Naming: No leading number, case-sensitive.
- Input: `prompt("message")`.
- Sequence matters.
- Key Point: Variables store data; declare and initialize before use.
Did you understand this topic?
Your answer is saved with your learning record. It does not mark the topic as mastered.
Quick revision
Revision Zone
Review the key facts, formulas and checks before you move on.3.4.2 Variables
Sticky Notes · Quick Revision
Key Point 1
- Variable: Stores value.
Key Point 2
- Declare: `var x;`.
Key Point 3
- Initialize: `x = 5;`.
Key Point 4
- Declare + Initialize: `var x = 5;`.
Key Point 5
- Types: Number, String, Boolean.
Key Point 6
- Naming: No leading number, case-sensitive.
Key Point 7
- Input: `prompt("message")`.
Key Point 8
- Sequence matters.
Same supplied content as this Notes page (shared canonical source).