To learn JavaScript, we must learn the basics.
In this article, we’ll look at the most basic parts of the JavaScript language.
Math Expressions
We should eliminate ambiguity with JavaScript math expressions.
For example, if we have:
let totalCost = 1 + 3 * 10;
then readers may be confused about which operation comes first.
JavaScript has precedence rules for operators. They generally follow the same rules as normal math.
However, we can make everyone’s lives easier by wrapping parentheses around expressions that have higher precedence.
For example, we can write:
let totalCost = 1 + (3 * 10);
then we wrap the expressions around the multiplication.
Now we know the multiplication operation comes first.
If we move the parentheses, then the operations would be done in a different order.
For instance, if we have:
let totalCost = (1 + 3) * 10;
then the addition is done before the multiplication.
Concatenating Strings
Strings are text values and they can be combined with concatenation.
For example, we can write:
alert("Thanks, " + userName + "!");
to combine the 3 expressions into 1 with the +
operator.
If userName
is 'james'
, then we have:
'Thanks, james!'
The 3 parts are combined together and returned as one string.
We can concatenate strings with any other JavaScript expressions.
They’ll be converted to strings automatically so that they can be concatenated together.
So if we have:
alert("2 plus 3 equals " + 2 + 3);
Then we get '2 plus 3 equals 23'
.
This is because 2 and 3 are converted to strings before they’re concatenated.
A more convenient way to combine strings and other expressions is to use template literals.
For example, we can write:
alert(`2 plus 3 equals ${2 + 3}`);
We replaced the quotes with the backticks.
Then we use the ${}
symbols to surround the JavaScripot expressions to interpolate the expressions.
This way, we have 2 + 3
returning a number since they’re concatenated with strings.
So we get '2 plus 3 equals 5'
.
Prompts
A prompt box lets us ask use for some information and provide a response field for the answer.
For example, we can write:
let name = prompt("Your name?", "mary");
We call prompt
with the question string as the first argument.
The 2nd argument is the default answer returned.
If we call that, the browser will show an alert box with an input box to let us enter our answer.
Then when we click OK, then the response is returned if it’s entered.
Otherwise, the default answer is returned.
If we omit the default answer in the 2nd argument and we entered nothing, then it returned null
.
prompt
is a global function, so window.prompt
is the same as prompt
.
But we can just write prompt
.
Conclusion
We can take text answers from a user with the prompt
function.
Math expressions can be made clearer with parentheses.