The "Script" Tag: Alert ('Hello, World!')
The "Script" Tag: Alert ('Hello, World!')
<!DOCTYPE HTML>
<html>
<body>
<script>
alert( 'Hello, world!' );
</script>
</body>
</html>
The <script> tag contains JavaScript code which is automatically executed when the browser
processes the tag.
Modern markup
The <script> tag has a few attributes that are rarely used nowadays but can still be found in old code:
The old HTML standard, HTML4, required a script to have a type. Usually it was
type="text/javascript". It’s not required anymore. Also, the modern HTML standard,
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.
This attribute was meant to show the language of the script. This attribute no longer makes
sense because JavaScript is the default language. There is no need to use it.
In really ancient books and guides, you may find comments inside <script> tags, like this:
<script type="text/javascript"><!--
...
//--></script>
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
<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.
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.2.0/lodash.js"></script>
<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
Lesson 2 jyercia
JavaScript Fundamentals Page 3 of 35
Code structure
Statements
alert('Hello'); alert('World');
Usually, statements are written on separate lines to make the code more readable:
alert('Hello');
alert('World');
Semicolons
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.
The rest of the line is a comment. It may occupy a full line of its own or follow a statement.
Like here:
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:
The content of comments is ignored, so if we put code inside /* … */, it won’t execute.
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 comment ?!? */
*/
alert( 'World' );
Lesson 2 jyercia
JavaScript Fundamentals Page 5 of 35
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";
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.
Please make sure that "use strict" is at the top of your scripts, otherwise strict mode may not be
enabled.
alert("some code");
// "use strict" below is ignored--it must be at the top
"use strict";
There is no directive like "no use strict" that reverts the engine to old behavior.
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:
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...
})()
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.
A variable
A variable is a “named storage” for data. We can use variables to store goodies, visitors, and other
data.
The statement below creates (in other words: declares 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!
That might seem shorter, but we don’t recommend it. For the sake of better readability, please use a
single line per variable.
Lesson 2 jyercia
JavaScript Fundamentals Page 8 of 35
Technically, all these variants do the same thing. So, it’s a matter of personal taste and aesthetics.
In older scripts, you may also find another keyword: var instead of let:
The var keyword is almost the same as let. It also declares a variable, but in a slightly different, “old-
school” way.
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
1. The name must contain only letters, digits, or the symbols $ and _.
2. The first character must not be a digit.
let userName;
let test123;
When the name contains multiple words, 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.
Case matters
Lesson 2 jyercia
JavaScript Fundamentals Page 9 of 35
Reserved names
There is a list of reserved words, which cannot be used as variable names because they are used by
the language itself.
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.
"use strict";
num = 5; // error: num is not defined
Constants
Variables declared using const are called “constants”. They cannot be changed. An attempt to do so
would cause an error:
When a programmer is sure that a variable will never change, they can declare it with const to
guarantee and clearly communicate that fact to everyone.
Uppercase constants
There is a widespread practice to use constants as aliases for difficult-to-remember values that are
known prior to execution.
Lesson 2 jyercia
JavaScript Fundamentals Page 10 of 35
For instance, let’s make constants for colors in so-called “web” (hexadecimal) format:
Benefits:
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:
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.
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.
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. 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.
alert( 1 / 0 ); // Infinity
So, if there’s a NaN somewhere in a mathematical expression, it propagates to the whole result.
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
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:
// embed a variable
alert( `Hello, ${name}!` ); // Hello, John!
// embed an expression
alert( `the result is ${1 + 2}` ); // the result is 3
The expression inside ${…} is evaluated and the result becomes a part of the string. We can put
anything in there: a variable like name or an arithmetical expression like 1 + 2 or something more
complex.
Please note that this can only be done in backticks. Other quotes don’t have this embedding
functionality!
alert( "the result is ${1 + 2}" ); // the result is ${1 + 2} (double quotes do nothing)
In some languages, there is a special “character” type for a single character. For example, in the C
language and in Java it is 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
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:
It forms a separate type of its own which contains only the null value:
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.
let x;
alert(x); // shows "undefined"
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
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 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.
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.
Summary
null for unknown values – a standalone type that has a single value null.
undefined for unassigned values – a standalone type that has a single value undefined.
object for more complex data structures.
symbol for unique identifiers.
Tasks
What is the output of the script?
let name = "Ilya";
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 is mostly obvious. A false becomes "false", null becomes "null", etc.
ToNumber
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:
Examples:
Please note that null and undefined behave differently here: null becomes zero while undefined becomes
NaN.
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.
This only happens when at least one of the arguments is a string. Otherwise, values are converted to
numbers.
ToBoolean
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).
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
Some languages (namely PHP) treat "0" as false. But in JavaScript, a non-empty string is always 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.
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
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).
Note that if one of the operands is a string, the other one is converted to a string too.
For example:
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:
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.
alert( 2 - '1' ); // 1
Lesson 2 jyercia
JavaScript Fundamentals Page 21 of 35
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
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.
If we want to treat them as numbers, we need to convert and then sum them:
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):
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
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.
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.
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 %
For instance:
Exponentiation **
For instance:
alert( 2 ** 2 ); // 4 (2 * 2)
alert( 2 ** 3 ); // 8 (2 * 2 * 2)
alert( 2 ** 4 ); // 16 (2 * 2 * 2 * 2)
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.
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.
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.
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
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.
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
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.
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.
AND ( & )
OR ( | )
XOR ( ^ )
NOT ( ~ )
LEFT SHIFT ( << )
RIGHT SHIFT ( >> )
ZERO-FILL RIGHT SHIFT ( >>> )
Modify-in-place
We often need to apply an operator to a variable and store the new result in that same variable.
For example:
let n = 2;
n = n + 5;
n = n * 2;
let n = 2;
n += 5; // now n = 7 (same as n = n + 5)
n *= 2; // now n = 14 (same as n = n * 2)
alert( n ); // 14
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;
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);
Here, the first expression 1 + 2 is evaluated and its result is thrown away. Then, 3 + 4 is evaluated
and returned as the result.
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:
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
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:
Like all other operators, a comparison returns a value. In this case, the value is a boolean.
For example:
String comparison
To see whether a string is greater than another, JavaScript uses the so-called “dictionary” or
“lexicographical” order.
For example:
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.
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).
When comparing values of different types, JavaScript converts the values to numbers.
For example:
For example:
A funny consequence
For example:
let a = 0;
alert( Boolean(a) ); // false
let b = "0";
alert( Boolean(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
This happens because operands of different types are converted to numbers by the equality operator
==. An empty string, just like false, becomes a zero.
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.
The strict equality operator is a bit longer to write, but makes it obvious what’s going on and leaves
less room for errors.
There’s a non-intuitive behavior when null or undefined are compared to other values.
There’s a special rule. These two are a “sweet couple”: they equal each other (in the sense of
==), but not any other value.
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.
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
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
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
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
It shows a modal window with a text message, an input field for the visitor, and the buttons
OK/CANCEL.
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:
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.
So, for prompts to look good in IE, we recommend always providing the second argument:
Lesson 2 jyercia
JavaScript Fundamentals Page 35 of 35
confirm
The syntax:
result = confirm(question);
The function confirm shows a modal window with a question and two buttons: OK and CANCEL.
For example:
Summary
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.
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