Introduction to React State Hooks

React hooks allows us to use state in function components. I find this method of using state easier than the old class-based version.

Import the useState hook from react before creating a function component.  The first thing to do is set the initial state.  Assign useState with the desired initial state as the parameter to an array as a const type variable.

const [count, setCount] = useState(0);

In the above example, we create a piece of state called count to store the value of a counter.  Inside the array, we place two items – the variable name for the state, and another variable to modify the state.  You may name these anything you like, but the convention is to use the name for the state preceded by ‘set’ for the modifier.  

The state variable cannot be modified directly.  We must use the second variable to change the state (setCount in this example).  Attempts to directly change the state will result in an error.

count = count + 1	// will cause an error
setCount(count + 1)	// will add 1 to the current state of the count variable.

The state may be passed down to the HTML render via JSX between the { }.

<h3>You clicked {count} times.</h3>

Since we have used the concept of a counter for this example, let us carry on by creating a counter component using the useState hook.

import React, { useState } from 'react';

const Counter = () => {
  const [count, setCount] = useState(0);
  return (
    <div>
      <p>You clicked { count } times!</P>
      <button onClick={() => setCount(count + 1)}>Click Me!</button>
        Click me!
      </button>
    </div>
  );
}

Clicking the button runs an anonymous arrow function which updates the state of count by calling setCount.  This is fine as a simple example, but you may also create the function separately and invoke it from the button.

We may expand our simple counter component by creating two functions, one for addition, another for subtraction.  Place these definitions above the return function.

const addCount = () => {
  setCount(count + 1)
}
const subtractCount = () => {
  setCount(count - 1)
}

Replace the button with two buttons, one for each function:

<button onClick={ addCount }> + </button>
<button onClick={ subtractCount }> - </button>

Here is the final component which now includes a button for addition and another for subtraction:

import React, { useState } from 'react';

const Counter = () => {
  const [count, setCount] = useState(0);
  
  const addCount = () => {
    setCount(count + 1)
  }
  const subtractCount = () => {
    setCount(count - 1)
  }
  return (
    <div>
      <p>You clicked { count } times!</P>
      <button onClick={ addCount }> - </button>
      <button onClick={ subtractCount }> - </button>
        Click me!
      </button>
    </div>
  );
}

Welcome to Deluxe Coding

Alleyway in Gumi City, South Korea
Gumi-si, South Korea
© 2012 Charles Dunlevy

I have decided to jump into this wild world of blogging because it allows me to combine two of the things I absolutely love into one! Amongst my peers, it is no secret that I love to write. Writing has been one of my favourite things since elementary school. I truly do believe that the pen is mightier than the sword. I guess today we can replace pen with pixels? Keys? Who knows.

During my middle school years, in place of writing in my English class journal, I would write code. I somehow moved away from code and found other interests which lead me to architectural technology and accounting. Currently, I work in the software industry and am still fascinated with computers and technology.

I began working as an analyst at a small software company way back in the stone age (or so it seems since time sure does fly). Over time, I rediscovered my love for coding and programming.

To be honest, I am still not sure what the difference between coding and programming is. I remember reading some heated discussions a while back regarding the use of these terms.

I am not an expert, but think I could still help others by writing about the vast world of computers while I continue learning and improving my skills. The great thing about this industry is that you will never know everything.

I hope that you find this site useful as we enjoy this wonderful world.

Overwhelmed by Code

Crunching numbers on a Chromebook
© 2017 Charles Dunlevy

In the Beginning

I started learning to code at the end of 2017. At the time, I was interested in Visual Basic for Applications (VBA) because I enjoy working with Microsoft Excel. I started to learn VBA in order to help me unleash more of Excel’s power and utility but did not expect this experiment to send me down the path to madness.

Google Apps Script

I have been using Excel at work for as long as I have been working in offices. In recent years, Google Sheets has been my go to outside of my day job. As I dabbled in VBA, I began to wonder if such a feature exists for Sheets. I stumbled upon a YouTube video introducing Google Apps Script (or as I like to call it, GAS).

Google Apps Script provides similar functionality for Google’s suite of applications to what Visual Basic for Applications provides for Microsoft’s suite.

The syntax for GAS was entirely different from VBA. The system runs online in the web browser and has easy access to web-based features and APIs. I soon discovered that GAS was actually a form of the JavaScript programming language which is used for websites.

