A computer program is a text file that contains a sequence of commands for a computer. There are many programming languages. Each of them requires the programmer to follow specific rules when writing the program so that the computer understands how to execute it. You will study the Javascript language and its rules.
All programs contain commands. With the help of commands, you can "talk" to your computer.
For example, console.log() is used to print messages to the console (press F12 and select the Console tab to see it – there may arleady be a lot of messages 😊):
Please note: end your command with ;
— so the computer knows for sure that this is the end of the command.
A comment is an explanatory text for a program. It is not executed by the computer but helps programmers understand a program's logic better.
Comments can be single-line or multi-line.
Single-line comments are indicated by two backslash characters //
. For example:
Multi-line comments start with /*
and end with */
. For example:
All programs work with data, such as numbers or strings. Literal is a way to write some data in the program.
Number literals consist of digits, -
and .
characters and do not require quotes: 42
, -5
, 3.14
.
In Javascript, you can concatenate (combine) strings using the +
operator.
Please note: in this context, the +
operator performs concatenation (not arithmetic addition of numbers).
For example:
You can concatenate not only strings but also other values, for example, a string with a number:
Please note: if at least one of the values combined by the operator + is a string, then the concatenation is performed (and we get a "glued" string). Concatenation can be performed several times in a row. For example:
String literals are always written in quotes: 'Misha'
, 'Hello, world!'
.
Variables are used to store data. Variables are used to store data. This is like a box with a name in which we can put something. Later we can take the stored data to use it in our program.
The assignment operator =
is used to set a variable value.
JavaScript allows you to create variables using let
and const
keywords.
Let's consider examples:
Please note: the variable name should explain what data is stored in it. Typically it contains one or more words in English. The first word should start with a small letter and the rest with a capital letter. Numbers (inside the name) and _
or $
characters are also possible but rarely used.
For example:
To calculate something in our program, we can combine variables and literals using operators. For example:
To calculate the expression value, you need:
- Replace each variable with its value.
- Perform the calculations.
For example:
Let's look at another example:
All values in Javascript have a specific data type. It determines which commands can be executed with certain values. For example, you can perform any mathematical operations with numbers (add, multiply, divide, and so on), and strings can be "glued" (concatenated) or divided into parts.
Let's consider data types in Javascript.
All the numbers (integer and fractional) have the number
data type.
For example:
The string
data type is used for strings (sequences of characters).
For example:
Please note: all the strings must be enclosed in quotes.
boolean
values can be either true
or false
. Such values check conditions inside of if
constructs and loops.
For example:
There are two more special values: null
and undefined
.
null
is "nothing". It is explicitly assigned to a variable when we do not know the needed value yet or want to remove its old value. For example, we have a box with a gift, and then the gift is taken out of the box, and the box becomes empty:
undefined
is the default value (before we set a variable value). For example:
The typeof
operator can be used to get the data type of your value or even an entire expression.
For example:
Please note: typeof null
returns the 'object'
string, while typeof undefined
returns the undefined
string:
In Javascript, all numbers are of the number
type. They can contain both integer and fractional values.
Let's look at what operations we can perform with numbers and their priority.
I hope you still remember from math lessons what operations you can perform with numbers: addition, subtraction, multiplication, division, exponentiation, and a remainder of the division.
Let's consider examples:
Using the %
operator, you can get the last digit of a number, for example:
You can also check if a number is even:
Usually, operations are performed from left to right. But multiplication and division have higher priority, so they are executed before addition and subtraction. For example:
To specify the correct calculation order, you should use parentheses ()
. Then this operation will be performed first, and then all the others, and (5 + 1) * 10
will be 60
.
Strings represent text data. They can be written in single, double, or backticks. Let's consider examples.
Here is a string in single quotes:
You can insert variable values, expressions, and line breaks using backticks. This insertion is called interpolation:
In the console we get:
Hi, Misha!
Welcome to the team.
a + b = 8
Double quotes ("Misha"
, "Hello, world!"
) work the same way as single quotes, but we won't use them to avoid confusion with double quotes in HTML.
Please note: the quotes type should match at the beginning and the end of your string.
In Javascript, you can concatenate (combine) strings using the +
operator.
Please note: in this context, the +
operator performs concatenation (not arithmetic addition of numbers).
For example:
You can concatenate not only strings but also other values, for example, a string with a number:
Please note: if at least one of the values combined by the operator +
is a string, then the concatenation is performed (and we get a "glued" string). Concatenation can be performed several times in a row. For example:
An empty string is a string that does not contain any characters.
The empty string is declared like this:
Typically, the empty string is used to "glue" parts to it as the program runs.
For example:
Sometimes you need to check if a particular condition is true. As a result, you will get one of two answers: yes, true
or no, not true
.
Javascript uses the boolean
type for such checks. It contains only two values: true
or false
.
For example:
Javascript uses the following operators to compare numbers: ===
, !==
, >
, <
, >=
and <=
.
Let's consider examples:
Strings in Javascript are compared letter by letter in alphabetical order. Let's explain:
- Compare the first letter of the first string with the first letter of the second string.
- If the first letters are different, the larger string is the one where the first letter is later in the alphabet.
- When the first letters are equal, the second letters are compared according to the same principle, and so on.
- The comparison continues until the following letter of one of the strings is greater than the corresponding letter in the other string.
- If one of the strings runs out of letters and the second does not, then the second one is greater.
- If all letters match, then the strings are equal.
For example:
Please note: in Javascript, lowercase letters come after uppercase letters, so comparing 'a' > 'Y'
evaluates to true
:
To get a variable's or expression's opposite value, use the logical negation operator !.
For example:
To apply the negation operator to an entire expression, you can use the ():
If you need to check that all conditions are met, you can use the &&
operator — logical AND.
It returns true
only if all of its arguments are true. Otherwise — false
.
For example:
If you need to check that at least one of the conditions is truthy, you can use the ||
operator — logical OR.
It returns true
if at least one of its arguments is true
. Otherwise — false
.
We'll discuss what the &&
and ||
operators return later.
You can also combine more than two conditions, for example:
If you use different operators in one expression, then you should use ()
:
Please note: the &&
operator priority is higher than ||
, so it will be executed first (unless you use parentheses).
A function is a small part of code that can be executed multiple times. It can take different arguments and return some results.
It allows you to avoid writing the same or similar code many times.
The function
keyword is used to create a function. Let's consider an example:
Where:
function
tells us that this is a function;sayHello
is the function name;personName
is the function parameter. There can be several parameters separated by commas, or not at all, then the()
parentheses should be empty;- the commands in curly braces
{}
are the function body. They are executed on each function call.
Please note: it's best to start the name with a verb that describes the action your function performs. The first word starts with a small letter, and all subsequent words start with a capital letter:
To call a function, you need to write its name and then specify arguments (if you have any) in parentheses.
Let's consider the previous example and pass various arguments to the sayHello()
function:
You can call a function even before it has been declared:
Please note: the value 3
goes to x
, and 2
goes to y
.
For a function to return some value, you need to write the return
keyword in its body, and on the right, specify a value or expression that you want to return.
Let's consider an example:
The result of a function is substituted in the place where it was called. In the examples below, the result is assigned to a variable:
Let's consider another example where the result of a function is not written to a variable (it is printed to the console, but not saved anywhere):
If there is no return
keyword in a function, or if there is no value to the right of return
, then the result is undefined
.
Please note: return
completely terminates the current function execution, so no further commands are executed:
As you already know, the commands in the program are executed sequentially (from top to bottom). But sometimes, we need some commands to be executed only on a specific condition. For this, conditional statements are used.
Let's take a closer look at conditional statements.
Use the if
statement if you need to check only one condition.
Let's consider an example:
After the if
keyword, you need to put parentheses ()
and write condition inside. Then put curly braces {}
, and write your commands inside — this is block body. The block body will only be executed if the condition is truthy.
Here the condition is age >= 18
. If we have age = 16
, then the condition is false, and the command inside the block is not executed. So in the console we get:
Go to the shop
Come back home
If you need to check multiple conditions, you can use the if
statement inside another if
. For example:
But it is challenging to track such a nested construction, for example, where the braces opened and where closed. Therefore, it is better to use the &&
and ||
logical operators to combine conditions:
An example of checking two conditions using the &&
operator:
An example of checking two conditions using the ||
operator:
Sometimes you need to execute different commands depending on whether the condition is truthy or not. You can perform that with two if
statements with opposite conditions. For example:
But there is a shorter and more convenient way to do the same — using the else
:
If the condition is met, then in the console we will see:
The condition isAdult === true
Otherwise, in the console we will see:
The condition isAdult !== true
If you need to execute one command out of several, depending on some condition, then you can use the else if
statement.
Let's consider an example:
With age = 5
, in the console we get: Child
.
You can also add the else
statement at the end, which will work if none of the conditions above is truthy:
With age = 1
, in the console we get: Baby
.
When the if
statement is used within a function, the return
keyword can be helpful to avoid multiple else if
statements.
Let's consider an example:
Sometimes you need to set different values for a variable depending on a condition. You can do it using the if
and else
statements:
But this is not very convenient for two reasons:
- Construction is too big.
- We cannot use
const
for theresult
because we need to reassign it inside theif else
.
There is another way — conditional (ternary) operator. Let's consider an example:
If the age >= 18
condition is met (as in our example), then 'Adult'
(after ?
) will be selected. Otherwise — 'Not an adult '
(after :
).
For clarity, you can write condition in parentheses:
If the expression is too long, then you can write each value on a new line:
This operator is often called a ternary because it is the only operator that uses 3 parts.
Often in your programs, you will need to repeat the same action several times. For this, loops are used.
Here we'll talk about for
, while
, and do while
loops and consider some examples of their usage.
Let's consider an example:
Where:
let age = 3
is the start command, which is executed only once before the loop starts;age < 10
is the condition that is checked before each loop iteration (body execution). The next iteration is executed only if the condition is truthy. Otherwise, the loop is finished;age++
is a command executed after each loop iteration.
In the console we will see:
My age is 3
My age is 4
My age is 5
My age is 6
My age is 7
My age is 8
My age is 9
The for
loop is often used to repeat commands several times.
Let's consider an example:
In the console we will see the following result:
This command will be executed 3 times
0
This command will be executed 3 times
1
This command will be executed 3 times
2
Please note: the loop variable is often called i
, which stands for index (pointer).
Let's take a step-by-step look at how the loop works (on the previous loop example):
- First, the
let i = 0
command is executed. - Next, the
i < 3
(0 < 3
) condition is checked —true
. - The
console.log(i)
command is executed withi === 0
. - The
i++
command is executed (now i === 1
). - The
i < 3
(1 < 3
) condition is checked again —true
. - The
console.log(i)
command is executed withi === 1
. - The
i++
command is executed (now i === 2
). - The
i < 3
(2 < 3
) condition is checked again —true
. - The
console.log(i)
command is executed withi === 2
. - The
i++
command is executed (nowi === 3
). - The
i < 3
(3 < 3
) condition is checked again —false
. - The loop is completed.
Sometimes it is convenient to start iterating over a loop from the end. Let's consider an example:
In the console we will see:
3
2
1
Please note: in this example, we started with let i = 3
and decremented it by 1
at each step instead of incrementing.
We can also create step loops and change the loop variable by any value. Let's consider an example:
In the console we get the following result:
5
15
25
Another example:
In the console we get the following result:
1
3
9
27
You can also sum numbers using a loop. For example:
Sometimes we do not know how many times a particular command needs to be executed. For example, when calculating the remainder of a division.
In such cases, we can use the while
loop that will run as long as the condition is truthy.
Let's consider an example:
Here value >= 5
is the condition. The loop body is executed while the condition is truthy.
If we need to check the condition after the first iteration (not before), then the do while
loop with a postcondition will work.
It is similar to the while
loop but checks the condition after the loop body has been executed once.
For example:
In the console we will see:
0
1
2
Let's look at another example:
Unlike the while (i < 3)
loop, this code prints 7
, and then completes its work.
In practice, the do while
loop is rarely used.