sam3
.
classification
.
family
;
// "Felinae"
sam3
[
"classification"
].
family
;
// "Felinae"
sam3
.
classification
[
"family"
];
// "Felinae"
sam3
[
"classification"
][
"family"
];
// "Felinae"
Objects can also contain functions. We’ll learn about functions in depth in
but for now, what you need to know is that a function contains code (essentially a
subprogram). Here’s how we add a function to
sam3
:
sam3
.
speak
=
function
() {
return
"Meow!"
; };
We can now call that function by adding parentheses to it:
sam3
.
speak
();
// "Meow!"
Lastly, we can delete a property from an object with the
delete
operator:
delete
sam3
.
classification
;
// the whole classification tree is removed
delete
sam3
.
speak
;
// the speak function is removed
If you’re familiar with object-oriented programming (OOP), you may be wondering
how JavaScript objects relate to OOP. For now, you should think of an object as a
generic container; we will discuss OOP in
Number, String, and Boolean Objects
We mentioned earlier in this chapter that numbers, strings, and booleans have corre‐
sponding object types (
Number
,
String
, and
Boolean
). These objects serve two pur‐
poses: to store special values (such as
Number.INFINITY
), and to provide functionality
in the form of function. Consider the following:
const
s
=
"hello"
;
s
.
toUpperCase
();
// "HELLO"
This example makes it look like
s
is an object (we accessed a function property as if it
were). But we know better:
s
is a primitive string type. So how is this happening?
What JavaScript is doing is creating a temporary
String
object (which has a function
toUpperCase
, among others). As soon as the function has been called, JavaScript dis‐
cards the object. To prove the point, let’s try to assign a property to a string:
const
s
=
"hello"
;
s
.
rating
=
3
;
// no error...success?
s
.
rating
;
// undefined
JavaScript allows us to do this, making it seem like we’re assigning a property to the
string
s
. What’s really happening, though, is that we’re assigning a property to the
temporary
String
object that’s created. That temporary object is immediately dis‐
carded, which is why
s.rating
is
undefined
.
This behavior will be transparent to you, and rarely (if ever) do you have to think
about it, but it can be useful to know what JavaScript is doing behind the scenes.
48 | Chapter 3: Literals, Variables, Constants, and Data Types