0% found this document useful (0 votes)
24K views

The "Script" Tag: Alert ('Hello, World!')

The document discusses JavaScript fundamentals including: 1) The <script> tag is used to insert JavaScript code into HTML and contains code that is executed when the browser processes the tag. 2) JavaScript programs can be placed in external .js files and linked using the src attribute of the <script> tag. 3) The "use strict" directive enables strict mode for modern JavaScript and must be placed at the top of scripts or functions to take effect. It helps avoid bugs by making "mistakes" errors.

Uploaded by

Jaja Arcenal
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24K views

The "Script" Tag: Alert ('Hello, World!')

The document discusses JavaScript fundamentals including: 1) The <script> tag is used to insert JavaScript code into HTML and contains code that is executed when the browser processes the tag. 2) JavaScript programs can be placed in external .js files and linked using the src attribute of the <script> tag. 3) The "use strict" directive enables strict mode for modern JavaScript and must be placed at the top of scripts or functions to take effect. It helps avoid bugs by making "mistakes" errors.

Uploaded by

Jaja Arcenal
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 35

JavaScript Fundamentals Page 1 of 35

The “script” tag


 JavaScript programs can be inserted into any part of an HTML document with the help of 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

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,
HTML5, 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>

Lesson 2  jyercia
JavaScript Fundamentals Page 2 of 35

This trick isn’t used in modern JavaScript. These comments hid 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 file (from the site root).

You can also provide a relative path from the current page. For instance, 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/3.2.0/lodash.js"></script>

To attach several scripts, use multiple tags:

<script src="/js/script1.js"></script>
<script src="/js/script2.js"></script>

Note:

 As a rule, only the simplest scripts are put into HTML. More complex ones reside in separate files.
 The benefit of a separate file is that the browser will download it and store it in its cache.
 Other pages that reference the same script will take it from the cache instead of downloading it, so
the file is actually downloaded only once.
 That reduces traffic and makes pages faster.

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

Lesson 2  jyercia
JavaScript Fundamentals Page 3 of 35

Code structure
Statements

 Statements are syntax constructs and commands that perform actions.


 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');
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.

We recommend putting semicolons between statements even if they are separated by newlines. This
rule is widely adopted by the community. Let’s note once again – it is possible to leave out
semicolons most of the time. But it’s safer – especially for a beginner – to use them.

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

Lesson 2  jyercia
JavaScript Fundamentals Page 4 of 35

Multiline comments start with a forward slash and an asterisk /* and end with an asterisk and
a forward slash */.

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.

Sometimes it can be handy to temporarily disable a part of code:

/* Commenting out the code


alert('Hello');
*/
alert('World');

Use hotkeys!

In most editors, a line of code can be commented out by pressing the Ctrl+/ hotkey for a single-line
comment and something like Ctrl+Shift+/ – for multiline comments (select a piece of code and press
the hotkey). For Mac, try Cmd instead of Ctrl.

Nested comments are not supported!

There may not be /*...*/ inside another /*...*/.

Such code will die with an error:

/*
/* nested comment ?!? */
*/
alert( 'World' );

Lesson 2  jyercia
JavaScript Fundamentals Page 5 of 35

The modern mode, "use strict"


For a long time, JavaScript evolved without compatibility issues. New features were added to the
language while old functionality didn’t change.

That had the benefit of never breaking existing code. But the downside was that any mistake or an
imperfect decision made by JavaScript’s creators got stuck in the language forever.

This was the case until 2009 when ECMAScript 5 (ES5) appeared. It added new features to the
language and modified some of the existing ones. To keep the old code working, most modifications
are off by default. You need to explicitly enable them with a special directive: "use strict".

“use strict”

The directive looks like a string: "use strict" or 'use strict'. When it is located at the top of a script, the
whole script works the “modern” way.

For example:

"use strict";

// this code works the modern way


...

We will learn functions (a way to group commands) soon.

Looking ahead, let’s just note that "use strict" can be put at the start of most kinds of functions
instead of the whole script. Doing that enables strict mode in that function only. But usually, people
use it for the whole script.

Ensure that “use strict” is at the top

