## FCC ‘Slasher Flick’

Today we’re going to work on freeCodeCamp‘s Basic Algorithm Scripting challenge – ‘Slasher Flick’.  This will be a pretty short post as we’re really not going to cover anything new,  I just wanted to go through this algorithm to show how short and concise a solution to a problem can be.

The ‘Slasher Flick’ challenge is to ‘return the remaining elements of an array after chopping off n elements from the head’.

This is the starting point FCC gives us:

As you can see, we need to write the body of the function ‘slasher’, which accepts an array ‘arr’ and a number ‘howMany’.  slasher should then return ‘arr’ with ‘howMany’ elements removed from the head, or beginning, of the array.

We can actually accomplish this challenge with just 1 line of code.  To do so, we’ll use the array.slice() method, which we first used in the ‘Title Case a Sentence’.

If you remember from that previous post, array.slice() is a method that returns a new array (which is what we need this function to return).  It takes 2 arguments.  The 1st argument is the index of where the returned array will begin, which is conveniently given to us as the argument ‘howMany’.  The 2nd argument for array.slice() is the index of the final element to include in the returned array, and is optional.  Since we’ll be returning the entire array after cutting off ‘howMany’ elements, we’ll only use 1 argument.  If you wanted to include ‘arr.length’ as the second argument to make it more clear, that would work too.

Now, given we have everything we need to return the wanted array, here’s the solution:

This function now returns the given array with ‘howMany’ elements removed from the head.

Obviously this algorithm is pretty simple, it’s part of the ‘Basic Algorithm Scripting’ after all, but I wanted to cover it to show that sometimes the solution can be pretty straightforward and simple…  No need to overthink it.

Hopefully this helped straighten out the code for you.

-Jeremy

## FCC ‘Title Case A Sentence’

Today we’re going to work through another of freeCodeCamp’s Basic Algorithm Scripting challenges – ‘Title Case A Sentence’.  To solve this challenge we must write a function that accepts a string, then returns that string with the first letter of each word capitalized and the remainder of each word in lowercase.

We’ll be using concepts that we’ve covered in previous posts (i.e. for loops, string methods, and arrays) and adding a couple new things like method chaining and some new string methods.

As I’ve mentioned previously, in JavaScript, the data type String has many methods associated with it.  W3schools has a good intro to these methods, MDN covers the string object on a deeper level.

Here’s the starting point given to us by freeCodeCamp.

We’ll start solving this challenge by breaking the given string (str) into an array of words, the same way we started ‘Find the Longest Word in a String’.

Quick tangent – we haven’t discussed yet that JavaScript can be tested right in your browser.  If you have a question about what a snippet of code does, just plug it into the console of your browser and test it.   To make sure the str.split() method that I just created is doing what I want, I plugged it into the console in Chrome and tested it.

As you can see, str.split(‘ ‘) is splitting the given string into an array, with each word as an individual element.  Now I’m confident in continuing with the solution to the algorithm challenge…

Next, we need to iterate through the array and capitalize the first letter of each word and lowercase the rest of the word.  To iterate through the array, we’ll use a for loop.  To handle the upper/lowercasing of the words, we’ll need a couple new string methods.

For a deeper understanding, and a list of many more string methods, check out the MDN page on strings.  Today, we’ll be using charAt(), toUpperCase(), toLowerCase() and slice().

toUpperCase() and toLowerCase() do exactly what they sound like, they return the calling string value in upper and lower cases respectively.  charAt() allows you to access a specific character of a string and takes one parameter – the index of the character you want to access (indexes of strings start at 0, just like arrays).

slice() allows you to access a specific segment of a string.  It takes two arguments, the indexes of where you want the segment to start and finish.  The second parameter is optional, if you leave it out, the slice will start at the first index you provide and continue to the end of the string.  Very important – all four methods mentioned above return the value of a string, they do not change the calling string.  See code below for demonstration…

Now, as mentioned above, we can chain these methods together using dot notation, so that after one method is called, a second method is called on the returned string of the first.

Check out this post on method chaining for a better understanding.

We can use everything we’ve talked about to get the first character of a string and capitalize it, then get the rest of the string (starting at index 1) and lowercase it.  Putting it all together looks like this:

Several notes on the above solution…

We used the join() method, which does the exact opposite of split.  join() is an array method that returns a string delimited by what you pass as an argument.  In this case, we gave an empty space (” “) as the argument, so each element of the array was joined together separated by a space.

Also, you will note that we used a ‘+’ to connect 2 parts of a string together.  This is an easy way in JavaScript to build a string.  It can be used with both literal strings and variables as such:

Hopefully this straightened out the code for you…  See you next time.

-Jeremy

## FCC ‘Factorialize a Number’

freeCodeCamp’s Basic Algorithm Scripting section – ‘Factorialize a Number

We’ll start digging into the freeCodeCamp (FCC) curriculum with ‘Factorialize a number’ because it’s pretty straight forward and it’ll allow us to discuss the structure of functions and introduce loops (This problem can also be solved with recursion, but we’ll get into that with some of the more complex algorithms).

The challenge is to write a function that will return the factorial of the number provided.

To understand factorials better, feel free to check out wikipedia, but basically, a factorial is the product of all integers less than or equal to n and is expressed as n!  (i.e. 4! = 4 x 3 x 2 x 1 = 24).

FCC provides the following starting point:

As I mentioned in my first post, a function is a block of code that acts independently to perform a task.  It can be called from other parts of your program, and therefore, can be used over and over to perform the same ‘function’.  Functions have many uses in JavaScript, check out Eloquent JavaScript – chapter 3 to learn more.

