This blog post is part of the series “Learning web development” – which teaches people who have never programmed before how to create web apps with JavaScript.
I’m interested in feedback! If there is something you don’t understand, please write a comment at the end of this page.
In this chapter, we take the very first steps with JavaScript and learn about numbers, variables and functions.
Starting with the next chapter, we’ll always learn by creating real, useful apps. In this chapter, we’ll warm up by doing some relatively simple interactions with JavaScript.
To run JavaScript programs, we need a so-called JavaScript engine. Luckily, each web browser has a built-in JavaScript engine. One way of interacting with it is via the browser’s console. We’ll see soon how the console works. As a first step, please figure out how to open the console of the web browser that you are using. The following links may help:
As an aside: I will occasionally ask you to figure out things by yourself (by doing a web search etc.). That is an important skill for web developers: You will not always have someone who explains to you how to do something. You will have to do your own research, experiment, etc.
The console enables an infinite back and forth between us and JavaScript:
Let’s try out the console.
We’ll start with very simple JavaScript code: so-called numeric expressions – “formulas” with numbers. For example, JavaScript can add numbers:
3 + 2
5
You can follow along in your own browser console and see if your output always matches what is shown here.
From now on, console interactions will be displayed as follows:
> 3 + 2
5
The >
(greater-than symbol) at the beginning of the first line indicates that this is our input. It’s something the browser displays, not something we type. We type what comes after the >
. The next line is the browser’s output.
So far, we have used the addition operator +
to add numbers. But we can also:
Use the subtraction operator -
to subtract numbers (the symbol is a hyphen):
> 3 - 2
1
Use the multiplication operator *
to multiply numbers (the symbol is an asterisk):
> 3 * 2
6
Use the division operator /
to divide numbers (the symbol is a slash):
> 3 / 2
1.5
Note that we have seen two kinds of numbers:
5
1.5
In JavaScript, these are not different: 5
means the same as 5.0
.
We can also write longer numeric expressions:
> 1 + 2 * 3
7
However, given that it’s not immediately obvious in which order multiple operators are going to be applied, I prefer to use parentheses in such a case – they make it clear what’s going to happen:
Adding 1 to 2 times 3:
> 1 + (2 * 3)
7
Multiplying 1 plus 2 by 3:
> (1 + 2) * 3
9
JavaScript does the former – it follows the mathematical rule of multiplication (and division) having a higher precedence than addition (and subtraction).
If we want to run a JavaScript program, we need a JavaScript engine:
In general, the JavaScript engine is a black box: We don’t see what happens inside it. However, there are exceptions – e.g.:
There are two words related to running JavaScript which are useful to know:
Syntax: Syntax refers to the rules for writing correct JavaScript programs. Computer languages are similar to human languages when it comes to syntax:
+ 3 1
Syntax can additionally refer to the structure of JavaScript source code (vs. the rules for that structure).
Runtime: The time during which an engine runs JavaScript code is called runtime.
Variables are an important construct in JavaScript: A variable is a box with a name in which we can put values (such as numbers).
> let myNumber = 8;
undefined
> myNumber * 2
16
myNumber
. We’ll soon get answers to two questions:
undefined
mean?myNumber
has become a name (an alias, an abbreviation) for the value that the variable contains.So far, we have only seen one kind of JavaScript code: expressions. An expression is JavaScript syntax that, when run, produces a value. The previous interaction contains new syntax:
let myNumber = 8;
That is a statement: syntax that, when executed, does things (at runtime). This particular statement is a variable declaration. It creates a variable. Let’s examine the syntax:
let
is the name of one command for creating variables.myNumber
is the name of the created variable.=
) indicates that we want to specify an initial value for the variable. 8
is that initial value. We initialized myNumber
with 8
.Why does this statement produce the result undefined
? That is a pseudo-value that means “there is no real result”. Statements often don’t have results. Expressions always have results.
A
, b
, etc.), a dollar sign ($
) or an underscore (_
)3
, 0
, etc.).The names of most variables start with lowercase letters. Word boundaries are marked via capital letters:
numberOfPeople
value3
This way of writing variable names is called camel case (because it has humps – like a camel).
Variables whose values never change sometimes have names with words in all-caps, separated by underscores:
NUMBER_OF_PEOPLE
VALUE3
The result of statement is virtually never useful. Therefore, from now on, I will omit the result of a console input if it ends with a semicolon – i.e., I’d write the previous example like this:
> let myNumber = 8;
> myNumber * 2
16
The output of the first line is irrelevant and therefore omitted.
If we don’t follow the syntax rules then JavaScript reports an error and we can’t run the code – e.g., let’s use an illegal variable name that starts with a digit:
> let 1number = 7;
SyntaxError: Invalid or unexpected token
The exact message varies between JavaScript engines, but the name of the error is always SyntaxError
.
In addition to retrieving the content of a variable, we can also change its content:
> let value = 0;
> value
0
> value = 3;
> value
3
We initialized the variable value
with 0
. Later, we changed its value to 3
. We used the assignment operator (=
) to do so (this time without a let
).
The right-hand side of an assignment can be any expression:
> value = 1 + 1 + 1;
> value
3
That enables statements that look weird and unmathematical:
> let myVar = 0;
> myVar = myVar + 1;
> myVar
1
What does the following statement mean?
myVar = myVar + 1;
myVar
.1
to it.myVar
.In other words: The assignment operator is not a mathematical equals sign. Its syntax has historical reasons. This would be better syntax:
myVar <- myVar + 1;
If we never change the value of a variable, we can use a different way of declaring it. Then JavaScript warns us if we accidentally change it:
> const TWO = 2;
> TWO + TWO
4
> TWO = 3;
TypeError: Assignment to constant variable.
In JavaScript, const
is not much different from let
. Its most useful as hint for programmers: “This variable will never change.”
The name of the variable is written in capital letters – as an additional hint that it is a constant. But we don’t have to do that; in fact, doing that has even become somewhat rare.
In JavaScript, variables can also be nested: Variables can contain variables themselves (the former variables are called objects). We’ll learn how to do that ourselves in a future chapter. But JavaScript already has many predefined nested variables – e.g., variable PI
inside variable Math
:
> Math.PI
3.141592653589793
The dot (.
) is used as a separator when accessing nested variables. That is similar to how slashes (/
) or backslashes (\
) separate directory names in file paths.
So far, the only values we have seen were numbers. Let’s explore another kind of value next: functions. A function is like a little program that we store inside a variable. We can use a statement to run/call/invoke a function:
In the following example, the variable timesThree
is/contains a function:
> const timesThree = (x) => { return x * 3; };
> timesThree(2)
6
> timesThree(0.5)
1.5
timesThree
.2
. It returns the result 6
.The function as a value has the following syntax:
(x) => { return x * 3; }
What does this syntax mean?
(x)
: The input of the function is stored in the variable x
. This variable is called the parameter of the function. A function can have zero or more parameters.=>
is mostly decorative.{
and }
) contain the function’s code.The body of a function can contain zero or more statements. The return
statement specifies the result of calling the function. I often omit the semicolon when it is immediately followed by a closing brace. In this case, I didn’t.
In consoles, our JavaScript code usually only consists of a single line. However, JavaScript code is normally stored in text files and consists of multiple lines. This is an example of a function that takes up multiple lines of text:
const celsiusToFahrenheit = (c) => {
const f = (c * (9/5)) + 32;
return f;
};
This function converts a temperature in Fahrenheit to a temperature in Celsius (source: Wikipedia):
c
is the input: A number that specifies the temperature in degree Celsius.f
. For clarity, we have used more parentheses than strictly necessary.f
as the result of the function.Note that the function contains two statements. Each ends with a semicolon. The semicolon at the very end belongs to the const
:
const celsiusToFahrenheit = ···;
We can paste this multi-line code into a console and call the function:
> celsiusToFahrenheit(0)
32
> celsiusToFahrenheit(40)
104
We’ll see this function again in a future project!