Please make sure that "use strict" is at the top of your scripts, otherwise strict mode may not be
enabled.

Strict mode isn’t enabled here:

alert("some code");
// "use strict" below is ignored--it must be at the top

"use strict";

// strict mode is not activated

Only comments may appear above "use strict".

There’s no way to cancel use strict

There is no directive like "no use strict" that reverts the engine to old behavior.

Once we enter strict mode, there’s no return.


Lesson 2  jyercia
JavaScript Fundamentals Page 6 of 35

Browser console

For the future, when you use a browser console to test features, please note that it doesn’t use strict
by default.

Sometimes, when use strict makes a difference, you’ll get incorrect results.

You can try to press Shift+Enter to input multiple lines, and put use strict on top, like this:

'use strict'; <Shift+Enter for a newline>


// ...your code
<Enter to run>

It works in most browsers, namely Firefox and Chrome.

If it doesn’t, the most reliable way to ensure use strict would be to input the code into console like
this:

(function() {
'use strict';

// ...your code...
})()

Always “use strict”

1. The "use strict" directive switches the engine to the “modern” mode, changing the behavior
of some built-in features.
2. Strict mode is enabled by placing "use strict" at the top of a script or function. Several
language features, like “classes” and “modules”, enable strict mode automatically.
3. Strict mode is supported by all modern browsers.
4. We recommended always starting scripts with "use strict". All examples in this tutorial
assume strict mode unless (very rarely) specified otherwise.

Variables
Most of the time, a JavaScript application needs to work with information. Here are two examples:
Lesson 2  jyercia
JavaScript Fundamentals Page 7 of 35

1. An online shop – the information might include goods being sold and a shopping cart.
2. A chat application – the information might include users, messages, and much more.

Variables are used to store this information.

A variable

 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 or defines) 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

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

That might seem shorter, but we don’t recommend it. For the sake of better readability, please use a
single line per variable.

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

let user = 'John';


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

Some people also define multiple variables in this multiline style:

let user = 'John',


age = 25,
message = 'Hello';

Lesson 2  jyercia
JavaScript Fundamentals Page 8 of 35

…Or even in the “comma-first” style:

let user = 'John'


, age = 25
, message = 'Hello';

Technically, all these variants do the same thing. So, it’s a matter of personal taste and aesthetics.

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.

There are subtle differences between let and var, but they do not matter for us yet. We’ll cover them
in detail in the chapter The old "var".

Variable naming

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, camelCase 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

Lesson 2  jyercia
JavaScript Fundamentals Page 9 of 35

Variables named apple and AppLE are two different variables.

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:

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


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

An assignment without use strict

Normally, we need to define a variable before using it. But in the old times, it was technically
possible to create a variable by a mere assignment of the value without using let. This still works
now if we don’t put use strict in our scripts to maintain compatibility with old scripts.

// note: no "use strict" in this example

num = 5; // the variable "num" is created if it didn't exist


alert(num); // 5

This is a bad practice and would cause an error in strict mode:

"use strict";
num = 5; // error: num is not defined

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

Uppercase constants

There is a widespread practice to use constants as aliases for difficult-to-remember values that are
known prior to execution.

Such constants are named using capital letters and underscores.

Lesson 2  jyercia
JavaScript Fundamentals Page 10 of 35

For instance, let’s make constants for colors in so-called “web” (hexadecimal) format:

const COLOR_RED = "#F00";


const COLOR_GREEN = "#0F0";
const COLOR_BLUE = "#00F";
const COLOR_ORANGE = "#FF7F00";

// ...when we need to pick a color


let color = COLOR_ORANGE;
alert(color); // #FF7F00

Benefits:

 COLOR_ORANGE is much easier to remember than "#FF7F00".


 It is much easier to mistype "#FF7F00" than COLOR_ORANGE.
 When reading the code, COLOR_ORANGE is much more meaningful than #FF7F00.

When should we use capitals for a constant and when should we name it normally? Let’s make that
clear.

Being a “constant” just means that a variable’s value never changes. But there are constants that are
known prior to execution (like a hexadecimal value for red) and there are constants that are
calculated in run-time, during the execution, but do not change after their initial assignment.

