Modern JavaScript From The Beginning: Section 2 – JavaScript Language Fundamentals (2 of 3)

This is the 2nd of 3 posts dealing with JavaScript Fundamentals from Brad Traversy‘s Modern JavaScript From the Beginning course on Udemy. It compares the course with Lambda material, from the pre-course and the full-stack developer track. (See part 1 here.)

Numbers & The Math Object

This section races through the Math object in JavaScript. Simple math, like addition, subtraction, multiplication, division and modulus are handled without use of the Math object. Its methods come into play for other calculations, including pi, rounding up or down, square roots, absolute values, exponentials, finding the minimum or maximum value in an array, generating a random number, and other functions.

The pre-course at Lambda gave examples of Math.pow, Math.round, Math.floor and Math.ceil. Modern JS gives examples of quite a few more, including using more than one at the same time (using “Math.floor(Math.random() * 20 + 1)” to generate a random integer between the numbers 1-20, which is probably fantastic for D&D players). I don’t recall going over additional Math methods during the main course at Lambda, so with regard to this topic, Modern JS gives examples of roughly 3X the number of Math methods as Lambda, although we’re generally advised to consult MDN for additional information, since this is something frequently done by developers out in the wild.

2-6 math
Using the Math object in JavaScript

String Methods & Concatenation

This lesson goes over concatenation, appending, escaping and then a series of string methods (some of which are also array methods).

Concatenation links or joins together two or more things. In JavaScript, concatenating 5 and 6 gives us 56. Concatenating “Alex” and “Webster” gives us “AlexWebster”, with no space in between. If we want a space, we have to concatenate that in, as well.

name = firstName + ' ' + lastName; //concatenation

Appending looks similar to concatenation in output, but is expressed through the += operator. Appending “Steve ” += “Digiorgio” gives us “Steve Digiorgio”.

name = "Steve ";
name += "DiGiorgio";
Steve DiGiorgio //appending

Escaping is new to me. Its not something that was covered at Lambda. Escaping essentially turns special characters into strings, so that they can be included in whatever needs to process or output a string with said character. The escape character is a “\”. For example:

names = 'J'onn J'onnz, Hawai'i, Muad'Dib, T'Challa, Drizzt Do'urden' //this will throw errors
names = 'J\'onn J\'onnz, Hawai\'i, Muad\'Dib, T\'Challa, Drizzt Do\'urden' //works
names = "J'onn J'onnz, Hawai'i, Muad'Dib, T'Challa, Drizzt Do'urden" //also works

w3schools has a section that explains escape characters some more. To my eye, when possible, enclosing the line with single quotes in double quotes seems to be the simplest way to go. In a situation in which both single and double quotes are used in the actual text or data, I can see how escape characters can save the day, however.

Additional topics discussed:

  • .length method
  • .concat method
  • .toUpperCase method
  • .toLowerCase method
  • treating a string like an array (firstName[3] returns the 4th letter in a name – they start at 0, like arrays)
  • .indexOf
  • .lastIndexOf
  • .charAt
  • getting the last character in a string: firstName.charAt(firstName.length -1);
  • .subString
  • .slice
  • .split
  • .replace
  • .includes

At Lambda, I remember seeing .length, .toUpperCase, .toLowerCase, .slice, .split and .includes. As mentioned before though, we were always advised to refer to MDN or w3schools to learn about additional methods, so I “unofficially” saw other methods, especially during sprint challenges.

During the JavaScript Fundamentals sprint at Lambda, I remember we went pretty hard into all kinds of methods, especially those for sorting and pulling out specific pieces of data from arrays and objects. There were exercises and challenges that stumped me for hours every day during that week.

That particular sprint is especially intimidating for people new to coding, as it moves from early concepts like variables, arrays, objects and functions to more difficult concepts like closure, callback functions, advanced array methods, “this”, prototypes, constructor functions, “new”, pseudo-classical inheritance and classes. After that, we’d have our first Build Week and then move into DOM manipulation and JavaScript components. Many students end up flexing into another cohort to repeat that section, and I nearly did it too. Its the sprint that really put the fear of not being able to grasp basic programming concepts into me. Getting over that can only be done by overcoming the obstacle, though, so I’m glad that its also all in this course. One piece of advice that floats around at Lambda is that if a concept is giving you trouble, you probably need “more reps”. To me, that’s essentially what this entire Modern JS course is.

2-7 string methods
String methods in JavaScript

Template Literals

I love template literals. They’ve helped me clean up my code quite a bit and include variables in places in which I didn’t previously know how to do so. Sometimes, in React, when writing JSX, I’ve confused myself a bit while using them, but overall they’ve added a lot of flexibility to my code.

So, what are they? They’re strings of data that are encapsulated by backticks instead of single or double quotes. Inside of these strings, variables, expressions or even functions can be included by surrounding them with a dollar-sign and curly braces, like this: ${variableName}. Here’s how that concatenation example from the previous section could look using template literals (also called string literals):

name = firstName + ' ' + lastName; //concatenation
name = `${firstName} ${lastName}`; //string literal

Note that we no longer need to have the plus signs and the apostrophes surrounding a space. This is because the string literal reads the space between the two variables as a space and just includes it. Its especially useful for React. I use it inside of JSX all the time. I also used it a lot when I was code to manipulate the DOM in JavaScript and needed it to render the values of data being looped through in arrays or objects into HTML.

I can’t remember when we learned about string literals at Lambda, and a search in the JavaScript Fundamentals material and the Applied JavaScript material shows object literals, but not string literals or template literals. I do remember my original TL, Reed, going over them with us, so maybe it was something that he showed us, and not something that was covered in the curriculum, but I recall using them on a sprint challenge and in my portfolio, and then in React. I also know that I used them when we learned about components in JavaScript, because its been a habit since.

