0% found this document useful (0 votes)
24K views92 pages

JS-A.L.U01 (Types and Coercion)

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

JS-A.L.U01 (Types and Coercion)

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

JavaScript Advanced

Types and Coercion

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 1


Overview
1. Types
2. Values
3. Natives
4. Coercion
5. Grammar

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 2


1. Built-in Types
 JavaScript defines seven built-in types:
1. null
2. undefined
3. boolean
4. number
5. string
6. object
7. symbol -- added in ES6!
 Note: All of these types except object are called "primitives".

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 6


1. Built-in Types
 The typeof operator inspects the type of the given value, and always
returns one of seven string values

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 7


1. Built-in Types
 Seventh string value that typeof return:

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 8


1. Built-in Types
 What about arrays? They're native to JS, so are they a
special type?

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 9


1. Values as Types
 In JavaScript, variables don't have types -- values have types.
Variables can hold any value.
 Another way to think about JS types is that JS doesn't have "type
enforcement,”
 A variable can, in one assignment statement, hold a string, and in the
next hold a number, and so on
Store a number
We already know that
number and string are
Store a string different type (behavior)

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 10


1. Values as Types
 If you use typeof against a variable, it's not asking "what's
the type of the variable?" as it may seem, since JS
variables have no types.
 Instead, it's asking "what's the type of the value in the
variable?"

what's the type of


the value in a ?

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 11


1. undefined vs undeclared
 Variables that have no
value currently, actually have
the undefined value.
 Calling typeof against such
variables will return "undefined"

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 13


1. undefined vs undeclared

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 14


1. undefined vs undeclared
 Consider:

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 15


1. undefined vs undeclared

In fact it means
b is not found/
declared

Easy to confuse
with b is undefined

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 16


1. Types – Summary
 JavaScript has 7 built-in types: null, undefined, boolean,
number, string, object, symbol.
 They can be identified by the typeof operator.
 Variables don't have types, but the values in them do.
These types define intrinsic behavior of the values.
 undefined is a value that a declared variable can hold.
”undeclared" means a variable has never been declared.

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 17


2. Values Overview
 arrays, strings, and numbers are the most basic building-
blocks of any program
 JavaScript has some unique characteristics with these
types
 Understand those characteristics help you to build better
program

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 18


2. Arrays
 As compared to other type-enforced languages,
JavaScript arrays are just containers for any type of value,
from string to number to object to even another array:

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 19


2. Arrays
 arrays are numerically indexed (as you'd expect), but they
also are objects that can have string keys/properties added
to them (but which don't count toward the length of
the array):

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 20


2. Arrays
 Be aware of is that if a string value intended as a key can be converted
to a standard base-10 number, then it is assumed that you wanted to
use it as a number index rather than as a string key!

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 21


2. Strings
 It's a very common belief that strings are essentially
just arrays of characters.
 While the implementation under the covers may or may not
use arrays, it's important to realize that JavaScript strings
are really not the same as arrays of characters.

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 22


2. Strings
 For example, let's consider these two values:

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 23


2. Strings
 Strings do have a shallow resemblance to arrays -- array-likes, as
above -- for instance, both of them having a length property,
an indexOf(..) method and a concat(..) method:

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 24


2. Strings
 So, they're both basically just "arrays of characters",
right?
 Not exactly:

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 25


2. Strings
 JavaScript strings are immutable, while arrays are quite
mutable.
 Moreover, the a[1] character position access form was not
always widely valid JavaScript.
 Older versions of IE did not allow that syntax (but now they
do).
 Instead, the correct approach has been a.charAt(1).

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 26


2. Strings
 None of the string methods that alter its contents can modify in-place,
but rather must create and return new strings.
 By contrast, many of the methods that change array contents
actually do modify in-place.

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 27


2. Strings
 Let's take another example: reversing a string (incidentally, a common
JavaScript interview trivia question!).
 arrays have a reverse() in-place mutator method, but strings do not:

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 28


2. Strings
 Solution: convert the string into an array, perform the
desired operation, then convert it back to a string.

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 29


2. Strings
 When you need to modify
strings:
1. Store them as arrays rather than
as strings.
2. Change element in the arrays
3. Then call join("") on the array of
characters whenever you actually
need the string representation.

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 30


2. Numbers
 JavaScript has just one numeric type: number.
 This type includes both integer values and fractional
decimal numbers.
 JavaScript specifically uses the "double precision" format
(aka "64-bit binary") of the standard
 But in fact only 53-bit is used

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 31


2. Numberic Syntax
 Because number values can be boxed with the Number object
wrapper, number values can access methods that are built into
the Number.prototype.
 For example, the toFixed(..) method allows you to specify how many
