Lesson 17 - Strict operators and casting in JavaScript - Online course
In the previous lesson on Conditions Conditions, we promised to return to them once again in the course. In today's lesson, we will therefore show the common problems with the use of conditions.
Strict operators for the second time
We have already encountered the operators ==
, ===
!=
!==
and the comparing of different data types. As a
reminder, let's see an example that demonstrates the difference between
comparing a value with the ==
operator and comparing it with a
value and a type with the ===
operator:
if (1 == '1') document.write('Equal in value.'); if (1 === '1') document.write('Equal in value and type.');
Sample application in the browser:
The first condition evaluates to true because only the values are compared.
More precisely, the text '1'
(string
)
is first cast to the number 1
(number
) and the
subsequent comparison is evaluated as true
.
The second condition is not being cast due to the strict operator
===
, so it is evaluated as false
, because the number
cannot be equal to the text in this way.
Casting is a rather complicated topic in JavaScript and would take up a whole separate course. We teach it in this separate lesson. We will show you how to avoid common problems with casting and where, on the contrary, casting will help us write clearer code.
Operator selection
So which operator to use for comparing? It is good practice to use the strict
operators ===
and !==
to avoid any casting when
comparing.
Using the ==
and !=
operators when comparing
different data types can have unexpected results, because casting rules are
often confusing. Do you remember the introductory lesson, where we said that
JavaScript was designed in 14 days? To illustrate this, let's look at a few
typical casting results that we probably wouldn't expect:
if ('' == '0') // false if (0 == '') // true if (0 == '0') // true if (false == 'false') // false if (false == '0') // true if (false == undefined) // false if (false == null) // false if (null == undefined) // true
Try to think about why the conditions were evaluated in this way. Not sure or
no idea at all? It doesn't matter, just use the strict operator
===
, which will behave as expected. The previous example with the
===
operator would always evaluate to false
.
The complete table with retyping of different values and data types when
comparing with the ==
operator can be found at: https://dorey.github.io/…ality-Table/
Shortening conditions by casting
So far, we have shown only the problems associated with casting and the possibility of avoiding them with the help of strict operators. We will now show a few examples where, on the contrary, we will use casting to our advantage.
Non-empty string verification
Let's have the following example: The user enters his name, and we want to
check if he really entered it. So we will check if the entered name is longer
than 0
. An example might look like this:
let name = prompt('Fill in your name'); if (name.length > 0) document.write('Name filled in.'); else document.write('Name not filled in.');
Thanks to casting, we can shorten the condition only to:
let name = prompt('Fill in your name'); if (name.length) document.write('Name filled in.'); else document.write('Name not filled in.');
The length
property is of type number
, which
evaluates to false
when 0
and to true
when any other.
We can even write the same condition just like this:
let name = prompt('Fill in your name'); if (name) document.write('Name filled in.'); else document.write('Name not filled in.');
If the name is not filled in and an empty string ''
is stored
instead, it will be cast to false
. Otherwise to true
.
We prefer these abbreviated notations in our scripts.
Non-empty array verification
Similarly, we can verify if we have an empty array or if the array contains anything:
let a = [1, 2, 3]; if (array.length) document.write('The array is not empty.'); else document.write('The array is empty.');
Be careful here! Unlike to a string, where empty evaluates as
false
, the empty array evaluates as
true
! Therefore, for an array, we must ask about its
length
. Result in the browser:
Conditions with null
A practical example of using null
in a condition is provided by
the getElementById()
method. This method returns the searched
element as a type of object
if successful. If unsuccessful, it
returns null
, which indicates that the element is not on the
page:
let htmlElement = document.getElementById('anElement'); if (htmlElement !== null) { //found document.write('Element found'); } else { //not found document.write('Element not found'); }
Since null
is cast to false
and object
to true
, we can also shorten the condition:
let htmlElement = document.getElementById('anElement'); if (htmlElement) { //found document.write('Element found'); } else { //not found document.write('Element not found'); }
Result:
Conditions with undefined
Surely you remember that a variable has the data type undefined
,
if we declare it and do not assign any value yet:
let value; document.write(typeof value);
Result:
Older syntax of the default parameter value
A practical example might be using a function with or without a parameter that you come across in older code. There you can find the following entry:
function greet(language) { // default value if (language === undefined) language = 'en'; if (language === 'en') document.write('Hello World!'); else if (language === 'cz') document.write('Ahoj světe!'); //... } greet(); greet('cz');
Result:
The function first tests whether the specified parameter exists and, if not,
assigns it a default value of 'en'
.
Because undefined
cast to false
, you might think of
writing a condition in this form:
if (language) language = 'en';
That would work in our case, but it's not a good idea. Here, it is necessary
to keep in mind that if we are passing a string
, then the empty
string
will be evaluated as false
again. The same
could occur in the case with a number where 0
would be passed.
While an empty language does not make sense for a parameter, an empty value
separator or the number 0
could already be an intention.
ES6 syntax of the default value of the parameter
Let's go back to the previous example. Thanks to ES6
, it can be
written even better, the default value can be assigned directly to the
parameter, and we do not have to check in the function whether the parameter has
been entered:
function greet(language = 'en') { if (language === 'en') document.write('Hello World!'); else if (language === 'cz') document.write('Ahoj světe!'); //... } greet(); greet('cz');
Result:
That's all for today's lesson on casting.
In the next lesson, Most common mistakes of JS beginners - Naming variables, we'll show you the most common JavaScript beginner mistakes when naming variables.