2-8 template literals
Template literals (also called string literals)

Arrays & Array Methods

This video starts off by briefly describing what an array is and then showing viewers how to create one in two different ways – by simply creating a variable and setting it to an array of some sort of data, and by using the “new Array” constructor. We see how an array can hold different types of data, like an array of numbers or an array of strings, and we see how it can hold a variety of different types of data all at once by seeing an array that has data from every data type we’ve seen so far.

Then, it dives right into array methods and properties, including the following:

  • .length (how long is an array, or how many elements does it contain)
  • Array.isArray() (is the item in the parenthesis actually an array)
  • getting a single value based on an element’s array index (num = numbers[2];)
  • inserting data into an array via array index (numbers[3] = 213;)
  • .push (add to end of array)
  • .unshift (add to beginning of array)
  • .pop (remove from end of array)
  • .shift (remove from beginning of array)
  • .splice (remove an element or a range of elements from an array)
  • .reverse (reorders an array backwards)
  • .concat (combine two arrays into a single array)
  • .sort (rearranges an array’s elements in alphabetical order if strings; if numbers it sorts based on first number, so 100 would come before 2 – to fix this we’d include a “compare function” that could look like the below code)
    sorted = numbers.sort(function(x, y) {
      return x - y;
    });
  • sort numbers in the other direction by returning “y – x” instead of “x – y”
  • writing a “finding function”

Some of the array methods from this video were also included in the Lambda material. .length, .push, .pop, .unshift and .shift were all introduced during the pre-course. In the main web developer curriculum, methods that haven’t been shown in Modern JS yet were also covered, including .forEach, map, .filter and .reduce.

2-9 arrays
Several arrays & array methods

Object Literals

An object literal is a comma-separated list of key-value pairs enclosed in a pair of curly braces. From what I can infer, it seems to be a single object.

const humanEraDeath {
  guitarVox: 'Chuck Schuldiner',
  guitar: 'Paul Masvidal',
  bass: 'Steve DiGiorgio',
  drums: 'Sean Reinert'
}

Where arrays tend to contain a set of data that are essentially each elements of their own, objects tend to contain a set of data about the same thing. Think of an array of people, each with their full names – each of these could even be an object, itself. An object, on the other hand would be one of these people, potentially with deeper data, like first name, last name, address, email, phone number, and so on. Arrays can contain objects (like if each of the people in our array above was an object with all of the data from the object example that followed), and objects can contain arrays (like if the phone number in each person’s object included entries for home, cell and work numbers).

This lesson shows viewers how to create an object literal, and then how to get a specific value from that object – like a person’s first name or last name – using dot notation and then bracket notation. It also goes over how to get data out of a nested array inside of an object, something that gave me a considerable amount of trouble during a sprint challenge that had something like an array of objects that each had an array of more data as one of their key-value pairs. If I remember right, it turned out that I needed to use bracket notation, and I had wasted a lot of time failing to get the data I needed with dot notation.

It also shows something that I found interesting: functions inside of an object. I think we did go over this at Lambda, but I haven’t used it since being introduced to it, except maybe when we worked with prototypes or some other constructor.

Finally, it closes by showing how to iterate over an array of objects, which is exactly what I had trouble with during one of the sprint challenges at Lambda.

I think that the big differentiator between this lesson and what we learned at Lambda is that this particular lesson focuses on creating an object and then reading data from it, whereas Lambda’s pre-course went a bit further in. The pre-course explained object definition, key-value pairs, and how to access data via dot or bracket notation, like here, but then forged ahead to include assigning values, removing properties, methods, for/in loops and the “this” keyword. We also learn that everything in JavaScript is an object – even arrays and strings are actually objects!

2-10 objects
An object literal

Dates & Times

Dates and time in JavaScript are new to me. I don’t think we covered this at Lambda so far, so this is uncharted territory. From this video, it seems fairly straightforward. Dates are objects and they contain the date (month, day year) and a timestamp, including time zone.

Dates can be converted from objects to string with the .toString method. Calling a new date (new Date()) returns the current date and time. A specific date can also be called or assigned to a variable by specifying it in the parenthesis of the Date() function. This can be done in several formats:

const birthday = new Date('5-17-1975');
const birthday = new Date('5-17-1975 07:15:00');
const birthday = new Date('May 17 1975');
const birthday = new Date('5/17/1975');

Several methods were also reviewed, including:

  • .getMonth() (returns the month as an integer – it starts at 0 for January, not 1)
  • .getDate() (returns the date of the month, so May 17th would return 17)
  • .getDay() (returns the day as an integer, with Sunday being 0)
  • .getFullYear() (returns the year as a 4-digit integer)
  • .getHours() (returns the hour of the day, so 7:00 AM would return 7)
  • .getMinutes() (returns the minute of the hour, so 7:30 AM would return 30)
  • .getSeconds() (returns the second of the minute)
  • .getMilliseconds() (returns the millisecond of the second, for those who waste no time)
  • .getTime() (returns a timestamp, which is the number of seconds that has passed since January 1, 1970!)

Most of these methods have complimentary methods that can set their data as well. To do this, just change the .get in each method to .set. For example, .setMonth(2) sets the month to March (0 = Jan, 1 = Feb, 2 = March).

2-11 dates and time
Date and time methods

 

2 thoughts on “Modern JavaScript From The Beginning: Section 2 – JavaScript Language Fundamentals (2 of 3)

Leave a comment