JavaScript Identifiers
JavaScript Identifiers
Identifiers can be short names (like x and y) or more descriptive names (age,
sum, totalVolume).
The general rules for constructing names for variables (unique identifiers) are:
Names can also begin with $ and _ (but we will not use it in this tutorial).
Note
In JavaScript, the equal sign (=) is an "assignment" operator, not an "equal to"
operator.
This is different from algebra. The following does not make sense in algebra:
x=x+5
(It calculates the value of x + 5 and puts the result into x. The value of x is
incremented by 5.)
Note
JavaScript variables can hold numbers like 100 and text values like "John Doe".
JavaScript can handle many types of data, but for now, just think of numbers
and strings.
Strings are written inside double or single quotes. Numbers are written
without quotes.
const pi = 3.14;
You declare a JavaScript variable with the var or the let keyword:
var carName;
or:
let carName;
carName = "Volvo";
You can also assign a value to the variable when you declare it:
In the example below, we create a variable called carName and assign the
value "Volvo" to it.
Then we "output" the value inside an HTML paragraph with id="demo":
Example
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = carName;
</script>
Note
Start the statement with let and separate the variables by comma:
Example
Example
let person = "John Doe",
carName = "Volvo",
price = 200;
Value = undefined
In computer programs, variables are often declared without a value. The value
can be something that has to be calculated, or something that will be
provided later, like user input.
The variable carName will have the value undefined after the execution of this
statement:
Example
let carName;
If you re-declare a JavaScript variable declared with var, it will not lose its
value.
The variable carName will still have the value "Volvo" after the execution of
these statements:
Example
Note
let carName;
JavaScript Arithmetic
Example
let x = 5 + 2 + 3;
Example
Example
let x = "5" + 2 + 3;
Note
If you put a number in quotes, the rest of the numbers will be treated as
strings, and concatenated.
Example
let x = 2 + 3 + "5";
Example
let $$$ = 2;
let $myMoney = 5;
Using the dollar sign is not very common in JavaScript, but professional
programmers often use it as an alias for the main function in a JavaScript
library.
In the JavaScript library jQuery, for instance, the main function $ is used to
select HTML elements. In jQuery $("p"); means "select all p elements".
let _x = 2;
let _100 = 5;