fractional decimal places you'd like the value to be represented with:

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 32


2. Small Decimal Values
 The most (in)famous side effect of using binary floating-
point numbers (which, remember, is true of all languages
that use IEEE 754 -- not just JavaScript as many
assume/pretend) is:

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 33


2. Small Decimal Values
 Mathematically, we know that statement should be true.
 Why is it false?
• Simply put, the representations for 0.1 and 0.2 in binary floating-
point are not exact,
• So when they are added, the result is not exactly 0.3.
• It's really close: 0.30000000000000004
• It’s not exactly 0.3

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 34


2. Small Decimal Values
 What if we did need to compare two numbers ?
• Use a tiny "rounding error" value as the tolerance for comparison.
• This tiny value is often called "machine epsilon,”
• Which is commonly 2^-52 (2.220446049250313e-16)

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 35


2. Safe Integer Ranges
 Range of "safe" is significantly less
than Number.MAX_VALUE.
 The maximum integer that can "safely"
be represented is 2^53 - 1, which
is 9007199254740991.
Safe

Not safe

a + 2 is outside
safe zone

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 36


2. Special Values – Non-value
 Both undefined and null are often taken to be
interchangeable as either "empty" values or "non" values.
 Other developers prefer to distinguish between them with
nuance. For example:
• null is an empty value
• undefined is a missing value
Or:
• undefined hasn't had a value yet
• null had a value and doesn't anymore

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 37


2. Special Numbers
 Not A Number
 Any mathematic operation you perform without both
operands being numbers (or values that can be interpreted
as regular numbers in base 10 or base 16) will result in the
operation failing to produce a valid number, in which case
you will get the NaN value.

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 38


2. Special Numbers
 NaN literally stands for "not a number", though this label/description is
very poor and misleading
 It would be much more accurate to think of NaN as being "invalid
number," "failed number," or even "bad number," than to think of it as
"not a number."

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 39


2. Special Numbers
 So, if you have a value in some variable and want to test to see if it's
this special failed-number NaN, you might think you could directly
compare to NaN itself, as you can with any other value,
like null or undefined. Nope.

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 40


2. Special Numbers
 NaN is a very special value in that it's never equal to another NaN value
(i.e., it's never equal to itself).
 So how do we test for it, if we can't compare to NaN (since that
comparison would always fail)?

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 41


2. Special Numbers
 As of ES6, finally a replacement utility has been
provided: Number.isNaN(..). A simple polyfill for it so that you can
safely check NaN values now even in pre-ES6 browsers is:

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 42


2. Special Numbers
 NaNs are probably a reality in a lot of real-world JS
programs, either on purpose or by accident.
 It's a really good idea to use a reliable test,
like Number.isNaN(..) as provided (or polyfilled), to
recognize them properly.
 If you're currently using just isNaN(..) in a program, the sad
reality is your program has a bug, even if you haven't been
bitten by it yet!

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 43


2. Special Numbers
 Infinities
 Developers from traditional compiled languages like C are
probably used to seeing either a compiler error or runtime
exception, like "Divide by zero," for an operation like:

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 44


2. Special Numbers
 However, in JS, this operation is well-defined and results in
the value Infinity (aka Number.POSITIVE_INFINITY).
Unsurprisingly:

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 45


2. Value vs. Reference
 A reference in JS points at a (shared) value, so if you have
10 different references, they are all always distinct
references to a single shared value; none of them are
references/pointers to each other.

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 46


2. Value vs. Reference
 Instead, the type of the value controls whether that value will be
assigned by value-copy or by reference-copy.

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 47


2. Value vs. Reference
 Simple values (aka scalar primitives)
are always assigned/passed by value-copy
 Compound values: objects (including arrays, and all
boxed object wrappers) and functions -- always create a
copy of the reference on assignment or passing

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 48


2. Value vs. Reference
 References are quite powerful
 The only control you have over reference vs. value-copy
behavior is the type of the value itself

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 49


2. Quiz
 What is the output of below code ?

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 50


2. Quiz
 What is the output of below code ?

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 51


2. Values – Summary
 In JavaScript, arrays are simply numerically indexed
collections of any value-type.
 strings are somewhat "array-like", but they have distinct
behaviors and care must be taken if you want to treat them
as arrays.
 Numbers in JavaScript include both "integers" and floating-
point values.

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 52


2. Values – Summary
 Several special values are defined within the primitive
types.
 The null type has just one value: null, and likewise
the undefined type has just the undefined value.
 undefined is basically the default value in any variable or
property if no other value is present.
 The void operator lets you create the undefined value from
any other value.

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 53


