0% found this document useful (0 votes)
7 views30 pages

javascript student

JavaScript is a programming language used in HTML pages, allowing dynamic modification and user interaction without server communication. It utilizes the <script> tag for code insertion, supports variable declarations with let, var, and const, and allows for various data types including numbers and strings. The document also emphasizes the importance of clear variable naming and provides guidelines for writing and organizing JavaScript code.

Uploaded by

dihoncho.pro
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views30 pages

javascript student

JavaScript is a programming language used in HTML pages, allowing dynamic modification and user interaction without server communication. It utilizes the <script> tag for code insertion, supports variable declarations with let, var, and const, and allows for various data types including numbers and strings. The document also emphasizes the importance of clear variable naming and provides guidelines for writing and organizing JavaScript code.

Uploaded by

dihoncho.pro
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

ISTAMA HND CGWD1/ SWE1

JAVASCRIPT

What is JavaScript?

• JavaScript is a programming language for use in


HTML pages
• Invented in 1995 at Netscape Corporation
(LiveScript)
• JavaScript has nothing to do with Java
• JavaScript programs are run by an interpreter built

into the user's web browser (not on the server)

What can JavaScript Do?


• JavaScript can dynamically modify an HTML page
• JavaScript can react to user input
• JavaScript can validate user input
• JavaScript can be used to create cookies (yum!)
• JavaScript is a full-featured programming language
• JavaScript user interaction does not require any communication with the server

The “script” tag

JavaScript programs can be inserted almost anywhere into an HTML document using the
<script> tag.

For instance:

<!DOCTYPE HTML>
<html>

<body>

<p>Before the script...</p>

<script>
alert( 'Hello, world!' );
</script>

<p>...After the script.</p>

</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 type attribute: <script type=…>

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.

The language attribute: <script language=…>

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.

Comments before and after scripts.

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 files are attached to HTML with the src attribute:

<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.

We can give a full URL as well. For instance:

<script
src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></
script>

To attach several scripts, use multiple tags:

<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.

If src is set, the script content is ignored.

A single <script> tag can’t have both the src attribute and code inside.

This won’t work:

<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.

The example above can be split into two scripts to work:

<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.

For example, here we split “Hello World” into two alerts:

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.

This would also work:

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.

We recommend putting semicolons between statements even if they are separated by


newlines. This rule is widely adopted by the community

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.

One-line comments start with two forward slash characters //.

The rest of the line is a comment. It may occupy a full line of its own or follow a statement.

Like here:

// This comment occupies a line of its own


alert('Hello');

alert('World'); // This comment follows the statement

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:

/* An example with two messages.


This is a multiline comment.
*/
alert('Hello');
alert('World');

The content of comments is ignored, so if we put code inside /* … */, it won’t execute.

Please, don’t hesitate to comment your code.

Variables

A variable is a “named storage” for data. We can use variables to store goodies, visitors, and
other data.

To create a variable in JavaScript, use the let keyword.

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;

message = 'Hello'; // store the string 'Hello' in the variable named


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!';

alert(message); // shows the variable content

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!

We can also declare multiple variables in one line:

let user = 'John', age = 25, message = 'Hello';

For the sake of better readability, please use a single line per variable.

The multiline variant is a bit longer, but easier to read:


Mrs PEWAHO 5
ISTAMA HND CGWD1/ SWE1

let user = 'John';


let age = 25;
let message = 'Hello';

var instead of let

In older scripts, you may also find another keyword: var instead of let:

var message = 'Hello';

The var keyword is almost the same as let. It also declares a variable, but in a slightly
different, “old-school” way.

We can also change it as many times as we want:

let message;

message = 'Hello!';

message = 'World!'; // value changed

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 hello = 'Hello world!';

let message;

// copy 'Hello world' from hello into message


message = hello;

// now two variables hold the same data


alert(hello); // Hello world!
alert(message); // Hello world!

A variable should be declared only once.

A repeated declaration of the same variable is an error:

let message = "This";