JavaScript

Curious, I started to look into JavaScript. Since JavaScript is primarily used in web page design, I had to learn to make web pages using Hypertext Markup Language (HTML) and Cascading Style Sheets (CSS). The 3 go hand-in-hand in creating beautiful, animated, and interactive websites.

I quickly found myself enjoying JavaScript much more than VBA. To me, the syntax looks “cleaner” and the flexibility of being able to practice code using nothing more than the developer features of a web browser lead me away from VBA. I had learned most of the VBA that I needed for work and would only study it when needed.

There is are unbelievable amounts of online resources to study JavaScript. Answers to most problems are often only a quick search away via Google or Stack Exchange. I love to study via textbooks but found that there are not enough up-to-date books available.

JavaScript is a massive beast which spawned many systems such as frameworks. The web developer community seems to be split between a growing number of framework camps such as Angular, React, etc. I found this all quite overwhelming but quickly discovered that I prefer actual raw coding during my studies. I have yet to use a framework, but will be choosing one soon.

Coffee break with iPhone 4
© 2012 Charles Dunlevy

Thoughts

I found myself overwhelmed by the thought that I will never know everything. There is too much out there, and things keep changing rapidly. This may be the reason why up-to-date computer programming books are so scarce.

I started to wonder whether or not I should continue with my studies. Frustration arose whenever I found myself stuck on a problem. Pure joy and jubilation was the feeling whenever said problem was solved.

Advice and Inspiration

One day while reading articles online, an experienced developer stated that nobody knows everything in programming and that “Google is your friend.” He mentioned that everybody in the industry searches Google, looks items up in textbooks, or searches through sites like Stack Exchange, Quora, Reddit, etc. He said that computer programming is an ongoing learning process. He also said that you should focus on what you need to know to do the tasks you are working on. There is no sense in learning things that you do not or may never use.

I read similar sentiment from different developers online and even spoke with some at work and at the local bar. All pretty much said the same thing. This inspired me to keep going! Also, I find that I really do enjoy solving the problems. It is quite a euphoric feeling when you solve a problem and get the program to do something that you were previously stuck on. Each time I feel not only a sense of accomplishment, but inspiration.

Programming Languages

I also looked at code comparison between different languages. I learned that there are a lot of similarities between some languages such as C-based… at least when it comes to syntax or parts thereof.

JavaScript

A lot of people confuse JavaScript with Java. The two languages are similar in the first 4 characters of their names only. There is some syntactic similarities because both use C-based syntax. Java is an Object Oriented Programming (OOP) language while JavaScript was originally just a scripting language. Java is a massive beast in itself. It contains a lot of boilerplate code (extra code which may appear to be unnecessary at times). Java is a much more powerful language used in all aspects of computer programming.

Java

I started to study Java since I would love to write desktop and Android applications. It is also one of the most widely-used languages so there are a tonne of resources available.

Java seems far more difficult than JavaScript. I also realized that desktop applications are not a big market as everything these days seems to be mobile or web-based. I figured I could study Java to create Android applications and JavaScript for web-based applications.

Kotlin

Google announced that a new language called Kotlin was now the preferred language for Android. They will continue to support Java as well. I started reading articles about this new language which has in fact been in development since maybe 2011 if my memory serves me correctly.

The surprising thing to me was how every author mentioned that the code was clean and concise and a joy to write compared to Java. I started to read some tutorials and found the same thing. Where in Java it may take 8 lines of code for something simple, Kotlin would take maybe 3 or 4. The syntax is much nicer to read and write.

I quickly bought some Kotlin books so that I may study this language and make good use of it. Since I was only at the beginning stages of learning Java, I have decided to put that on hold and focus on Kotlin for now. Kotlin is a Java Virtual Machine (JVM) language that compiles to Java bytecode. It has been getting a lot of praise from Java developers for ease of use, clean syntax, and concise code.

Conclusion

Coding is definitely not for everybody, but if you like a) problem-solving and b) learning/studying, it is a great field to get into. I have always loved learning. I always believed that learning is a lifetime activity. One should not stop learning just because they finished school and started their career. Some careers such as computer programming or most tech-related fields involve a lifetime of learning as you can never know it all and it keeps evolving.

Tutorial Hell

