Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Preview
Start a free Courses trial
to watch this video
Solution video for adding a method code challenge.
This video doesn't have any notes.
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
Welcome back.
0:00
This code challenge was a bit
more difficult than the first one
0:01
because it involved manipulating
your string property a little bit.
0:04
The goal was to add a method to
the object literal called count words,
0:07
that returned the number of
words in the string property.
0:11
Adding a method to an object literal
is a lot like adding a property.
0:14
It has the key,
which is the name of the method, and
0:17
a value, which is the actual method.
0:19
So let's add our key.
0:22
Then our method declaration.
0:26
So how do we get the number
of words in a phrase?
0:32
Strings in JavaScript have a lot of
neat methods you can use on them.
0:35
One of them is a method called split.
0:39
You call the split method on a string,
and pass in a delimiter as an argument.
0:42
A delimiter is a character or
0:46
a sequence of characters that separates
parts of texts or string data.
0:48
Many times a delimiter is a comma, like in
a CSV, or a comma separated value file.
0:52
Oftentimes it can also
be a space character.
0:57
The split method will separate
a string into an array,
1:01
with each element
separated at the delimiter.
1:04
So if we use the split method and
pass in a space character,
1:06
each word of the string will
become an element in the array.
1:10
So let's look at that.
1:13
Let's create a variable
to hold our new array.
1:14
Then we'll access the string
property using this.string.
1:23
Remember, the this keyword is how
an object can access properties and
1:27
methods that belong to itself.
1:30
So then we just call the split method and
1:31
pass in the space
character as an argument.
1:34
Once we have our phrase broken
into an array of words,
1:43
all we need to do is return
the length of the array,
1:45
which is now equal to the number
of words in the phrase.
1:48
So if you wanna see this in real time,
let's try to call the split method on
1:57
the string property and
log the output to the console.
2:01
So I'm gonna save the file and
jump down to the terminal.
2:17
Great, as you can see,
the output here is showing an array, and
2:26
each word of the phrase is
an element inside this array.
2:29
Great work, and
I'll see you in the next code challenge.
2:33
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up