// repeated 'let' leads to an error


let message = "That"; // SyntaxError: 'message' has already been declared

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

There are two limitations on variable names in JavaScript:

1. The name must contain only letters, digits, or the symbols $ and _.
2. The first character must not be a digit.

Examples of valid names:

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.

These names are valid:

let $ = 1; // declared a variable with the name "$"


let _ = 2; // and now a variable with the name "_"

alert($ + _); // 3

Examples of incorrect variable names:

let 1a; // cannot start with a digit

let my-name; // hyphens '-' aren't allowed in the name

Case matters

Variables named apple and APPLE are two different variables.

Non-Latin letters are allowed, but not recommended

It is possible to use any language, including Cyrillic letters or even hieroglyphs, like this:

let имя = '...';


let 我 = '...';

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.

For example: let, class, return, and function are reserved.

The code below gives a syntax error:

Mrs PEWAHO 7
ISTAMA HND CGWD1/ SWE1

let let = 5; // can't name a variable "let", error!


let return = 5; // also can't name it "return", error!

Constants
To declare a constant (unchanging) variable, use const instead of let:

const myBirthday = '18.04.1982';

Variables declared using const are called “constants”. They cannot be reassigned. An attempt
to do so would cause an error:

const myBirthday = '18.04.1982';

myBirthday = '01.01.2001'; // error, can't reassign the constant!

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.

Name things right


Talking about variables, there’s one more extremely important thing.

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.

Some good-to-follow rules are:

 Use human-readable names like userName or shoppingCart.


 Stay away from abbreviations or short names like a, b, c, unless you really know what
you’re doing.
 Make names maximally descriptive and concise. Examples of bad names are data and
value. Such names say nothing. It’s only okay to use them if the context of the code
makes it exceptionally obvious which data or value the variable is referencing.
 Agree on terms within your team and in your own mind. If a site visitor is called a
“user” then we should name related variables currentUser or newUser instead of
currentVisitor or newManInTown.

Mrs PEWAHO 8
ISTAMA HND CGWD1/ SWE1

Summary
We can declare variables to store data by using the var, let, or const keywords.

 let – is a modern variable declaration.


 var – is an old-school variable declaration. Normally we don’t use it at all, but we’ll
cover subtle differences from let in the chapter The old "var", just in case you need
them.
 const – is like let, but the value of the variable can’t be changed.

Variables should be named in a way that allows us to easily understand what’s inside them.

Tasks
Working with variables

importance: 2

1. Declare two variables: admin and name.


2. Assign the value "John" to name.
3. Copy the value from name to admin.
4. Show the value of admin using alert (must output “John”).

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

 Infinity represents the mathematical Infinity ∞. It is a special value that’s greater


than any number.

We can get it as a result of division by zero:

alert( 1 / 0 ); // Infinity

Or just reference it directly:

 alert( Infinity ); // Infinity

 NaN represents a computational error. It is a result of an incorrect or an undefined


mathematical operation, for instance:

alert( "not a number" / 2 ); // NaN, such division is erroneous

NaN is sticky. Any further mathematical operation on NaN returns NaN:

 alert( NaN + 1 ); // NaN


 alert( 3 * NaN ); // NaN
 alert( "not a number" / 2 - 1 ); // NaN

So, if there’s a NaN somewhere in a mathematical expression, it propagates to the


whole result (there’s only one exception to that: NaN ** 0 is 1).

Mathematical operations are safe

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.

A BigInt value is created by appending n to the end of an integer:

// the "n" at the end means it's a BigInt


const bigInt = 1234567890123456789012345678901234567890n;

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

Right now, BigInt is supported in Firefox/Chrome/Edge/Safari, but not in IE.

String
A string in JavaScript must be surrounded by quotes.

let str = "Hello";


let str2 = 'Single quotes are ok too';
let phrase = `can embed another ${str}`;

In JavaScript, there are 3 types of quotes.

1. Double quotes: "Hello".


2. Single quotes: 'Hello'.
3. Backticks: `Hello`.

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:

