JavaScript variables have the capability to store both numerical values, such as 100, and textual values, referred to as “text strings” in programming terminology.
JavaScript supports various data types, but for simplicity, focus on numbers and strings for now.
Strings are enclosed within either double or single quotation marks, while numbers are written without quotes.
When a number is enclosed in quotes, JavaScript interprets it as a text string.
Example
const pi = 3.14; let person = “John Doe”; let answer = ‘Yes I am!’; |
In JavaScript, creating a variable is referred to as “declaring” a variable.
You declare a JavaScript variable using either the var or the let keyword.
var carName; |
or:
let carName; |
Upon declaration, the variable holds no value, technically rendering it as undefined.
To assign a value to the variable, utilize the equal sign:
carName = “Volvo”; |
You also have the option to assign a value to the variable during its declaration:
let carName = “Volvo”; |
In the following example, a variable named carName is established and assigned the value “Volvo”.
Subsequently, we display the value within an HTML paragraph identified by id=”demo”:
Example
<p id=”demo”></p> <script> let carName = “Volvo”; document.getElementById(“demo”).innerHTML = carName; </script> |
Note Declaring all variables at the outset of a script is considered a best practice in programming. |