For instance:

const pageLoadTime = /* time taken by a webpage to load */;

The value of pageLoadTime is not known prior to the page load, so it’s named normally. But it’s still
a constant because it doesn’t change after assignment.

In other words, capital-named constants are only used as aliases for “hard-coded” values.

Name things right

A variable name should have a clean, obvious meaning, describe 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.

Lesson 2  jyercia
JavaScript Fundamentals Page 11 of 35

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

Summary

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

 let – is a modern variable declaration. The code must be in strict mode to use let in Chrome (V8).
 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

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

Giving the right name

1. Create a variable with the name of our planet. How would you name such a variable?
2. Create a variable to store the name of a current visitor to a website. How would you name that
variable?

Lesson 2  jyercia
JavaScript Fundamentals Page 12 of 35

Data types
A variable in JavaScript can contain any data. A variable can at one moment be a string and at another be a
number:

// no error
let message = "hello";
message = 123456;

Programming languages that allow such things are called “dynamically typed”, meaning that there are data
types, but variables are not bound to any of them.

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

 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 operation on NaN returns NaN:

alert( "not a number" / 2 + 5 ); // NaN

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

Mathematical operations are safe


Lesson 2  jyercia
JavaScript Fundamentals Page 13 of 35

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

2. A string

A string in JavaScript must be surrounded by quotes.

let str = "Hello";