let name = "John";

// 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)

There is no character type.

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

Boolean (logical type)


The boolean type has only two values: true and false.

This type is commonly used to store yes/no values: true means “yes, correct”, and false
means “no, incorrect”.

For instance:

let nameFieldChecked = true; // yes, name field is checked


let ageFieldChecked = false; // no, age field is not checked

Boolean values also come as a result of comparisons:

let isGreater = 4 > 1;

alert( isGreater ); // true (the comparison result is "yes")

The “null” value


It forms a separate type of its own which contains only the null value:

let age = null;

It’s just a special value which represents “nothing”, “empty” or “value unknown”.

The code above states that age is unknown.

The “undefined” value


The special value undefined also stands apart. It makes a type of its own, just like null.

The meaning of undefined is “value is not assigned”.

If a variable is declared, but not assigned, then its value is undefined:

let age;

alert(age); // shows "undefined"

Objects and Symbols


The object type is special.

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

The typeof operator


The typeof operator returns the type of the argument. It’s useful when we want to process
values of different types differently or just want to do a quick check.

A call to typeof x returns a string with the type name:

typeof undefined // "undefined"

typeof 0 // "number"

typeof 10n // "bigint"

typeof true // "boolean"

typeof "foo" // "string"

typeof Symbol("id") // "symbol"

typeof Math // "object" (1)

typeof null // "object" (2)

typeof alert // "function" (3)

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.

The typeof operator allows us to see which type is stored in a variable.

Tasks
String quotes

importance: 5

What is the output of the script?

Mrs PEWAHO 13
ISTAMA HND CGWD1/ SWE1

let name = "Ilya";

alert( `hello ${1}` ); // ?

alert( `hello ${"name"}` ); // ?

alert( `hello ${name}` ); // ?

Interaction: alert, prompt, confirm


As we’ll be using the browser as our demo environment, let’s see a couple of functions to
interact with the user: alert, prompt and confirm.

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:

result = prompt(title, [default]);

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:

let age = prompt('How old are you?', 100);

alert(`You are ${age} years old!`); // You are 100 years old!

In IE: always supply a default

The second parameter is optional, but if we don’t supply it, Internet Explorer will insert the
text "undefined" into the prompt.

Run this code in Internet Explorer to see:

let test = prompt("Test");

So, for prompts to look good in IE, we recommend always providing the second argument:

let test = prompt("Test", ''); // <-- for IE

confirm
The syntax:

result = confirm(question);

The function confirm shows a modal window with a question and two buttons: OK and
Cancel.

The result is true if OK is pressed and false otherwise.

For example:

let isBoss = confirm("Are you the boss?");

alert( isBoss ); // true if OK is pressed

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

There are two limitations shared by all the methods above:

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

Create a web-page that asks for a name and outputs it.

Basic operators, maths


We know many operators from school. They are things like addition +, multiplication *,
subtraction -, and so on.

Terms: “unary”, “binary”, “operand”


 An operand – is what operators are applied to. For instance, in the multiplication of 5
* 2 there are two operands: the left operand is 5 and the right operand is 2.
Sometimes, people call these “arguments” instead of “operands”.
 An operator is unary if it has a single operand. For example, the unary negation -
reverses the sign of a number:

 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 %

The remainder operator %, despite its appearance, is not related to percents.

The result of a % b is the remainder of the integer division of a by b.

For instance:

alert( 5 % 2 ); // 1, a remainder of 5 divided by 2


alert( 8 % 3 ); // 2, a remainder of 8 divided by 3

Exponentiation **

The exponentiation operator a ** b raises a to the power of b.

In school maths, we write that as ab.

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.

For example, a square root is an exponentiation by ½:

alert( 4 ** (1/2) ); // 2 (power of 1/2 is the same as a square root)


alert( 8 ** (1/3) ); // 2 (power of 1/3 is the same as a cubic root)

String concatenation with binary +


Let’s meet features of JavaScript operators that are beyond school arithmetics.