2. Values – Summary
 numbers include several special values,
like NaN (supposedly "Not a Number", but really more
appropriately "invalid number"); +Infinity and -Infinity;
and -0.
 Simple scalar primitives (strings, numbers, etc.) are
assigned/passed by value-copy, but compound values
(objects, etc.) are assigned/passed by reference-copy.
 References are not like references/pointers in other
languages -- they're never pointed at other
variables/references, only at the underlying values.

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 54


3. Natives
 Here's a list of the most commonly used natives (Object):
o String()
o Number()
o Boolean()
o Array()
o Object()
o Function()
o Date()
o Error()

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 55


3. Natives – Boxing Wrappers
 These object wrappers serve a very important purpose.
 Primitive values don't have properties or methods,
 To access .length or .toString() you need an object wrapper around the
value

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 56


3. Natives – Boxing Wrappers
 In general, there's basically no reason to use the object
form directly.
 It's better to just let the boxing happen implicitly where
necessary.
 In other words, never do things like new String("abc"), new
Number(42), etc -- always prefer using the literal primitive
values "abc" and 42.

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 57


3. Natives – Boxing Wrappers
 There are some gotchas with using the object wrappers directly that you
should be aware of if you do choose to ever use them. For example,
consider Boolean wrapped values:

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 58


3. Natives – Boxing
 If you want to manually box a primitive value, you can use
the Object(..) function (no new keyword):

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 59


3. Natives – Unboxing
 If you have an object wrapper and you want to get the underlying
primitive value out, you can use the valueOf() method:

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 60


3. Natives – Array(..)
 The Array constructor has a special form where if only
one number argument is passed, instead of providing that value
as contents of the array, it's taken as a length to "presize the array"

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 61


3. Natives – Array(..)
 It doesn't help matters that this is yet another example where browser
developer consoles vary on how they represent such an object, which
breeds more confusion.

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 62


3. Natives – Array(..)
 To visualize the difference, try this:

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 63


3. Natives – Array(..)
 To create an array and fill value to its:

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 64


3. Natives – Object/Function
 The Object(..)/Function(..)/RegExp(..) constructors are also generally
optional (and thus should usually be avoided unless specifically called
for):

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 65


3. Natives – Date and Error
 The Date(..) and Error(..) native constructors are much more useful than
the other natives, because there is no literal form for either.
 To create a date object value, you must use new Date().
The Date(..) constructor accepts optional arguments to specify the
date/time to use, but if omitted, the current date/time is assumed.
 By far the most common reason you construct a date object is to get the
current timestamp value (a signed integer number of milliseconds since
Jan 1, 1970). You can do this by calling getTime() on a date object
instance.

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 66


3. Natives – Date and Error
 Date Usage:

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 67


3. Natives – Date and Error
 Date Usage:

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 68


3. Natives – Date and Error
 The Error(..) constructor behaves the same with
the new keyword present or omitted.
 The main reason you'd want to create an error object is that
it captures the current execution stack context into the
object
 This stack context includes the function call-stack and the
line-number where the error object was created, which
makes debugging that error much easier.

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 69


3. Natives – Summary
 JavaScript provides object wrappers around primitive values, known as
natives (String, Number, Boolean, etc).
 These object wrappers give the values access to behaviors appropriate
for each object subtype (String.trim(), Array.concat()).
 If you have a simple scalar primitive value like "abc" and you access
its length property or some String.prototype method
 JS automatically "boxes" the value (wraps it in its respective object
wrapper) so that the property/method accesses can be fulfilled.

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 70


4. Coercion
 Converting a value from one type to another is often called
"type casting," when done explicitly,
 "coercion" when done implicitly (forced by the rules of how
a value is used).
 Another terms: "type casting" (or "type conversion") occur
in statically typed languages at compile time,
 "type coercion" is a runtime conversion for dynamically
typed languages.

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 71


4. Coercion
 However, in JavaScript, most people refer to all these types
of conversions as coercion: "implicit coercion" vs. "explicit
coercion."

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 72


4. Coercion - ToBoolean
 Falsy Values
 All of JavaScript's values can be divided into two
categories:
1. values that will become false if coerced to boolean
2. everything else (which will obviously become true)

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 73


4. Coercion - ToBoolean
 We get the following as the so-called "falsy" values list:
 undefined
 null
 false
 +0, -0, and NaN
 "” (empty string)

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 74


4. Coercion - ToBoolean
 Truthy Values
 What exactly are the truthy values? a value is truthy if it's
not on the falsy list.

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 75


4. Coercion - ToBoolean
 What about these?

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 76


4. Coercion - Explicit Coercion
 To convert number to string and vice versa:

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 77