let str2 = 'Single quotes are ok too';
let phrase = `can embed ${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 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 char.

In JavaScript, there is no such type. There’s only one type: string. A string may consist of only one
character or many of them.

Lesson 2  jyercia
JavaScript Fundamentals Page 14 of 35

3. A 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")

4. The “null” value


The special null value does not belong to any of the types described above.

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

let age = null;

In JavaScript, null is not a “reference to a non-existing object” or a “null pointer” like in some other
languages.

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

The code above states that age is unknown or empty for some reason.

5. 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 x;
alert(x); // shows "undefined"

Technically, it is possible to assign undefined to any variable:

let x = 123;
x = undefined;
alert(x); // "undefined"

…But we don’t recommend doing that. Normally, we use null to assign an “empty” or “unknown” value
to a variable, and we use undefined for checks like seeing if a variable has been assigned.

Lesson 2  jyercia
JavaScript Fundamentals Page 15 of 35

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

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.

It supports two forms of syntax:

1. As an operator: typeof x.
2. As a function: typeof(x).

In other words, it works with parentheses or without them. The result is the same.

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

typeof undefined // "undefined"


typeof 0 // "number"
typeof true // "boolean"
typeof "foo" // "string"
typeof Symbol("id") // "symbol"
typeof Math // "object" (1)
typeof null // "object" (2)
typeof alert // "function" (3)

The last three lines may need additional explanation:

1. Math is a built-in object that provides mathematical operations.


2. The result of typeof null is "object". That’s wrong. It is an officially recognized error in typeof, kept
for compatibility. Of course, null is not an object. It is a special value with a separate type of its own.
So, again, this is an error in the language.
3. The result of typeof alert is "function", because alert is a function of the language. We’ll study
functions in the next chapters where we’ll see that there’s no special “function” type in JavaScript.
Functions belong to the object type. But typeof treats them differently. Formally, it’s incorrect, but
very convenient in practice.

Summary

There are 7 basic data types in JavaScript.

 number for numbers of any kind: integer or floating-point.


 string for strings. A string may have one or more characters, there’s no separate single-character
type.
 boolean for true/false.
Lesson 2  jyercia
JavaScript Fundamentals Page 16 of 35

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

 Two forms: typeof x or typeof(x).


 Returns a string with the name of the type, like "string".
 For null returns "object" – this is an error in the language, it’s not actually an object.

 Tasks
What is the output of the script?
let name = "Ilya";

alert( `hello ${1}` );

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

alert( `hello ${name}` );

Lesson 2  jyercia
JavaScript Fundamentals Page 17 of 35

Type Conversions
Most of the time, operators and functions automatically convert the values given to them to the right
type.

For example, alert automatically converts any value to a string to show it. Mathematical operations
convert values to numbers.

There are also cases when we need to explicitly convert a value to the expected type.

 ToString

String conversion happens when we need the string form of a value.

For example, alert(value) does it to show the value.

We can also call the String(value) function to convert a value to a string:

let value = true;


alert(typeof value); // boolean

value = String(value); // now value is a string "true"


alert(typeof value); // string

String conversion is mostly obvious. A false becomes "false", null becomes "null", etc.

 ToNumber

Numeric conversion happens in mathematical functions and expressions automatically.

For example, when division / is applied to non-numbers:

alert( "6" / "2" ); // 3, strings are converted to numbers

We can use the Number(value) function to explicitly convert a value to a number:

let str = "123";


alert(typeof str); // string

let num = Number(str); // becomes a number 123

alert(typeof num); // number

Explicit conversion is usually required when we read a value from a string-based source like a text form
but expect a number to be entered.

If the string is not a valid number, the result of such a conversion is NaN. For instance:

let age = Number("an arbitrary string instead of a number");

alert(age); // NaN, conversion failed


Lesson 2  jyercia
JavaScript Fundamentals Page 18 of 35

Numeric conversion rules:

Examples:

alert( Number(" 123 ") ); // 123


alert( Number("123z") ); // NaN (error reading a number at "z")
alert( Number(true) ); // 1
alert( Number(false) ); // 0

Please note that null and undefined behave differently here: null becomes zero while undefined becomes
NaN.

Addition ‘+’ concatenates strings

Almost all mathematical operations convert values to numbers. A notable exception is addition +. If one
of the added values is a string, the other one is also converted to a string.

Then, it concatenates (joins) them:

alert( 1 + '2' ); // '12' (string to the right)

alert( '1' + 2 ); // '12' (string to the left)

This only happens when at least one of the arguments is a string. Otherwise, values are converted to
numbers.

 ToBoolean

Boolean conversion is the simplest one.

It happens in logical operations (later we’ll meet condition tests and other similar things) but can also be
performed explicitly with a call to Boolean(value).

The conversion rule:

 Values that are intuitively “empty”, like 0, an empty string, null, undefined, and NaN, become
false.
 Other values become true.

For instance:

Lesson 2  jyercia
JavaScript Fundamentals Page 19 of 35

alert( Boolean(1) ); // true


alert( Boolean(0) ); // false

alert( Boolean("hello") ); // true


alert( Boolean("") ); // false

Please note: the string with zero "0" is true

Some languages (namely PHP) treat "0" as false. But in JavaScript, a non-empty string is always true.

alert( Boolean("0") ); // true


alert( Boolean(" ") ); // spaces, also true (any non-empty string is true)

Summary

The three most widely used type conversions are to string, to number, and to boolean.

a. ToString – Occurs when we output something. Can be performed with String(value). The
conversion to string is usually obvious for primitive values.

b. ToNumber – Occurs in math operations. Can be performed with Number(value).

c. ToBoolean – Occurs in logical operations. Can be performed with Boolean(value).

 Tasks
What are results of these expressions?

1. "" + 1 + 0
2. "" - 1 + 0
3. true + false
4. 6 / "3"
5. "2" * "3"
6. 4 + 5 + "px"
7. "$" + 4 + 5
8. "4" - 2
9. "4px" - 2
10. 7/0
11. " -9 " + 5
12. " -9 " - 5
13. null + 1
14. undefined + 1

Operators

Lesson 2  jyercia
JavaScript Fundamentals Page 20 of 35

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

Before we move on, let’s grasp some common terminology.

 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, we’re talking about two different operators here: the unary negation (single operand:
reverses the sign) and the binary subtraction (two operands: subtracts).

String concatenation, binary +

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 one of the operands is a string, the other one is converted to a string too.

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. The rule is simple: if
either operand is a string, the other one is converted into a string as well.

However, note that operations run from left to right. If there are two numbers followed by a string,
the numbers will be added before being converted to a string:

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

String concatenation and conversion is a special feature of the binary plus +. Other arithmetic
operators work only with numbers and always convert their operands to numbers.

For instance, subtraction and division:

alert( 2 - '1' ); // 1
Lesson 2  jyercia
JavaScript Fundamentals Page 21 of 35

alert( '6' / '2' ); // 3

Numeric conversion, unary +

The plus + exists in two forms: the binary form that we used above and the unary form.

The unary plus or, in other words, the plus operator + applied to a single value, doesn’t do anything
to numbers. But if the operand is not a number, the unary plus converts it into a number.

For example:

// No effect on numbers
let x = 1;
alert( +x ); // 1

let y = -2;
alert( +y ); // -2

// Converts non-numbers
alert( +true ); // 1
alert( +"" ); // 0

It actually does the same thing as Number(...), but is shorter.

The need to convert strings to numbers arises very often. For example, if we are getting values from
HTML form fields, they are usually strings.

What if we want to sum them?

The binary plus would add them as strings:

let apples = "2";


let oranges = "3";

alert( apples + oranges ); // "23", the binary plus concatenates strings

If we want to treat them as numbers, we need to convert and then sum them:

let apples = "2";


let oranges = "3";

// both values converted to numbers before the binary plus


alert( apples + oranges ); // 5

// the longer variant


// alert( Number(apples) + Number(oranges) ); // 5

From a mathematician’s standpoint, the abundance of pluses may seem strange. But from a
programmer’s standpoint, there’s nothing special: unary pluses are applied first, they convert strings
to numbers, and then the binary plus sums them up.

Why are unary pluses applied to values before the binary ones? As we’re going to see, that’s because
of their higher precedence.
Lesson 2  jyercia
JavaScript Fundamentals Page 22 of 35

Operator precedence

If an expression has more than one operator, the execution order is defined by their precedence, or,
in other words, the implicit priority order of operators.

From school, we all know that the multiplication in the expression 1 + 2 * 2 should be calculated
before the addition. That’s exactly the precedence thing. The multiplication is said to have a higher
precedence than the addition.

Parentheses override any precedence, so if we’re not satisfied with the implicit order, we can use
them to change it. For example: (1 + 2) * 2.

There are many operators in JavaScript. Every operator has a corresponding precedence number. The
one with the larger number executes first. If the precedence is the same, the execution order is from
left to right.

Here’s an extract from the precedence table (you don’t need to remember this, but note that unary
operators are higher than corresponding binary ones):

Precedence Name Sign


… … …
16 unary plus +
16 unary negation -
14 multiplication *
14 division /
13 addition +
13 subtraction -
… … …
3 assignment =
… … …

As we can see, the “unary plus” has a priority of 16 which is higher than the 13 of “addition” (binary
plus). That’s why, in the expression "+apples + +oranges", unary pluses work before the addition.

Assignment

Let’s note that an assignment = is also an operator. It is listed in the precedence table with the very
low priority of 3.

That’s why, 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
Lesson 2  jyercia
JavaScript Fundamentals Page 23 of 35

It is possible 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.

The assignment operator "=" returns a value

An operator always returns a value. That’s obvious for most of them like addition + or multiplication
*. But the assignment operator follows this rule too.

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;

let c = 3 - (a = b * 5);

alert( a ); // 3
alert( c ); // 0

In the example above, the result of (a = b + 1) is the value which is assigned to a (that is 3). It is then
used to subtract from 3.

Funny code, isn’t it? We should understand how it works, because sometimes we see it in 3rd-party
libraries, but shouldn’t write anything like that ourselves. Such tricks definitely don’t make code
clearer or readable.

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 is a remainder of 5 divided by 2


alert( 8 % 3 ); // 2 is a remainder of 8 divided by 3
alert( 6 % 3 ); // 0 is a remainder of 6 divided by 3

Exponentiation **

The exponentiation operator ** is a recent addition to the language.


Lesson 2  jyercia
JavaScript Fundamentals Page 24 of 35

For a natural number b, the result of a ** b is a multiplied by itself b times.

For instance:

alert( 2 ** 2 ); // 4 (2 * 2)
alert( 2 ** 3 ); // 8 (2 * 2 * 2)
alert( 2 ** 4 ); // 16 (2 * 2 * 2 * 2)

The operator works for non-integer numbers as well.

For instance:

alert( 4 ** (1/2) ); // 2 (power of 1/2 is the same as a square root, that's maths)
alert( 8 ** (1/3) ); // 2 (power of 1/3 is the same as a cubic root)

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

Important:

Increment/decrement can only be applied to variables. Trying to use it on a value like 5++ will give
an error.

The operators ++ and -- can be placed either before or after a variable.

 When the operator goes after the variable, it is in “postfix form”: counter++.
 The “prefix form” is when the operator goes before the variable: ++counter.

Both of these statements do the same thing: increase counter by 1.

Is there any difference? Yes, but we can only see it if we use the returned value of ++/--.

Let’s clarify. As we know, all operators return a value. Increment/decrement is no exception. The
prefix form returns the new value while the postfix form returns the old value (prior to
increment/decrement).

Lesson 2  jyercia
JavaScript Fundamentals Page 25 of 35

To see the difference, here’s an example:

let counter = 1;
let a = ++counter; // (*)

alert(a); // 2

In the line (*), the prefix form ++counter increments counter and returns the new value, 2. So, the
alert shows 2.

Now, let’s use the postfix form:

let counter = 1;
let a = counter++; // (*) changed ++counter to counter++

alert(a); // 1

In the line (*), the postfix form counter++ also increments counter but returns the old value (prior to
increment). So, the alert shows 1.

To summarize:

 If the result of increment/decrement is not used, there is no difference in which form to use:
 let counter = 0;
 counter++;
 ++counter;
alert( counter ); // 2, the lines above did the same

If we’d like to increase a value and immediately use the result of the operator, we need the prefix
form:

let counter = 0;
alert( ++counter ); // 1

If we’d like to increment a value but use its previous value, we need the postfix form:

let counter = 0;
alert( counter++ ); // 0

Increment/decrement among other operators

The operators ++/-- can be used inside expressions as well. Their precedence is higher than most
other arithmetical operations.

For instance:

let counter = 1;
alert( 2 * ++counter ); // 4

Compare with:

Lesson 2  jyercia
JavaScript Fundamentals Page 26 of 35

let counter = 1;
alert( 2 * counter++ ); // 2, because counter++ returns the "old" value

Though technically okay, such notation usually makes code less readable. One line does multiple
things – not good.

While reading code, a fast “vertical” eye-scan can easily miss something like counter++ and it won’t
be obvious that the variable increased.

We advise a style of “one line – one action”:

let counter = 1;
alert( 2 * counter );
counter++;

Bitwise operators

Bitwise operators treat arguments as 32-bit integer numbers and work on the level of their binary
representation.

These operators are not JavaScript-specific. They are supported in most programming languages.

The list of operators:

 AND ( & )
 OR ( | )
 XOR ( ^ )
 NOT ( ~ )
 LEFT SHIFT ( << )
 RIGHT SHIFT ( >> )
 ZERO-FILL RIGHT SHIFT ( >>> )

These operators are used very rarely.

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

Lesson 2  jyercia
JavaScript Fundamentals Page 27 of 35

Short “modify-and-assign” operators exist for all arithmetical and bitwise operators: /=, -=, etc.

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)

Comma

The comma operator , is one of the rarest and most unusual operators. Sometimes, it’s used to write
shorter code, so we need to know it in order to understand what’s going on.

The comma operator allows us to evaluate several expressions, dividing them with a comma. Each of
them is evaluated but only the result of the last one is returned.

For example:

let a = (1 + 2, 3 + 4);

alert( a ); // 7 (the result of 3 + 4)

Here, the first expression 1 + 2 is evaluated and its result is thrown away. Then, 3 + 4 is evaluated
and returned as the result.

Comma has a very low precedence

Please note that the comma operator has very low precedence, lower than =, so parentheses
are important in the example above.

Without them: a = 1 + 2, 3 + 4 evaluates + first, summing the numbers into a = 3, 7, then the
assignment operator = assigns a = 3, and finally the number after the comma, 7, is not
processed so it’s ignored.

Why do we need an operator that throws away everything except the last part?

Sometimes, people use it in more complex constructs to put several actions in one line.

For example:

// three operations in one line


for (a = 1, b = 3, c = a * b; a < 10; a++) {
...
}

Such tricks are used in many JavaScript frameworks. That’s why we’re mentioning them.
But, usually, they don’t improve code readability so we should think well before using them.

Lesson 2  jyercia
JavaScript Fundamentals Page 28 of 35

 Tasks
The postfix and prefix forms

What are the final values of all variables a, b, c and d after the code below?

let a = 1, b = 1;

let c = ++a; // ?2
let d = b++; // ?1

Assignment result

What are the values of a and x after the code below?

let a = 2;

let x = 1 + (a *= 2);

Lesson 2  jyercia
JavaScript Fundamentals Page 29 of 35

Comparisons
We know many comparison operators from maths:

 Greater/less than: a > b, a < b.


 Greater/less than or equals: a >= b, a <= b.
 Equals: a == b (please note the double equals sign =. A single symbol a = b would mean an
assignment).
 Not equals. In maths the notation is ≠, but in JavaScript it’s written as an assignment with an
exclamation sign before it: a != b.

Boolean is the result

Like all other operators, a comparison returns a value. In this case, the value is a boolean.

 true – means “yes”, “correct” or “the truth”.


 false – means “no”, “wrong” or “not the truth”.

For example:

alert( 2 > 1 ); // true (correct)


alert( 2 == 1 ); // false (wrong)
alert( 2 != 1 ); // true (correct)

A comparison result can be assigned to a variable, just like any value:

let result = 5 > 4; // assign the result of the comparison


alert( result ); // true

String comparison

To see whether a string is greater than another, JavaScript uses the so-called “dictionary” or
“lexicographical” order.

In other words, strings are compared letter-by-letter.

For example:

alert( 'Z' > 'A' ); // true


alert( 'Glow' > 'Glee' ); // true
alert( 'Bee' > 'Be' ); // true

The algorithm to compare two strings is simple:

1. Compare the first character of both strings.


2. If the first character from the first string is greater (or less) than the other string’s, then the
first string is greater (or less) than the second. We’re done.
3. Otherwise, if both strings’ first characters are the same, compare the second characters the
same way.
4. Repeat until the end of either string.

Lesson 2  jyercia
JavaScript Fundamentals Page 30 of 35

5. If both strings end at the same length, then they are equal. Otherwise, the longer string is
greater.

In the examples above, the comparison 'Z' > 'A' gets to a result at the first step while the strings
"Glow" and "Glee" are compared character-by-character:

1. G is the same as G.
2. l is the same as l.
3. o is greater than e. Stop here. The first string is greater.

Not a real dictionary, but Unicode order

The comparison algorithm given above is roughly equivalent to the one used in dictionaries or phone
books, but it’s not exactly the same.

For instance, case matters. A capital letter "A" is not equal to the lowercase "a". Which one is
greater? The lowercase "a". Why? Because the lowercase character has a greater index in the internal
encoding table JavaScript uses (Unicode).

Comparison of different types

When comparing values of different types, JavaScript converts the values to numbers.

For example:

alert( '2' > 1 ); // true, string '2' becomes a number 2


alert( '1' == 1 ); // true, string '01' becomes a number 1

For boolean values, true becomes 1 and false becomes 0.

For example:

alert( true == 1 ); // true


alert( false == 0 ); // true

A funny consequence

It is possible that at the same time:

 Two values are equal.


 One of them is true as a boolean and the other one is false as a boolean.

For example:

let a = 0;
alert( Boolean(a) ); // false

let b = "0";
alert( Boolean(b) ); // true

alert(a == b); // true!

Lesson 2  jyercia
JavaScript Fundamentals Page 31 of 35

From JavaScript’s standpoint, this result is quite normal. An equality check converts values using the
numeric conversion (hence "0" becomes 0), while the explicit Boolean conversion uses another set of
rules.

Strict equality

A regular equality check == has a problem. It cannot differentiate 0 from false:

alert( 0 == false ); // true

The same thing happens with an empty string:

alert( '' == false ); // true

This happens because operands of different types are converted to numbers by the equality operator
==. An empty string, just like false, becomes a zero.

What to do if we’d like to differentiate 0 from false?

A strict equality operator === checks the equality without type conversion.

In other words, if a and b are of different types, then a === b immediately returns false without an
attempt to convert them.

Let’s try it:

alert( 0 === false ); // false, because the types are different

There is also a “strict non-equality” operator !== analogous to !=.

The strict equality operator is a bit longer to write, but makes it obvious what’s going on and leaves
less room for errors.

Comparison with null and undefined

There’s a non-intuitive behavior when null or undefined are compared to other values.

For a strict equality check ===

These values are different, because each of them is a different type.

alert( null === undefined ); // false

For a non-strict check ==

There’s a special rule. These two are a “sweet couple”: they equal each other (in the sense of
==), but not any other value.

alert( null == undefined ); // true


For maths and other comparisons < > <= >=

null/undefined are converted to numbers: null becomes 0, while undefined becomes NaN.

Lesson 2  jyercia
JavaScript Fundamentals Page 32 of 35

Now let’s see some funny things that happen when we apply these rules. And, what’s more
important, how to not fall into a trap with them.

Strange result: null vs 0

Let’s compare null with a zero:

alert( null > 0 ); // (1) false


alert( null == 0 ); // (2) false
alert( null >= 0 ); // (3) true

Mathematically, that’s strange. The last result states that "null is greater than or equal to zero", so in
one of the comparisons above it must be true, but they are both false.

The reason is that an equality check == and comparisons > < >= <= work differently. Comparisons
convert null to a number, treating it as 0. That’s why (3) null >= 0 is true and (1) null > 0 is false.

On the other hand, the equality check == for undefined and null is defined such that, without any
conversions, they equal each other and don’t equal anything else. That’s why (2) null == 0 is false.

An incomparable undefined

The value undefined shouldn’t be compared to other values:

alert( undefined > 0 ); // false (1)


alert( undefined < 0 ); // false (2)
alert( undefined == 0 ); // false (3)

Why does it dislike zero so much? Always false!

We get these results because:

 Comparisons (1) and (2) return false because undefined gets converted to NaN and NaN is a
special numeric value which returns false for all comparisons.
 The equality check (3) returns false because undefined only equals null, undefined, and no
other value.

Evade problems

Why did we go over these examples? Should we remember these peculiarities all the time? Well, not really.
Actually, these tricky things will gradually become familiar over time, but there’s a solid way to evade
problems with them:

Just treat any comparison with undefined/null except the strict equality === with exceptional care.

Don’t use comparisons >= > < <= with a variable which may be null/undefined, unless you’re really sure of
what you’re doing. If a variable can have these values, check for them separately.

Summary

 Comparison operators return a boolean value.


 Strings are compared letter-by-letter in the “dictionary” order.
Lesson 2  jyercia
JavaScript Fundamentals Page 33 of 35

 When values of different types are compared, they get converted to numbers (with the exclusion of a
strict equality check).
 The values null and undefined equal == each other and do not equal any other value.
 Be careful when using comparisons like > or < with variables that can occasionally be
null/undefined. Checking for null/undefined separately is a good idea.

 Tasks
What will be the result for these expressions?

5>4
"apple" > "pineapple"
"2" > "12"
undefined == null
undefined === null
null == "\n0\n"
null === +"\n0\n"

Lesson 2  jyercia
JavaScript Fundamentals Page 34 of 35

Interaction: alert, prompt, confirm


alert

Syntax:

alert(message);

This shows a message and pauses script execution until the user presses “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 visitor may type something in the prompt input field and press OK. Or they can cancel the input
by pressing CANCEL or hitting the Esc key.

The call to prompt returns the text from the input field or null if the input was canceled.

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:

Lesson 2  jyercia
JavaScript Fundamentals Page 35 of 35

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

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
Create a web-page that asks for a name and outputs it.

Lesson 2  jyercia

You might also like