Usually, the plus operator + sums numbers.

But, if the binary + is applied to strings, it merges (concatenates) them:

let s = "my" + "string";


alert(s); // mystring

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:

alert( '1' + 2 ); // "12"


alert( 2 + '1' ); // "21"

See, it doesn’t matter whether the first operand is a string or the second one.

Here’s a more complex example:

alert(2 + 2 + '1' ); // "41" and not "221"

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'.

alert('1' + 2 + 2); // "122" and not "14"

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.

Here’s the demo for subtraction and division:

alert( 6 - '2' ); // 4, converts '2' to a number


alert( '6' / '2' ); // 3, converts both 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

Assignment = returns a value

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.

Here’s a demo that uses an assignment as part of a more complex expression:

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

Another interesting feature is the ability to chain 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;

That’s easier to read, especially when eye-scanning the code fast.

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;

This notation can be shortened using the operators += and *=:

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;

alert( n ); // 16 (right part evaluated first, same as n *= 8)

Increment/decrement
Increasing or decreasing a number by one is among the most common numerical operations.

So, there are special operators for it:

 Increment ++ increases a variable by 1:

 let counter = 2;
counter++; // works the same as counter = counter + 1, but is
shorter
alert( counter ); // 3

 Decrement -- decreases a variable by 1:

 let counter = 2;
 counter--; // works the same as counter = counter - 1, but is
shorter
 alert( counter ); // 1

Conditional branching: if, '?'


Sometimes, we need to perform different actions based on different conditions.

To do that, we can use the if statement and the conditional operator ?, that’s also called a
“question mark” operator.

The “if” statement


The if(...) statement evaluates a condition in parentheses and, if the result is true,
executes a block of code.

For example:

