Course Content
Introduction to JavaScript
Introduction to JavaScript
Variables
Variables play a crucial role in programming, allowing you to store and reuse values.
Note
A variable is like a container holding different data types, such as numbers, text, or more complex structures.
Before using variables, they must be defined. To define a variable, use the let
keyword and choose a name for it:
Note
Variable names should follow the camelCase style. camelCase means that words are written together without spaces, and each word (except the first) is capitalized.
By default, a new variable contains the undefined
value, indicating that no value has been assigned.
Note
The
undefined
value signifies that a value has not yet been assigned to the variable.
You can assign a value to a variable using the assignment operator (=
):
Alternatively, you can assign a value when the variable is defined:
Using Variables
Variables can be used to represent various values in your code and can be reused multiple times, reducing code repetition.
let word = "VariableText"; // The variable value is the `"VariableText"` console.log("ValueText"); // Print the `"ValueText"` console.log(word); // Print the variable value
You can assign and reassign values to variables as needed:
let numb; numb = 100; console.log(numb); numb = 100 + 20; console.log(numb);
Variables are essential in programming because they allow you to reuse the same value many times. Consider a scenario where you've written 1000 lines of code using a specific value but made a typo that appears multiple times. In such a case, you'd need to correct every occurrence of that word in your code, which would be a significant waste of time.
Now, let's examine a similar example with fewer lines:
console.log("Hello Word!"); console.log("I love this Word!"); console.log("I need to live in this Word!"); console.log("This Word is the best!");
In this example, the author accidentally omitted the letter l
in the word World
. To fix this program, you only need to correct one occurrence of the typo.
Look at the following example:
let x = "Word"; console.log("Hello " + x + "!"); console.log("I love this " + x + "!"); console.log("I need to live in this " + x + "!"); console.log("This " + x + " is the best!");
You can fix it by changing one letter in the variable value from "Word"
to "World"
. Please correct the provided example on your own.
Note
In the example above, we used string concatenation. We will delve into string concatenation in the next section.
Thanks for your feedback!