Lately I have seen a lot of posts on social media regarding a concept called “Tutorial Hell.” One glance at YouTube and you will quickly see that the service has been inundated with computer programming tutorials. This is a great resource for both new and experienced programmers alike but it does have its pitfalls.

Some people end up in a position where the follow a bunch of tutorials but find they cannot start and complete projects on their own. Some even go as far as to create portfolios filled with projects created via tutorials.

I find that simply following tutorials can lead to a false sense of achievement. I remember following a quite complex tutorial, feeling proud upon completion, then realizing that I actually did not learn much. All I was doing was watching, pausing, writing code as seen on screen, the resuming. I would get frustrated at how often I had to pause and rewind to catch some code because the instructor was going too fast.

Some instructors do not actually instruct. Their tutorial comes across as more of a ‘follow me’ or even ‘look what I can do.’ These are the guys who record a tutorial where all they are doing is speeding through a project without explaining things.

On the other hand, there are a lot of great tutorials out there. Some guys and gals just have a real knack for coding and teaching. They explain concepts in a manner that not only teaches you how but also why.

Tips and Advice

A good way to learn from tutorials is to stop and take notes. Actually, even better is to watch the entire tutorial without coding. Just absorb the information and watch the coding. After that, go back and take notes. Then watch the tutorial again while coding along.

After that approach, you should have a better grasp at the concepts but don’t stop there. Go on an make tweaks to the project. Make it your own. Next step is to create your very own project using concepts learned from the tutorial. I find I learn better when working on my own project and encountering many, many, many errors and challenges along the way.

Conclusion

The world of tutorials does not have to be Hell. It is a great resource if used correctly. Remember, not all teachers teach the same way, just like not all students learn the same way. Some people are just really good at memorizing things, others require note-taking. Find the method which bests suits you and enjoy the wonderful world of computer programming!

Computer programming is actually part art and part science. I have learned that is is good to tell a story with your code. It will aid in readability for others who may work on your project as well as make maintaining your code a lot easier.

For more about telling a story with your code, feel free to read: https://www.g2i.co/blog/telling-a-story-with-your-code

5 Useful JavaScript String Methods

JavaScript contains a lot of useful methods. Today, we shall look at 5 useful methods for working with strings.

concat()
The concat() method is used to concatenate two or more strings.

const myString = "The quick brown fox";
const myOtherString = " jumped over the lazy dog.";

In this example, we have two string variables named myString and myOtherString respectively. Using the concatenate method, we can create a third string variable. Let’s name the new variable myNewString.

We assign the concatenated string to the new string variable by attaching the .concat() method to the end of the first string and inserting the second string as the only argument between the brackets.

const myNewString = myString.concat(myOtherString);

This results in the creation of a new string containing the combined text of the original two strings.

console.log(myNewString)
>> The quick brown fox jumped over the lazy dog.

In our example, we created a new string variable containing the results of the concatenation. We do not always have to create a new variable. The .concat() method can also work on its own. The only requirement is a variable to be attached to, and either another variable, text, or number inside the brackets.

console.log(myString.concat(' is 5 years old.'))
// The quick brown fox is 5 years old.

Using .concat() in the manner above is really not ideal. That example was to illustrate that the method works in different ways. It is much easier to use a + sign to display the contents of myString with additional items.

console.log(myString + ' is 5 years old.')
// The quick brown fox is 5 years old.

substring()
The substring() method is used to extract a portion of a string.

The substring method accepts up to two parameters:

substring(start, ?end)

1. start
2. end (optional)

The numeric position of strings is zero-based, just like in arrays. This means that the first character is 0, the second is 1, etc. For some reason, this method does not include the character which exists at the end position. Think of the end position as more of an ‘up to.’ To include this character, set the end to one number higher. If the start number > end, JavaScript will reverse the order therefore substring(10,5) == substring(5,10).

const myString = "The quick brown fox";

In the following example, we will create a new string containing the word ‘quick’ from the myString variable which contains ‘The quick brown fox’. The first letter in ‘quick’ is at position 4 and the last at position 8. In order to include the character at position 8, select 9 as the end position.

const myNewString = myString.substring(4,9);
console.log myNewString
// quick

If we want to extract ‘brown fox’, we do not need to specify and end position since fox is the last word in the string. All we need to do is specify the start position which is the position of first letter in ‘brown’.

const myNewestString = myString.substring(10);
console.log myNewestString
// brown fox