As you can see above, the function we’ll be building is named factorialize and has one parameter (num).  The way it’s written above, it returns that parameter (the body of a function is contained in {}).  The function is then called on line 5 and passed the argument (5).

We need to add the code that will take the parameter (num) and calculate and return the factorial of ‘num’.

We’ll start by declaring a variable to store the value of the factorial and set it equal to 1.

We’ll add the code to calculate the factorial using a while loop.  Loops allow us to set a condition, then execute a block of code until that condition is met.  MDN gives a pretty good intro to while loops here.

We’ll use the argument (num) in our condition and say:

This while loop will now iterate until num>1 is false.  Therefore, we have to remember to somehow change num each time so that eventually the loop will end (otherwise, we have an infinite loop and the program will never complete).

Now we have to do something each time the loop iterates, this is where our variable total comes in.  Given that JavaScript will execute the right side of an equation before it stores it to the left side, we can set total = total * num, then depricate num by 1.  That would look something like this:

If we walk through this for num = 5, the first pass would be

Now total = 5 and num = 4.  Since 4 > 1, the while loop will execute again.

Now total = 20 and num = 3.  This will continue until the while (num>1) fails.  It would look like this.

total = 60, num = 2.

total = 120, num = 1.

At this point, the while loop condition would be false, and the loop would end with total = 120.  Given 5! = 120, we have the right total, we just need to return it.  We can just change the return statement from return num; to return total;.

Putting everything together:

This gives us the correct answer, but JavaScript makes statements that add, subtract, multiply or divide a number by itself much easier to write using the following operators: +=, -=, *= and /=.  You can also increment and deprecate by 1 using ++ and — respectively.  See the w3schools page on operators for more info.  Knowing that, the solution seen above can be written:

These two solutions do the exact same thing and solve the ‘Factorialize a Number’ algorithm challenge.

Hopefully this straightened out the code for you.  See you next time.

-Jeremy

## Intro to JavaScript Terms

As a primer to more in depth JavaScript discussions, I figured an intro to some of the terminology that we’ll be using might be helpful.  As this will not be a complete “Intro to JavaScript” (far from it, in fact), I’ll provide links to resources that I’ve found helpful along the way.

Resources

There are several sites that I use frequently in learning to code.  Obviously, freeCodeCamp is the main one.  As I mentioned in my first post, I am currently working through the front end development certification at freeCodeCamp and highly recommend it.  While working through the freeCodeCamp curriculum I use w3schools, MDN and Stack Overflow extensively as references.  I also found that Tutorial Republic is an excellent resource for HTML, CSS and Bootstrap (which is a powerful front end framework that makes creating responsive web pages much easier).

There are also a couple books that I’ve used along the way.  The first is ‘Eloquent JavaScript‘, which is an excellent free resource (available in print also) for learning JavaScript.  It’s not exactly a book for beginners, but the online version provides examples and problems that you can work through right in the browser.  It’s the best JavaScript resource I’ve found yet…   I also picked up the Head First books ‘HTLM and CSS‘ and ‘HTML5 Programming‘.  They’re more on the beginner side, but are written well and I found them helpful in learning to interact with the DOM (which we will get into in future posts).

Intro to Terminology

Now, to cover some terms we’ll be using frequently.  In future posts, I will have to assume a basic understanding of these languages, otherwise each post will be the length of a book.  So I urge you, if you have any questions about the concepts listed below, please use the resources listed above to read more about them.

In JavaScript, groups of data are called values and these values have types.  There are 7 data types in JavaScript:

• undefined
• null
• boolean
• string
• symbol
• number
• object

Any of these data types can be stored in a variable.  To declare a variable, use the keyword ‘var’, as such:

The above statement created a variable named ‘a’.  It also includes a comment…  Anything written on a line after // is a comment and will be ignored by the browser.  You can also assign values to the variable when you create it. The following statements create variables and assign values of the various data types.

JavaScript provides several data structures called objects and arrays.  I plan on covering objects and arrays in depth in decipheredCode so for now will only cover each at a very high level.

Objects allow us to group data of various types (including other objects) as name:value pairs called properties.  Objects are used extensively in JavaScript, in fact JSON (JavaScript Object Notation) files are the way most programs pass data among themselves over the web.

An array is a list of objects or values, called elements, stored inside brackets and separated by commas.  Array elements can be accessed using bracket notation and indexes (note: first element in an array is index [0]).  An example of accessing the first element of an array would be:

The arr declared above would now have the string ‘apple’ as it’s first element (index [0]).  Chapter 4  of ‘Eloquent JavaScript’ gives a great explanation in the use of objects and arrays.

Another term used extensively in JavaScript, and programming in general, is function.  A function is a self contained block of code that can act on it’s own to do something.  A function can take a set of parameters (optional) and contains a block of code to act on those parameters.  Here’s an example of a function.

This function, named addOne, has one parameter (num).  The code inside the function creates a new variable called newNum, then sets newNum equal to num + 1 and returns the value of newNum.  The way we would use this function (or invoke it) is

This example calls the addOne function and passes the number 5 as an argument.  This function call would return the value 6.

What is an argument?  An argument is the actual value that you pass into the function, as opposed to a parameter, which is the name listed in the function definition.  I’ll be using these terms interchangeably here at decipheredCode (whether right or wrong…), so you can think of both arguments and parameters as something that gets passed into a function.

Now…  This has been a long, rambling post that mentioned a bunch of things but didn’t really explain anything in detail. I feel, however, that it was necessary before I started digging any deeper..  Hopefully, this will be helpful to someone just starting out on their journey to learn to code.  The next posts here at decipheredCode will start to dig into real problems.  Meantime, I urge anyone that is interested to check out the links that I mentioned above and to start getting their hands dirty by writing some code!

-Jeremy