Understanding A Specific JavaScript Class Example: Class Formatter.
Tags: javascript, staticmethod, classobjects
Published: 2023-07-24 02:28:27

#Class Formatter, Static Method.

I have created this post because I wanted to understand more about this specific example and the Static Method in a JavaScript Class. In this instance I'm going to be using an example from one of my labs in The Flatiron curriculum. Not just to get a better grasp of JavaScript Classes and The Static Method but also about the other different methods included in this example.

First, let's start with some definitions.

## What is a Class?
*Classes* are a template for creating objects. They encapsulate data with code to work on that data. A blueprint for initializing objects that have default parameters. 

### Syntax

!["Class Syntax"](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u9pmqi2lrkrghi8x4hu1.png)

## What is a Static Method?
The *static* keyword defines a static method or field for a class. Static properties (fields and methods) are defined on the class itself instead of each instance. Static methods are often used to create utility functions for an application, whereas static fields are useful for caches, fixed-configuration, or any other data that don't need to be replicated across instances.

### Syntax

!["Static Method Syntax](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ifhcwrqv5i65i4z35zlk.png)

## Class Formatter example.
Now that we got some understanding about what a Class and Static Method are let's take a look at the example:

!["Class Formatter"](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7xgj8i9vjcqrrce9na5b.png)

In this example we have a *Class* named *Formatter* with 3 Static Methods: *static capitalize()*, *static sanitize()*, and *static titleize*.

The *Class Formatter* serves as a template to capitalize the first letter in a string, for removing all non-alphanumeric characters except for dashes, single quotes and spaces or capitalizes all words in a sentence except: *the, a, an, but, of, and, for, at, by, and from*. Also, it always capitalizes the first word in a string.

In the first part we have this:

!["static capitalize"](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/grv9dtqpv0rdte44m266.png)

Here we have the Class Formatter and the first Static Method: static capitalize().
Static capitalize(string) takes a string as an argument and uses the methods: *.charAt()*, *.toUpperCase()* and *.slice()*; to returned a capitalized string. 

First The *charAt() method* returns the character at the specified index in a string.

```
string.charAt(0)
```

index 0 returns the first letter in the string. 

Then *.toUpperCase() method* converts the string specified by the *.charAt* at index 0 to uppercase. So basically the first letter in the string.

```
string.charAt(0).toUpperCase()
```
The *.slice()* method at the end extracts the part of the string starting at index 1(which is the second letter in the string) and adds("+") it to the first letter that was capitalized. Therefore returning the whole string with the first letter capitalized.

```
string.charAt(0).toUpperCase() + string.slice(1)
```

Next, let's look at the second Static Method:

!["static sanitize"](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vsc639s4qihx9g5hpl0p.png)

Here we have *static sanitize(string)*. It takes a string as a parameter and removes all non-alphanumeric characters except for dashes, single quotes and spaces.  

It uses the *.replace()* method which searches a string for a value or a regular expression. This method returns a new string with the value(s) replaced and does not change the original string.

```
string.replace(/[^A-Za-z0-9-' ]+/g, "")
```
Everything that's inside the [] brackets is an exception and the 'g' flag makes sure that all matching values are replaced. So everything other than A-Z, a-z, 0-9, dash(-), single quote(') and spaces. 
_(I still need a better understanding of *.replace()* and what goes inside the parenthesis and brackets so once I get a better understanding I'll update this post.)_

Lastly, we have third Static Method: *static titleize(string)*:


!["static titleize"](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/twolbvcsvi1dtmtsa9x6.png)

*static titleize(string)" takes a string as an argument and returns all words in a sentence capitalized except for: ["the", "a", "an", "but", "of", "and", "for", "at", "by", "and" "from"]. Also it always capitalized the first word.

Let's take a look a it bit by bit because this is the part I had the hardest time with. 

First, we have a variable called *exceptions* which holds an array of the words that are to be excluded from being capitalized. 

```
 static titleize(string){
    const exceptions = ["the", "a", "an", "but", "of", "and", "for", "at", "by", "from"];
```

Second, we have another variable called *words*. The variable *words" is set to the value *string.split(' ')*. 

```
const words = string.split(' ');
```
Here we are using the *.split method*. This method splits a string into an array of substrings and returns a new array. It doesn't change the original string. 
Since we are using (' '), it indicates that the string will be split between words. Meaning that whatever sentences is input as the string(argument) it will be split into an array of words and stored in the *words* variable. 

Now let's look at the next block of code.

```
for(let i = 0; i < words.length; i++){
     const word = words[i];
```

Here we have a *for loop*. this loop allows us to run the same code over and over, each time with a different value.
In the code above we have se the value of *i* to 0 as the start of our loop. The loop will run as long as the value of *i* is less then the length of the value of the variable *words*. Remember the variable *words* has the value of an array of words. So it'll go over each word in the array. 
Then we have a variable called *word* set to a value of words[i]. The *i* inside the brackets here represent an index number that will indicate which word to capitalize in the *words* array. 

Next we have an *if statement*:

```
if(i === 0 || !exceptions.includes(word)){
      words[i] = this.capitalize(word);
}
```
The *if statement* translates:
If the value of *i* is strictly equal(===) to 0 OR(||) the value of *word* is NOT(!) present in the *exceptions* variable. Then the value of *i* in *words[i]* is equal to 0 making it *word[0]* = this.capitalize(word). 
Since all three static methods are inside the *class Formatter*, we are able to call on this.capitalize static method to use it on the word variable. This last bit of code indicated that the first letter in will be capitalized if the *if statement* requirements are met. 

Lastly we have:

```
return words.join(' ')
```

Here we are using *.join(' ') method*. This method creates and returns a new string by concatenating all of the elements in an array. Returns an array as a string. 

This bit of code at the end will take the array stored in the variable *words* and return them as a string separated by a space between each word. Returning the string that was used as argument with the new changes. 

##Last Note
I hope I was able to make some sense in my explanations. I'm a newbie so I usually have a hard time putting my thought process in written form. I hope this helps my fellow newbies to understand all the methods mentioned a little better.

Thanks for reading!  

###Sources:

[Flatiron School](https://flatironschool.com/)
[MDN Static Method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#static_methods_and_fields)
[MDN Classes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes)
[w3schools Classes](https://www.w3schools.com/js/js_classes.asp)
[w3schools Static Method](https://www.w3schools.com/js/js_class_static.asp)
[w3schools .slice() Method](https://www.w3schools.com/jsref/jsref_slice_string.asp)
[w3schools .replace() Method](https://www.w3schools.com/jsref/jsref_replace.asp)
[MDN .replace() Method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace)
[w3schools .split() Method](https://www.w3schools.com/jsref/jsref_split.asp)
[w3schools for loop](https://www.w3schools.com/js/js_loop_for.asp)
[w3schools if else Statement](https://www.w3schools.com/js/js_if_else.asp)
[MDN .join() Method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join)