javascript student
javascript student
JAVASCRIPT
What is JavaScript?
JavaScript programs can be inserted almost anywhere into an HTML document using the
<script> tag.
For instance:
<!DOCTYPE HTML>
<html>
<body>
<script>
alert( 'Hello, world!' );
</script>
</body>
</html>
The <script> tag contains JavaScript code which is automatically executed when the
browser processes the tag.
Modern markup
Mrs PEWAHO 1
ISTAMA HND CGWD1/ SWE1
The <script> tag has a few attributes that are rarely used nowadays but can still be found in
old code:
The old HTML standard, HTML4, required a script to have a type. Usually it was
type="text/javascript". It’s not required anymore. Also, the modern HTML
standard totally changed the meaning of this attribute. Now, it can be used for
JavaScript modules. But that’s an advanced topic, we’ll talk about modules in another
part of the tutorial.
This attribute was meant to show the language of the script. This attribute no longer
makes sense because JavaScript is the default language. There is no need to use it.
In really ancient books and guides, you may find comments inside <script> tags, like
this:
<script type="text/javascript"><!--
...
//--></script>
This trick isn’t used in modern JavaScript. These comments hide JavaScript code from
old browsers that didn’t know how to process the <script> tag. Since browsers
released in the last 15 years don’t have this issue, this kind of comment can help you
identify really old code.
External scripts
If we have a lot of JavaScript code, we can put it into a separate file.
<script src="/path/to/script.js"></script>
Here, /path/to/script.js is an absolute path to the script from the site root. One can also
provide a relative path from the current page. For instance, src="script.js", just like
src="./script.js", would mean a file "script.js" in the current folder.
<script
src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></
script>
<script src="/js/script1.js"></script>
<script src="/js/script2.js"></script>
Mrs PEWAHO 2
ISTAMA HND CGWD1/ SWE1
…
Please note:
As a rule, only the simplest scripts are put into HTML. More complex ones reside in separate
files.
A single <script> tag can’t have both the src attribute and code inside.
<script src="file.js">
alert(1); // the content is ignored, because src is set
</script>
We must choose either an external <script src="…"> or a regular <script> with code.
<script src="file.js"></script>
<script>
alert(1);
</script>
Summary
We can use a <script> tag to add JavaScript code to a page.
The type and language attributes are not required.
A script in an external file can be inserted with <script
src="path/to/script.js"></script>.
Code structure
Statements
Statements are syntax constructs and commands that perform actions.
We’ve already seen a statement, alert('Hello, world!'), which shows the message
“Hello, world!”.
We can have as many statements in our code as we want. Statements can be separated with a
semicolon.
alert('Hello'); alert('World');
Usually, statements are written on separate lines to make the code more readable:
alert('Hello');
Mrs PEWAHO 3
ISTAMA HND CGWD1/ SWE1
alert('World');
Semicolons
A semicolon may be omitted in most cases when a line break exists.
alert('Hello')
alert('World')
Here, JavaScript interprets the line break as an “implicit” semicolon. This is called an
automatic semicolon insertion.
In most cases, a newline implies a semicolon. But “in most cases” does not mean
“always”!
There are cases when a newline does not mean a semicolon. For example:
alert(3 +
1
+ 2);
The code outputs 6 because JavaScript does not insert semicolons here. It is intuitively
obvious that if the line ends with a plus "+", then it is an “incomplete expression”, so a
semicolon there would be incorrect. And in this case, that works as intended.
Comments
As time goes on, programs become more and more complex. It becomes necessary to add
comments which describe what the code does and why.
Comments can be put into any place of a script. They don’t affect its execution because the
engine simply ignores them.
The rest of the line is a comment. It may occupy a full line of its own or follow a statement.
Like here:
Multiline comments start with a forward slash and an asterisk /* and end with an
asterisk and a forward slash */.
Mrs PEWAHO 4
ISTAMA HND CGWD1/ SWE1
Like this:
The content of comments is ignored, so if we put code inside /* … */, it won’t execute.
Variables
A variable is a “named storage” for data. We can use variables to store goodies, visitors, and
other data.
The statement below creates (in other words: declares) a variable with the name “message”:
let message;
Now, we can put some data into it by using the assignment operator =:
let message;
The string is now saved into the memory area associated with the variable. We can access it
using the variable name:
let message;
message = 'Hello!';
To be concise, we can combine the variable declaration and assignment into a single line:
let message = 'Hello!'; // define the variable and assign the value
alert(message); // Hello!
For the sake of better readability, please use a single line per variable.
In older scripts, you may also find another keyword: var instead of let:
The var keyword is almost the same as let. It also declares a variable, but in a slightly
different, “old-school” way.
let message;
message = 'Hello!';
alert(message);
When the value is changed, the old data is removed from the variable:
We can also declare two variables and copy data from one into the other.
let message;
So, we should declare a variable once and then refer to it without let.
In such languages, once the value is stored “in the box”, it’s there forever. If we need to store
something else, the language forces us
Variable naming
Mrs PEWAHO 6
ISTAMA HND CGWD1/ SWE1
1. The name must contain only letters, digits, or the symbols $ and _.
2. The first character must not be a digit.
let userName;
let test123;
When the name contains multiple words, camel Case is commonly used. That is: words go
one after another, each word except first starting with a capital letter: myVeryLongName.
What’s interesting – the dollar sign '$' and the underscore '_' can also be used in names.
They are regular symbols, just like letters, without any special meaning.
alert($ + _); // 3
Case matters
It is possible to use any language, including Cyrillic letters or even hieroglyphs, like this:
Technically, there is no error here. Such names are allowed, but there is an international
convention to use English in variable names. Even if we’re writing a small script, it may have
a long life ahead. People from other countries may need to read it some time.
Reserved names
There is a list of reserved words, which cannot be used as variable names because they are
used by the language itself.
Mrs PEWAHO 7
ISTAMA HND CGWD1/ SWE1
Constants
To declare a constant (unchanging) variable, use const instead of let:
Variables declared using const are called “constants”. They cannot be reassigned. An attempt
to do so would cause an error:
When a programmer is sure that a variable will never change, they can declare it with const
to guarantee and clearly communicate that fact to everyone.
A variable name should have a clean, obvious meaning, describing the data that it stores.
Variable naming is one of the most important and complex skills in programming. A quick
glance at variable names can reveal which code was written by a beginner versus an
experienced developer.
In a real project, most of the time is spent modifying and extending an existing code base
rather than writing something completely separate from scratch. When we return to some
code after doing something else for a while, it’s much easier to find information that is well-
labeled. Or, in other words, when the variables have good names.
Please spend time thinking about the right name for a variable before declaring it. Doing so
will repay you handsomely.
Mrs PEWAHO 8
ISTAMA HND CGWD1/ SWE1
Summary
We can declare variables to store data by using the var, let, or const keywords.
Variables should be named in a way that allows us to easily understand what’s inside them.
Tasks
Working with variables
importance: 2
Data types
A value in JavaScript is always of a certain type. For example, a string or a number.
We can put any type in a variable. For example, a variable can at one moment be a string and
then store a number:
// no error
let message = "hello";
message = 123456;
Programming languages that allow such things, such as JavaScript, are called “dynamically
typed”, meaning that there exist data types, but variables are not bound to any of them.
Number
let n = 123;
n = 12.345;
The number type represents both integer and floating point numbers.
There are many operations for numbers, e.g. multiplication *, division /, addition +,
subtraction -, and so on.
Besides regular numbers, there are so-called “special numeric values” which also belong to
this data type: Infinity, -Infinity and NaN.
Mrs PEWAHO 9
ISTAMA HND CGWD1/ SWE1
alert( 1 / 0 ); // Infinity
Doing maths is “safe” in JavaScript. We can do anything: divide by zero, treat non-numeric
strings as numbers, etc.
The script will never stop with a fatal error (“die”). At worst, we’ll get NaN as the result.
Special numeric values formally belong to the “number” type. Of course they are not numbers
in the common sense of this word.
BigInt
In JavaScript, the “number” type cannot represent integer values larger than (253-1) (that’s
9007199254740991), or less than -(253-1) for negatives. It’s a technical limitation caused by
their internal representation.
For most purposes that’s quite enough, but sometimes we need really big numbers, e.g. for
cryptography or microsecond-precision timestamps.
BigInt type was recently added to the language to represent integers of arbitrary length.
Mrs PEWAHO 10
ISTAMA HND CGWD1/ SWE1
As BigInt numbers are rarely needed, we don’t cover them here, but devoted them a separate
Compatibility issues
String
A string in JavaScript must be surrounded by quotes.
Double and single quotes are “simple” quotes. There’s practically no difference between them
in JavaScript.
Backticks are “extended functionality” quotes. They allow us to embed variables and
expressions into a string by wrapping them in ${…}, for example:
// embed a variable
alert( `Hello, ${name}!` ); // Hello, John!
// embed an expression
alert( `the result is ${1 + 2}` ); // the result is 3
The expression inside ${…} is evaluated and the result becomes a part of the string. We can
put anything in there: a variable like name or an arithmetical expression like 1 + 2 or
something more complex.
Please note that this can only be done in backticks. Other quotes don’t have this embedding
functionality!
alert( "the result is ${1 + 2}" ); // the result is ${1 + 2} (double quotes
do nothing)
In some languages, there is a special “character” type for a single character. For example, in
the C language and in Java it is called “char”.
In JavaScript, there is no such type. There’s only one type: string. A string may consist of
zero characters (be empty), one character or many of them.
Mrs PEWAHO 11
ISTAMA HND CGWD1/ SWE1
This type is commonly used to store yes/no values: true means “yes, correct”, and false
means “no, incorrect”.
For instance:
It’s just a special value which represents “nothing”, “empty” or “value unknown”.
let age;
All other types are called “primitive” because their values can contain only a single thing (be
it a string or a number or whatever). In contrast, objects are used to store collections of data
and more complex entities.
The symbol type is used to create unique identifiers for objects. We have to mention it here
for the sake of completeness, but also postpone the details till we know objects.
Mrs PEWAHO 12
ISTAMA HND CGWD1/ SWE1
typeof 0 // "number"
Summary
There are 8 basic data types in JavaScript.
number for numbers of any kind: integer or floating-point, integers are limited by
±(253-1).
bigint is for integer numbers of arbitrary length.
string for strings. A string may have zero or more characters, there’s no separate
single-character type.
boolean for true/false.
null for unknown values – a standalone type that has a single value null.
undefined for unassigned values – a standalone type that has a single value
undefined.
object for more complex data structures.
symbol for unique identifiers.
Tasks
String quotes
importance: 5
Mrs PEWAHO 13
ISTAMA HND CGWD1/ SWE1
alert
This one we’ve seen already. It shows a message and waits for the user to press “OK”.
For example:
alert("Hello");
The mini-window with the message is called a modal window. The word “modal” means that
the visitor can’t interact with the rest of the page, press other buttons, etc, until they have dealt
with the window. In this case – until they press “OK”.
prompt
The function prompt accepts two arguments:
It shows a modal window with a text message, an input field for the visitor, and the buttons
OK/Cancel.
title
The text to show the visitor.
default
An optional second parameter, the initial value for the input field.
The square brackets in syntax [...]
The square brackets around default in the syntax above denote that the parameter is
optional, not required.
The visitor can type something in the prompt input field and press OK. Then we get that text
in the result. Or they can cancel the input by pressing Cancel or hitting the Esc key, then we
get null as the result.
The call to prompt returns the text from the input field or null if the input was canceled.
Mrs PEWAHO 14
ISTAMA HND CGWD1/ SWE1
For instance:
alert(`You are ${age} years old!`); // You are 100 years old!
The second parameter is optional, but if we don’t supply it, Internet Explorer will insert the
text "undefined" into the prompt.
So, for prompts to look good in IE, we recommend always providing the second argument:
confirm
The syntax:
result = confirm(question);
The function confirm shows a modal window with a question and two buttons: OK and
Cancel.
For example:
Summary
We covered 3 browser-specific functions to interact with visitors:
alert
shows a message.
prompt
shows a message asking the user to input text. It returns the text or, if Cancel button or
Esc is clicked, null.
confirm
shows a message and waits for the user to press “OK” or “Cancel”. It returns true for
OK and false for Cancel/Esc.
All these methods are modal: they pause script execution and don’t allow the visitor to
interact with the rest of the page until the window has been dismissed.
Mrs PEWAHO 15
ISTAMA HND CGWD1/ SWE1
1. The exact location of the modal window is determined by the browser. Usually, it’s in
the center.
2. The exact look of the window also depends on the browser. We can’t modify it.
That is the price for simplicity. There are other ways to show nicer windows and richer
interaction with the visitor, but if “bells and whistles” do not matter much, these methods
work just fine.
Tasks
A simple page
importance: 4
let x = 1;
x = -x;
alert( x ); // -1, unary negation was applied
An operator is binary if it has two operands. The same minus exists in binary form as well:
let x = 1, y = 3;
alert( y - x ); // 2, binary minus subtracts values
Formally, in the examples above we have two different operators that share the same
symbol: the negation operator, a unary operator that reverses the sign, and the
subtraction operator, a binary operator that subtracts one number from another.
Maths
The following math operations are supported:
Mrs PEWAHO 16
ISTAMA HND CGWD1/ SWE1
Addition +,
Subtraction -,
Multiplication *,
Division /,
Remainder %,
Exponentiation **.
The first four are straightforward, while % and ** need a few words about them.
Remainder %
For instance:
Exponentiation **
For instance:
alert( 2 ** 2 ); // 2² = 4
alert( 2 ** 3 ); // 2³ = 8
alert( 2 ** 4 ); // 2⁴ = 16
Just like in maths, the exponentiation operator is defined for non-integer numbers as well.
Note that if any of the operands is a string, then the other one is converted to a string too.
Mrs PEWAHO 17
ISTAMA HND CGWD1/ SWE1
For example:
See, it doesn’t matter whether the first operand is a string or the second one.
Here, operators work one after another. The first + sums two numbers, so it returns 4, then the
next + adds the string 1 to it, so it’s like 4 + '1' = '41'.
Here, the first operand is a string, the compiler treats the other two operands as strings too.
The 2 gets concatenated to '1', so it’s like '1' + 2 = "12" and "12" + 2 = "122".
The binary + is the only operator that supports strings in such a way. Other arithmetic
operators work only with numbers and always convert their operands to numbers.
Assignment
Let’s note that an assignment = is also an operator.
when we assign a variable, like x = 2 * 2 + 1, the calculations are done first and then the =
is evaluated, storing the result in x.
let x = 2 * 2 + 1;
alert( x ); // 5
The fact of = being an operator, not a “magical” language construct has an interesting
implication.
All operators in JavaScript return a value. That’s obvious for + and -, but also true for =.
The call x = value writes the value into x and then returns it.
let a = 1;
let b = 2;
Mrs PEWAHO 18
ISTAMA HND CGWD1/ SWE1
let c = 3 - (a = b + 1);
alert( a ); // 3
alert( c ); // 0
In the example above, the result of expression (a = b + 1) is the value which was assigned
to a (that is 3). It is then used for further evaluations.
Chaining assignments
let a, b, c;
a = b = c = 2 + 2;
alert( a ); // 4
alert( b ); // 4
alert( c ); // 4
Chained assignments evaluate from right to left. First, the rightmost expression 2 + 2 is
evaluated and then assigned to the variables on the left: c, b and a. At the end, all the
variables share a single value.
Once again, for the purposes of readability it’s better to split such code into few lines:
c = 2 + 2;
b = c;
a = c;
Modify-in-place
We often need to apply an operator to a variable and store the new result in that same
variable.
For example:
let n = 2;
n = n + 5;
n = n * 2;
let n = 2;
n += 5; // now n = 7 (same as n = n + 5)
n *= 2; // now n = 14 (same as n = n * 2)
alert( n ); // 14
Short “modify-and-assign” operators exist for all arithmetical and bitwise operators: /=, -=,
etc.
Mrs PEWAHO 19
ISTAMA HND CGWD1/ SWE1
Such operators have the same precedence as a normal assignment, so they run after most other
calculations:
let n = 2;
n *= 3 + 5;
Increment/decrement
Increasing or decreasing a number by one is among the most common numerical operations.
let counter = 2;
counter++; // works the same as counter = counter + 1, but is
shorter
alert( counter ); // 3
let counter = 2;
counter--; // works the same as counter = counter - 1, but is
shorter
alert( counter ); // 1
To do that, we can use the if statement and the conditional operator ?, that’s also called a
“question mark” operator.
For example:
In the example above, the condition is a simple equality check (year == 2015), but it can be
much more complex.
Mrs PEWAHO 20
ISTAMA HND CGWD1/ SWE1
If we want to execute more than one statement, we have to wrap our code block inside curly
braces:
if (year == 2015) {
alert( "That's correct!" );
alert( "You're so smart!" );
}
We recommend wrapping your code block with curly braces {} every time you use an if
statement, even if there is only one statement to execute. Doing so improves readability.
For example:
if (year == 2015) {
alert( 'You guessed it right!' );
} else {
alert( 'How can you be so wrong?' ); // any value except 2015
}
For example:
In the code above, JavaScript first checks year < 2015. If that is falsy, it goes to the next
condition year > 2015. If that is also falsy, it shows the last alert.
Mrs PEWAHO 21
ISTAMA HND CGWD1/ SWE1
For instance:
let accessAllowed;
let age = prompt('How old are you?', '');
alert(accessAllowed);
The so-called “conditional” or “question mark” operator lets us do that in a shorter and
simpler way.
The operator is represented by a question mark ?. Sometimes it’s called “ternary”, because the
operator has three operands. It is actually the one and only operator in JavaScript which has
that many.
The condition is evaluated: if it’s truthy then value1 is returned, otherwise – value2.
For example:
Technically, we can omit the parentheses around age > 18. The question mark operator has a
low precedence, so it executes after the comparison >.
But parentheses make the code more readable, so we recommend using them.
Please note:
In the example above, you can avoid using the question mark operator because the
comparison itself returns true/false:
// the same
let accessAllowed = age > 18;
Multiple ‘?’
A sequence of question mark operators ? can return a value that depends on more than one
condition.
Mrs PEWAHO 22
ISTAMA HND CGWD1/ SWE1
For instance:
alert( message );
It may be difficult at first to grasp what’s going on. But after a closer look, we can see that it’s
just an ordinary sequence of tests:
if (age < 3) {
message = 'Hi, baby!';
} else if (age < 18) {
message = 'Hello!';
} else if (age < 100) {
message = 'Greetings!';
} else {
message = 'What an unusual age!';
}
(company == 'Netscape') ?
alert('Right!') : alert('Wrong.');
Depending on the condition company == 'Netscape', either the first or the second
expression after the ? gets executed and shows an alert.
We don’t assign a result to a variable here. Instead, we execute different code depending on
the condition.
It’s not recommended to use the question mark operator in this way.
The notation is shorter than the equivalent if statement, which appeals to some programmers.
But it is less readable.
Mrs PEWAHO 23
ISTAMA HND CGWD1/ SWE1
if (company == 'Netscape') {
alert('Right!');
} else {
alert('Wrong.');
}
Our eyes scan the code vertically. Code blocks which span several lines are easier to
understand than a long, horizontal instruction set.
The purpose of the question mark operator ? is to return one value or another depending on its
condition. Please use it for exactly that. Use if when you need to execute different branches
of code.
Tasks
if (a string with zero)
importance: 5
if ("0") {
alert( 'Hello' );
}
importance: 2
Using the if..else construct, write the code which asks: ‘What is the “official” name of
JavaScript?’
If the visitor enters “ECMAScript”, then output “Right!”, otherwise – output: “You don’t
know? ECMAScript!”
importance: 2
Using if..else, write the code which gets a number via prompt and then shows in alert:
importance: 5
let result;
if (a + b < 4) {
result = 'Below';
} else {
result = 'Over';
}
importance: 5
For readability, it’s recommended to split the code into multiple lines.
let message;
if (login == 'Employee') {
message = 'Hello';
} else if (login == 'Director') {
message = 'Greetings';
} else if (login == '') {
message = 'No login';
} else {
message = '';
}
For example, outputting goods from a list one after another or just running the same code for
each number from 1 to 10.
while (condition) {
// code
// so-called "loop body"
}
While the condition is truthy, the code from the loop body is executed.
Mrs PEWAHO 25
ISTAMA HND CGWD1/ SWE1
let i = 0;
while (i < 3) { // shows 0, then 1, then 2
alert( i );
i++;
}
A single execution of the loop body is called an iteration. The loop in the example above
makes three iterations.
If i++ was missing from the example above, the loop would repeat (in theory) forever. In
practice, the browser provides ways to stop such loops, and in server-side JavaScript, we can
kill the process.
Any expression or variable can be a loop condition, not just comparisons: the condition is
evaluated and converted to a boolean by while.
let i = 3;
while (i) { // when i becomes 0, the condition becomes falsy, and the loop
stops
alert( i );
i--;
}
Curly braces are not required for a single-line body
If the loop body has a single statement, we can omit the curly braces {…}:
let i = 3;
while (i) alert(i--);
do {
// loop body
} while (condition);
The loop will first execute the body, then check the condition, and, while it’s truthy, execute it
again and again.
For example:
let i = 0;
do {
alert( i );
i++;
} while (i < 3);
Mrs PEWAHO 26
ISTAMA HND CGWD1/ SWE1
This form of syntax should only be used when you want the body of the loop to execute at
least once regardless of the condition being truthy. Usually, the other form is preferred:
while(…) {…}.
Let’s learn the meaning of these parts by example. The loop below runs alert(i) for i from
0 up to (but not including) 3:
part
begin let i = 0 Executes once upon entering the loop.
condition i < 3 Checked before every loop iteration. If false, the loop stops.
body alert(i) Runs again and again while the condition is truthy.
step i++ Executes after the body on each iteration.
Run begin
→ (if condition → run body and run step)
→ (if condition → run body and run step)
→ (if condition → run body and run step)
→ ...
That is, begin executes once, and then it iterates: after each condition test, body and step
are executed.
If you are new to loops, it could help to go back to the example and reproduce how it runs
step-by-step on a piece of paper.
// run begin
let i = 0
// if condition → run body and run step
if (i < 3) { alert(i); i++ }
// if condition → run body and run step
if (i < 3) { alert(i); i++ }
Mrs PEWAHO 27
ISTAMA HND CGWD1/ SWE1
Here, the “counter” variable i is declared right in the loop. This is called an “inline” variable
declaration. Such variables are visible only inside the loop.
let i = 0;
Skipping parts
For example, we can omit begin if we don’t need to do anything at the loop start.
Like here:
let i = 0;
for (;;) {
// repeats without limits
}
Please note that the two for semicolons ; must be present. Otherwise, there would be a
syntax error.
Mrs PEWAHO 28
ISTAMA HND CGWD1/ SWE1
But we can force the exit at any time using the special break directive.
For example, the loop below asks the user for a series of numbers, “breaking” when no
number is entered:
let sum = 0;
while (true) {
sum += value;
}
alert( 'Sum: ' + sum );
The break directive is activated at the line (*) if the user enters an empty line or cancels the
input. It stops the loop immediately, passing control to the first line after the loop. Namely,
alert.
Summary
We covered 3 types of loops:
Tasks
Last loop value
importance: 3
let i = 3;
while (i) {
alert( i-- );
}
importance: 4
Mrs PEWAHO 29
ISTAMA HND CGWD1/ SWE1
For every loop iteration, write down which value it outputs and then compare it with the
solution.
let i = 0;
while (++i < 5) alert( i );
2. let i = 0;
3. while (i++ < 5) alert( i );
reference: https://javascript.info
Mrs PEWAHO 30