4. Coercion - Explicit Coercion
 Explicitly: Parsing Numeric Strings
 A similar outcome to coercing a string to a number can be achieved by
parsing a number out of a string's character contents

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 78


4. Coercion - Explicit Coercion
 The pre-ES5 fix was simple, but so easy to forget: always
pass 10 (base 10) as the second argument.
 This was totally safe:

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 79


4. Coercion - Explicit Coercion
 Explicitly: any => Boolean
 Now, let's examine coercing from any non-
boolean value to a boolean.
 Just like
with String(..) and Number(..) above, Boolean
(..) (without the new, of course!) is an explicit
way of forcing the ToBoolean coercion:

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 80


4. Coercion - Explicit Coercion
 The unary ! negate operator explicitly coerces a
value to a boolean.
 So, the most common way JS developers
explicitly coerce to boolean is to use
the !! double-negate operator, because the
second ! will flip the parity back to the original

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 81


4. Coercion - Implicit Coercion
 Implicit coercion refers to type conversions that are hidden,
with non-obvious side-effects that implicitly occur from other
actions.
 In other words, implicit coercions are any type conversions
that aren't obvious (to you).

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 82


4. Coercion - Implicit Coercion
 Implicitly: any => Boolean
 It's by far the most common and also by far the most
potentially troublesome.
 Remember: implicit coercion is what kicks in when you use
a value in such a way that it forces the value to be
converted

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 83


4. Coercion - Implicit Coercion
 But, what sort of expression operations require/force
(implicitly) a boolean coercion?
1. Test expression in an if (..) statement.
2. Test expression (second clause) in a for ( .. ; .. ; .. ) loop.
3. Test expression in while (..) and do..while(..) loops.
4. Test expression (first clause) in ? : ternary expressions.
5. left-hand operand to the || ("logical or") and && ("logical and")
operators.

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 84


4. Coercion - Implicit Coercion
 Let's look at some
examples:

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 85


4. Coercion - Implicit Coercion
 Loose Equals vs. Strict Equals
 Loose equals is the == operator, and strict equals is the === operator.
Both operators are used for comparing two values for "equality,”
 A very common misconception about these two operators is:
"== checks values for equality and === checks both values and types
for equality.”
 The correct description is: "== allows coercion in the equality
comparison and === disallows coercion."

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 86


4. Coercion - Implicit Coercion
 Comparing: strings to numbers
 To illustrate == coercion, let's first build off
the string and number examples earlier in this chapter:

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 87


4. Coercion - Implicit Coercion
 Comparing: anything to Boolean
 One of the biggest gotchas with the implicit coercion
of == loose equality pops up when you try to compare a
value directly to true or false.

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 88


4. Coercion – Summary
 coercion: JavaScript type conversions, which can be
characterized as either explicit or implicit.
 Explicit coercion is code which is obvious that the intent is
to convert a value from one type to another
 Implicit coercion is coercion that is "hidden" as a side-effect
of some other operation, where it's not as obvious that the
type conversion will occur
 Especially for implicit, coercion must be used responsibly
and consciously

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 89


5. Grammar - Statements & Expressions

 A "sentence" is one complete formation of words that expresses a


thought: it's comprised of one or more "phrases," each of which can be
connected with punctuation marks or conjunction words ("and," "or,"
etc).
 And so it goes with JavaScript grammar. Statements are sentences,
expressions are phrases, and operators are conjunctions/punctuation.

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 90


5. Grammar - Statements & Expressions

 Every expression can be evaluated to a value result.


 For example:
statement

expresion
7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 91
5. Grammar - Automatic Semicolons

 ASI (Automatic Semicolon Insertion) is when JavaScript


assumes a ; in certain places in your JS program even if
you didn't put one there.
 ASI allows JS to be tolerant of certain places where ; aren't
commonly thought to be necessary.
 It's important to note that ASI will only take effect in the
presence of a newline (aka line break).
 Semicolons are not inserted in the middle of a line.

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 92


5. Grammar - Automatic Semicolons
 Major case is with: break, continue, return:

Always return undefined

ASI

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 93


5. Grammar - Automatic Semicolons

 Always use semicolons wherever you know they are


"required," and limit your assumptions about ASI to a
minimum.
Make sure no newline break after return

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 94


5. Grammar – Summary
 Statements and expressions have analogs in English
language -- statements are like sentences and expressions
are like phrases.
 ASI (Automatic Semicolon Insertion) is a parser-error-
correction mechanism built into the JS engine, which allows
it under certain circumstances to insert an assumed ’;’ in
places where it is required
 Always use semicolon ‘;’

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 95


Thank you

7/5/2021 09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 96

You might also like