toUpperCase()
The toUpperCase() method is self-explanatory. It is used to convert a string to all caps.

const myString = "The quick brown fox";
const myNewString = myString.toUpperCase();
console.log(myNewString);
// THE QUICK BROWN FOX

toLowerCase()
The toLowerCase() method is like the toUpperCase() methods except it converts a string to lowercase.

const myString = "The quick brown fox";
const myNewString = myString.toLowerCase();
console.log(myNewString);
// the quick brown fox

repeat()
The repeat() method repeats a string a specified number of times.

const myString = "The quick brown fox";
myString.repeat(2);
// The quick brown foxThe quick brown fox

5 Useful JavaScript Array Methods

Residential condominium being built atop existing office building
© 2020 Charles Dunlevy

JavaScript contains a lot of useful methods. Methods are in fact functions which perform actions on the contents of an array, string, or object. To invoke a method, attach it to the end of the item after a decimal. Some methods require parameters entered within the brackets. These take on two forms:

array/string/object.method()

array/string/object.method(parameter)

Today, we shall look at 5 useful methods for working with arrays. The following perform a variety of actions on the contents of the array. Some mutate the array, others just return values.

join()

The join() method joins the elements of an array into a string. It does not mutate the original array.

const myArray = ["Toronto", "London", "Shanghai", "New York"];
myArray.join();
// "Toronto,London,Shanghai,New York"

By default, join() inserts a comma between each element as separators. You may specify different separators by entering characters, strings, etc. as the sole parameter. For example, you may insert a space between each element by entering a blank space between two single quotes within the parameter field. The is useful for creating a sentence out of a list of words/items.

myArray.join(' ');
// "Toronto London Shanghai New York"

myArray.join(' finance ');
// "Toronto finance London finance Shanghai finance New York finance"

You may also use join() to insert the values of one array into another. For example, join array1 with array2 to create a long string containing the contents of both arrays. This is performed by attaching the join() method to the end of array1 and passing array2 in as a parameter. The following example displays the result to the console.

const array1 = [1, 2, 3, 4, 5];
const array2 = ['a', 'b', 'c'];
array1.join(array2);
// "1a,b,c2a,b,c3a,b,c4a,b,c5"

The next example is similar to the previous one except we create a new array with the results of joining arrays 1 and 2.

const array1 = [1, 2, 3, 4, 5];
const array2 = ['a', 'b', 'c'];
const array3 = array1.join(array2);
console.log(array3);
// "1a,b,c2a,b,c3a,b,c4a,b,c5"

includes()

The includes() method checks for the existence of a specified element returning a Boolean value true or false. If searching for a string, remember, like everything else in JavaScript, this is case sensitive.

const fruits = ['apple', 'banana', 'strawberry'];
fruits.includes('banana');
// true
fruits.includes('kiwi');
// false

pop()

The pop() method is used to remove or ‘pop’ the last element off an array. Compared to some of the other methods used to mutate an array, ‘pop’ by name is easier to make sense of.

const days = ['Monday', 'Tuesday', 'Wednesday'];
days.pop();
// Wednesday
days;
// ["Monday", "Tuesday"]

push()

The push() method may be used when you would like to to add or ‘push’ a new element onto the end of an array. This too has a name that makes sense. We will look at other array-mutating methods at another date. I chose the two with the best names for today’s article.

const fruits = ['apple', 'banana', 'strawberry'];
fruits.push('pear');
// ["apple", "banana", "strawberry", "pear"]

reverse()

The reverse() method reverses the order of the array. This method does not mutate the array. In the following example, the reversed array is output to the console.

const someNumbers = [1, 2, 3, 4, 5];
someNumbers.reverse();
// [5, 4, 3, 2, 1]

The results may also be assigned to a new array by creating a new one with the original array containing the attached method.

const someNumbers = [1, 2, 3, 4, 5];
const reversedNumbers = someNumbers.reverse();
console.log(reversedNumbers);
// [5, 4, 3, 2, 1]

JavaScript array methods are very useful. There are several more to be discussed in future articles. New methods are being added from time to time when the ECMAScript standard updates (usually annually). Please visit http://www.ecma-international.org/ for more information.

JavaScript continues to grow and gain new features with each update. I am not sure if it is possible to know everything about JavaScript or any programming language for that matter. There is no need to learn every single thing. Just stick to what is needed for the task at hand.