let year = prompt('In which year was ECMAScript-2015 specification


published?', '');

if (year == 2015) alert( 'You are right!' );

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.

The “else” clause


The if statement may contain an optional “else” block. It executes when the condition is
falsy.

For example:

let year = prompt('In which year was the ECMAScript-2015 specification


published?', '');

if (year == 2015) {
alert( 'You guessed it right!' );
} else {
alert( 'How can you be so wrong?' ); // any value except 2015
}

Several conditions: “else if”


Sometimes, we’d like to test several variants of a condition. The else if clause lets us do
that.

For example:

let year = prompt('In which year was the ECMAScript-2015 specification


published?', '');

if (year < 2015) {


alert( 'Too early...' );
} else if (year > 2015) {
alert( 'Too late' );
} else {
alert( 'Exactly!' );
}

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.

There can be more else if blocks. The final else is optional.

Conditional operator ‘?’


Sometimes, we need to assign a variable depending on a condition.

Mrs PEWAHO 21
ISTAMA HND CGWD1/ SWE1

For instance:

let accessAllowed;
let age = prompt('How old are you?', '');

if (age > 18) {


accessAllowed = true;
} else {
accessAllowed = false;
}

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 syntax is:

let result = condition ? value1 : value2;

The condition is evaluated: if it’s truthy then value1 is returned, otherwise – value2.

For example:

let accessAllowed = (age > 18) ? true : false;

Technically, we can omit the parentheses around age > 18. The question mark operator has a
low precedence, so it executes after the comparison >.

This example will do the same thing as the previous one:

// the comparison operator "age > 18" executes first anyway


// (no need to wrap it into parentheses)
let accessAllowed = age > 18 ? true : false;

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:

let age = prompt('age?', 18);

let message = (age < 3) ? 'Hi, baby!' :


(age < 18) ? 'Hello!' :
(age < 100) ? 'Greetings!' :
'What an unusual age!';

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:

1. The first question mark checks whether age < 3.


2. If true – it returns 'Hi, baby!'. Otherwise, it continues to the expression after the
colon ‘":"’, checking age < 18.
3. If that’s true – it returns 'Hello!'. Otherwise, it continues to the expression after the
next colon ‘":"’, checking age < 100.
4. If that’s true – it returns 'Greetings!'. Otherwise, it continues to the expression after
the last colon ‘":"’, returning 'What an unusual age!'.

Here’s how this looks using if..else:

if (age < 3) {
message = 'Hi, baby!';
} else if (age < 18) {
message = 'Hello!';
} else if (age < 100) {
message = 'Greetings!';
} else {
message = 'What an unusual age!';
}

Non-traditional use of ‘?’


Sometimes the question mark ? is used as a replacement for if:

let company = prompt('Which company created JavaScript?', '');

(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

Here is the same code using if for comparison:

let company = prompt('Which company created JavaScript?', '');

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

Will alert be shown?

if ("0") {
alert( 'Hello' );
}

The name of JavaScript

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!”

Show the sign

importance: 2

Using if..else, write the code which gets a number via prompt and then shows in alert:

 1, if the value is greater than zero,


 -1, if less than zero,
 0, if equals zero.

In this task we assume that the input is always a number.

Demo in new window


Mrs PEWAHO 24
ISTAMA HND CGWD1/ SWE1

Rewrite 'if' into '?'

importance: 5

Rewrite this if using the conditional operator '?':

let result;

if (a + b < 4) {
result = 'Below';
} else {
result = 'Over';
}

Rewrite 'if..else' into '?'

importance: 5

Rewrite if..else using multiple ternary operators '?'.

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 = '';
}

Loops: while and for


We often need to repeat actions.

For example, outputting goods from a list one after another or just running the same code for
each number from 1 to 10.

Loops are a way to repeat the same code multiple times.

The “while” loop


The while loop has the following syntax:

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

For instance, the loop below outputs i while i < 3:

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.

For instance, a shorter way to write while (i != 0) is while (i):

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--);

The “do…while” loop


The condition check can be moved below the loop body using the do..while syntax:

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(…) {…}.

The “for” loop


The for loop is more complex, but it’s also the most commonly used loop.

It looks like this:

for (begin; condition; step) {


// ... loop body ...
}

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:

for (let i = 0; i < 3; i++) { // shows 0, then 1, then 2


alert(i);
}

Let’s examine the for statement part-by-part:

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.

The general loop algorithm works like this:

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.

Here’s exactly what happens in our case:

// for (let i = 0; i < 3; i++) alert(i)

// 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

// if condition → run body and run step


if (i < 3) { alert(i); i++ }
// ...finish, because now i == 3
Inline variable declaration

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.

for (let i = 0; i < 3; i++) {


alert(i); // 0, 1, 2
}
alert(i); // error, no such variable

Instead of defining a variable, we could use an existing one:

let i = 0;

for (i = 0; i < 3; i++) { // use an existing variable


alert(i); // 0, 1, 2
}

alert(i); // 3, visible, because declared outside of the loop

Skipping parts

Any part of for can be skipped.

For example, we can omit begin if we don’t need to do anything at the loop start.

Like here:

let i = 0; // we have i already declared and assigned

for (; i < 3; i++) { // no need for "begin"


alert( i ); // 0, 1, 2
}

We can also remove the step part:

let i = 0;

for (; i < 3;) {


alert( i++ );
}

This makes the loop identical to while (i < 3).

We can actually remove everything, creating an infinite loop:

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

Breaking the loop


Normally, a loop exits when its condition becomes falsy.

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) {

let value = +prompt("Enter a number", '');

if (!value) break; // (*)

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:

 while – The condition is checked before each iteration.


 do..while – The condition is checked after each iteration.
 for (;;) – The condition is checked before each iteration, additional settings
available.

Tasks
Last loop value

importance: 3

What is the last value alerted by this code? Why?

let i = 3;

while (i) {
alert( i-- );
}

Which values does the while loop show?

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.

Both loops alert the same values, or not?

1. The prefix form ++i:

 let i = 0;
while (++i < 5) alert( i );

 The postfix form i++

2. let i = 0;
3. while (i++ < 5) alert( i );

reference: https://javascript.info

Mrs PEWAHO 30

You might also like