Beyond the Basics - Hello JavaScript | Programming Fundamentals: Learn to program with JavaScript (2016)

Hello JavaScript | Programming Fundamentals: Learn to program with JavaScript (2016)

Beyond the Basics

JavaScript is a multi-paradigm programming language. The main reason for this is to give developers a wide variety and options to freely create and develop on their selected paradigm. Each paradigm has advantages and disadvantages, and depending on the problem at hand, each methodology is more suitable for a specific type of problem than others.

This chapter is a light introduction to more advance topics in programming. Each of these topics can be expanded into their own books, e.g., Functional Programming, Object Oriented Programming, Software Engineering, etc. This chapter is used to provide you with an introduction to these more advanced topics and to start moving your skills as a programmer to the next level.

Each of the sections provides you with an introduction to these larger topics, along with some examples of the most common features that you will use as a new programmer.

No programming challenges are required for this chapter, since it’s just an introduction into these more advance topics.

Functions and Scope

“The full beauty of the subject of generating functions emerges only from tuning in on both channels: the discrete and the continuous.” - Herbert Wilf

JavaScript supports both functions and methods. The majority of the functionality that JavaScript provides is a set of predefined functions. These functions are pieces of predefined code that do some specific task such as print out a result to the terminal like console.log.

Functions naming conventions are the same as that of variables. They must have a unique identifier and not conflict with each other.

Pro Tip

When learning a new framework i.e Angular, Backbone, React, Underscore, etc the biggest challenge will be learning about all the functions available to you.

Use the following rule of thumb when creating new functions:

1. Give your functions a readable name

2. Know the parameters of a function

3. Know what to expect out of a function

Below, there is an illustration of a function g(x) that requires an input x and outputs value. The name of the function is clear and concise, the parameters are clear, and we know what to expect as output.

However, it’s unknown to us what exactly g(x) is doing. This is a key concept of functions—being able to use a function abstractly and get a requested output from it. This allows you to focus on the problem that you are attempting to solve instead of all of the details that go into g(x).

Function

Functions in JavaScript are “First Class Citizens”. In other words, JavaScript supports passing functions as arguments to other functions, returning functions as the values from other functions, assigning functions to variables, and storing functions in a data structure. JavaScript supports higher-order functions, non-local variables in nested functions, anonymous functions, and closures.

Why use functions in the first place?

Functions are useful because they allow us to wrap up a piece a code that does one specific task, and only one task. In turn, this helps us to create large code bases with useful names allowing for code reuse to construct even more complex programs in record time.

Function Definition

1 /*

2 Raises a base number to a selected exponent.

3 Returns value of base to exponent b^e

4 */

5 var power = function(base, exponent){

6 if (exponent == 0) {

7 return 1; // Base Case

8 }

9 if (exponent > 0) {

10 return base * power(base, exponent - 1);

11 }

12 };

13

14 console.log(power(2,5));

Results

1 32

In the example above, the variable power is assigned to a function. Anytime you want to use the function, you would just use the variable assigned to that function with parenthesis power(2,5); If a function has no parameters, use the name of the function along with a pair of empty parenthesispower();.

All functions must contain the keyword function along with a pair of braces {} and parenthesis (). Functions don’t need to have a name nor parameters. Functions can optionally return an explicit value; otherwise, all functions return the value of undefined.

Function Definitions

1 // function with the name power

2 function power(base, exponent){

3 // Code Block

4 }

5

6 // function with out parameters

7 function hello() {

8 console.log('hello');

9 }

Functions can wrap code that is used over and over again, which allows you to reuse code without having repetitive pieces of code all over the place.

The best way to find the right name for a function, is to be able to think about what the responsibility of the function will be. This is where having a strong background in Unix comes in handy. Take for example the code below. It’s composed from the smaller programs curl, grep, |, and >>. Each of them do exactly one thing and because of this single responsibility we can start to create larger and more complex programs based on simpler programs.

Sample

1 curl -i https://www.jsecademy.com | grep 'JavaScript' >> JSecademy.md

JavaScript also supports self-executing functions. This type of function is useful for creating a local scope to variables. All variables declared within the self-executing function are, by default, only available within the self-executing function. This helps create separation from other functions, preventing naming conflicts with other variables or functions.

Example of self-executing function

1 //Anonymous function

2 (function(){

3 // Code

4 }());//() Executes immediately

Self-executing function with parameters

1 var url = 'http://jsecademy.com'; // Global variable

2 (function(URL){ // Parameter

3 console.log(URL); // Local variable

4 }(url)); // Passing Global variable

Results

1 http://jsecademy.com

Parameters and Scopes

All functions in JavaScript can have parameters and scopes. Function parameters are optional and the amount of them can vary. All parameters in JavaScript are passed by reference, meaning that once the variable enters a function it will be in scope for that function. If the value changes inside that function, it will not affect the value outside the function.

On the function level scope, any new variables declared by the keyword var will only exist inside the local scope unless it’s returned back by using the keyword return.

Global variable passed by reference:

1 var url = "http://jsecademy.com"; // global variable

2 function printURL(url) {

3 console.log(url);

4 }

5 printURL(url);

Local Variables

1 function printURL() {

2 var url = "http://jsecademy.com"; // local scope variable

3 console.log(url);

4 }

5 printURL();

Results

1 http://jsecademy.com

Local variables prevent your program from conflicting with other local variables in other functions. This allows you to use the same variable names in two different locations this concept is also known as private variables.

Function Composition

Function of Functions

Function composition, also known as function of functions, is where the result of one function is used as the input to another function, resulting in a third function. This allows for simple functions to build up to more complex ones. Since JavaScript treats all functions as first class citizens, function composition is highly encouraged to be used throughout an application.

Example of Function Composition

1 (function printURL() {

2 var url = 'http://jsecademy.com'; // Local variable to printURL()

3 console.log('Original URL:', url);

4

5 // Requires URL without prefix

6 function secureURL(url) {

7 var securePrefix = 'https://'; // Local variable to secureURL()

8 url = securePrefix + url;

9 return url;

10 }

11

12 // Returns prefix from URL

13 function URLPreFix(url) {

14 if (url.substr(0, 'http://'.length) === 'http://') {

15 return 'http://';

16 }

17 if (url.substr(0, 'https://'.length) === 'https://') {

18 return 'https://';

19 }

20 }

21

22 // Return URL with out prefix, requires prefix

23 function URLWithOutPreFix(url, prefix) {

24 if (prefix === 'http://') {

25 return url.substr('http://'.length, url.length);

26 }

27 if (prefix === 'https://') {

28 return url.substr('https://'.length, url.length);

29 }

30 }

31

32 console.log('Secure URL:', secureURL(URLWithOutPreFix(url, URLPreFix(url))));

33 })();

Results

1 Original URL: http://jsecademy.com

2 Secure URL: https://jsecademy.com

In the example above, there is a self-executing function named printURL() that is executed right away. Inside the scope of printURL() there are three functions: secureURL(), URLPreFix(), and URLWithoutPreFix(). All of three of these functions are used in composition to create a secure URL. First, the URLWithoutPreFix() function requires a url and a prefix. The prefix can be obtained by using URLPreFix() function, which requires a url. Then, URLWithoutPreFix() returns a url without a prefix that is used by the secureURL() function and returns a url with the prefix of https://.

Composed like this, the code is not coupled to just converting URL’s to https://. Instead, it is broken up into multiple functions that can be used independently for specific tasks if need be.

JavaScript Code Sample

1 var url = 'http://jsecademy.com';

2 console.log('Original URL is:', url);

3 // Return URL with out prefix, requires prefix

4 function URLWithOutPreFix(url, prefix) {

5 if (prefix === 'http://') {

6 return url.substr('http://'.length, url.length);

7 }

8 if (prefix === 'https://') {

9 return url.substr('https://'.length, url.length);

10 }

11 }

12

13 // Returns prefix from URL

14 function URLPreFix(url) {

15 if (url.substr(0, 'http://'.length) === 'http://') {

16 return 'http://';

17 }

18 if (url.substr(0, 'https://'.length) === 'https://') {

19 return 'https://';

20 }

21 }

22

23 console.log('URL Prefix is:',URLPreFix(url));

24 console.log('URL With out Prefix is:',URLWithOutPreFix(url, URLPreFix(url)));

25 console.log('URL With optional Prefix is: //' + URLWithOutPreFix(url, URLPreFix(\

26 url)));

Results

1 Original URL is: http://jsecademy.com

2 URL Prefix is: http://

3 URL With out Prefix is: jsecademy.com

4 URL With optional Prefix is: //jsecademy.com

From the example above, URL’s can now be manipulated into three options: with prefix, without prefix, or with the optional prefix that works with any type of prefix.

Recursion

Recursion

Recursion is one of the topics that differ from the normal control flow of programs. The reason for this is that recursion is the act of calling a function from within itself. A recursive function MUST have a base case to terminate all of the calls made; otherwise, the stack will overflow with recursive calls.

Example of power function with recursion

1 /*

2 Raises a base number to a selected exponent.

3 Returns value of base to exponent b^e

4 */

5 var power = function(base, exponent){

6 if (exponent == 0) {

7 return 1; // Base Case

8 }

9 if (exponent > 0) {

10 return base * power(base, exponent - 1);

11 }

12 };

13 console.log(power(2,5));

Results

1 32

Example of a enumeration with recursion

1 function enumartion(start,end) {

2 console.log(start);

3 if (end == 1)

4 return 1;

5 else

6 return enumartion(start + 1, end - 1);

7 }

8 enumartion(1,10);

Results

1 1

2 2

3 3

4 4

5 5

6 6

7 7

8 8

9 9

10 10

How many calls does it take to overflow the stack? This depends on what platform JavaScript is running.

Testing Recursion call Stack

1 (function(){

2 var count = 0;

3 function computeMaxCallStackSize(){

4 try {

5 count++;

6 return computeMaxCallStackSize();

7 } catch (e) {

8 return;

9 }

10 }

11 computeMaxCallStackSize();

12 console.log(count);

13 }());

Results

Platform

Calls

node

11434

Chrome

17926

Safari

50723

Firefox

107375

Objects

OO is about managing dependencies by selectively re-inverting certain key dependencies in your architecture, so that you can prevent rigidity, fragility, non reusability. - Uncle Bob

Programming paradigms come and go, but object-oriented programming has had constant growth since the term “Object Oriented Programming” was first coined by Alan Kay in the 1970s and gained wide adoption by the early 1980’s.

Up to this point, most of the programs from the examples have been functional programs or procedural programs. In a procedural programming paradigm, procedures work on data; in a functional programming paradigm, functions evaluate to other functions; and now in object oriented programming, the focus will be to create objects that contain both properties and methods that model them according to a specification.

JavaScript provides a wide range of objects that are defined with a preset value. Each of these objects has specific procedures (methods) and properties that can accomplish a wide variety of tasks. Since object oriented programming (OOP) is an entirely more advanced topic, we will only be covering the most basic and common objects that you will use, which are generic Objects, Arrays, Numbers, Dates, and Regular Expressions.

Below you will see an image of an object that is a light. It contains both methods and properties. The property is the simple one of a state, which holds the current state of the light (if it’s on or off). The object also has three methods, which are switch(), turnOff, and turnOn. The switch toggle will either turn the light on or off depending on what the state of the light is. This should start to give you an idea of how objects are used.

Light Object

Data types are grouped into two different parts: primitives or composites. Each of these data types include predefined function definitions that can help you create your application. Composite data types can help you extend a primitive data type to do something completely different. This is a more advanced topic that is beyond the scope of this book. The remaining parts of this book will focus on how to use this predefined functionality that the JavaScript programming language provides for you.

Strings

Strings are a primitive data type that JavaScript includes in the language. Strings can be used to represent a sequence of characters.

Here are the most common string operations for mutating a string:

Methods

Method

Description

toString()

Returns the value of a string

toLowerCase()

Returns a new string that is all lowercase

toUpperCase()

Returns a new string that is all uppercase

charAt(index)

Returns the character at the specified index

concat(string)

Returns a new string composed from the strings passed in as a parameter

Properties

Property

Description

length

Returns the length of a string

Strings can be made all lowercase. JavaScript provides you with the toLowerCase() method. This method does not mutate the original string; instead, it returns you a new string that is all lowercase.

JavaScript Code Sample

1 var firstName = "Kimberly";

2 var lowercase = firstName.toLowerCase();

3

4 console.log(firstName);

5 console.log(lowercase);

Results

1 Kimberly

2 kimberly

Just like you can go all lowercase, you can also go all uppercase with the toUpperCase() method. This method does not mutate the original string; instead, it returns you a new string that is all uppercase.

JavaScript Code Sample

1 var firstName = "Kimberly";

2 var uppercase = firstName.toUpperCase();

3 console.log(firstName);

4 console.log(uppercase);

Results

1 Kimberly

2 KIMBERLY

Programs might require you to verify that a string is of a certain length. This is such a common request that in JavaScript, all strings have the .length property to identify the length of a string.

JavaScript Code Sample

1 var firstName = "Kimberly";

2 var length = firstName.length;

3 console.log(length);

Results

1 8

Now that you know the length of the string, you can iterate over the string and use the charAt() method to display the letter at a given index position.

JavaScript Code Sample

1 var firstName = "Kimberly";

2 for (var i = 0; i < firstName.length; i++) {

3 var character = firstName.charAt(i);

4 console.log(character);

5 }

Results

1 K

2 i

3 m

4 b

5 e

6 r

7 l

8 y

Concatenating Strings

When you would like to combine more than one string, you can use concatenation with the + addition operator. The most common use cases of concatenation of strings are the following:

1. Combination of multiple strings to compose a message

2. Displaying a value in a single line instead of multiple lines

Pro Tip

JavaScript combines two or more strings together to compose a new string.

Example of concatenating strings.

JavaScript Code Sample

1 var firstName = "Kimberly";

2 var lastName = "Thompson";

3

4 var fullName = firstName + " " + lastName;

5 console.log(fullName);

Results

1 Kimberly Thompson

In the example above, three variables are used: firstName, lastName and fullName. The variable fullName is composed of firstName, an empty space " ", and lastName. Take special note of the empty space. We could have stored that space character in a variable, but instead we took advantage of the + addition operator to concatenate the strings.

JavaScript makes the operation of concatenating strings even easier with the concat() method. The function will join two or more strings to compose a new string.

JavaScript Code Sample

1 var firstName = "Kimberly";

2 var lastName = "Thompson";

3

4 var fullName = firstName.concat(" ", lastName, ".");

5 console.log(fullName);

Results

1 Kimberly Thompson.

In this example, four strings are joined together: firstName, an empty space " ", lastName, and the period ..

Pro Tip

The concat() function is specially useful when creating complex strings.

Summary

This is just a sample of what JavaScript strings can do. If you would like to see the full documentation for all the functions and methods that are available to you when working with strings, check out the complete JavaScript Reference.

Data Structures

In Computer Science, you will find a wide variety of data structures that you can manipulate in your programs. For example, hash maps, arrays, associative arrays, graphs, lists, stacks, queues, and trees, just to name a few. Don’t worry. This is an entire section of Computer Science that is not covered in this book.

JavaScript provides you with one of these fundamental data structures which is the array. We have taken a look at them in the previous chapter, but now we will be taking our existing knowledge of objects and arrays and exploring how JavaScript can help us work with them.

Remember, arrays are just a data structure that stores related information together in a location in memory.

The following are the most common array operations for removing and adding items to an array:

Method

Description

push(item)

Adds item to the end of the array

unshift(item)

Adds item to the beginning of the array

pop()

Removes last item in the array

shift()

Removes first item in the array

Adding to an array

At this point, you should be fairly comfortable with adding items to any array based on an index.

Example of adding an item to an index

1 var names = [];

2 names[10] = "Brandy";

3 console.log(names[10]);

Results

1 Brandy

There will be cases where you won’t know the exact index location of where the item needs to be inserted. The push() method will add the item to the last available element location of the array.

Example of adding an item to an index

1 var names = ["Brandy"];

2 names.push("Ferguson");

3 console.log(names);

Results

1 [ 'Brandy', 'Ferguson' ]

The unshift() method will add the item to the beginning of the array and shift all the elements one location to the right.

JavaScript Code Sample

1 var names = ["Brandy" , "Ferguson"];

2 names.unshift("Megan");

3 console.log(names);

Results

1 [ 'Megan', 'Brandy', 'Ferguson' ]

Removing from an array

JavaScript supports multiple methods for removing items from an array. The easiest option is to set the value of a predefined location to be undefined. This partially works.

JavaScript Code Sample

1 var names = ["Brandy", "Ferguson"];

2 names[1] = undefined;

3 console.log(names);

4 console.log(names.length);

Results

1 [ 'Brandy', undefined ]

2 2

The value of index 1 is set to zero, but the length of the array remains at 2. This could be behavior that you want, but for most use cases you would want to remove the element and change the length of the array.

This is where the pop() method comes in handy. It will remove the last element of the array and change the length of the array.

JavaScript Code Sample

1 var names = ["Brandy", undefined];

2 names.pop();

3 console.log(names);

4 console.log(names.length);

Results

1 [ 'Brandy' ]

2 1

Pro Tip

JavaScript also supports the keyword delete to set a value of an array to undefined

If you want to remove an item from the beginning of the array you can use shift() method.

JavaScript Code Sample

1 var names = ["Brandy", "Ferguson"];

2 names.shift();

3 console.log(names);

4 console.log(names.length);

Results

1 [ 'Ferguson' ]

2 1

Mutating Arrays

Using arrays as a data structure can become very useful when mutating an array to do a specific task. JavaScript gives you a wide support for a variety of functions for mutating arrays that are pre-defined in the language.

The following are the most common operations for mutating an array:

Method

Description

toString()

Converts an array into a string

join(‘delimiter’)

Joins all items in array to a string with an optional delimiter

splice(startIndex, howManyToRemove, itemToAdd1, itemToAdd2)

Adds or removes from an array; returns items removed

slice(startIndex, endIndex)

Returns a new array with selected index

sort()

Sorts items of array alphabetically

reverse()

Reverses the order of the array

concat(array[])

Joins two or more arrays

indexOf(item)

Searches array for an item and returns index

JavaScript arrays will automatically be turned into a string when outputting their values to the console. This is because the console object is invoking the toString() method behind the scenes. If you want to convert an array without the console, just use the toString() method.

JavaScript Code Sample

1 var names = ["Brandy", "Ferguson"];

2 var string = names.toString();

3 console.log(typeof string);

4 console.log(string);

Results

1 string

2 Brandy,Ferguson

The names are pre-formatted with a , comma when using the toString() method. You can alter this behavior by using the join() method on the array. When you join the array you can set a specific delimiter when each of the items is concatenated.

Pro Tip

Remember the join() method does not mutate the original array.

JavaScript Code Sample

1 var names = ["Brandy", "Ferguson"];

2 var mutatedArray = names.join('|');

3 console.log(mutatedArray);

Results

1 string

2 Brandy|Ferguson

If you have a predefined index and know how many items you want to remove or insert into the array, then the splice() method will do exactly this. The method requires starting location to add or remove items, how many items to remove, and the number of items N to add into the array.

JavaScript Code Sample

1 var names = ["Brandy", "Ferguson"];

2 names.splice(1,0,"Megan");

3 console.log(names);

Results

1 [ 'Brandy', 'Megan', 'Ferguson' ]

In the code example, we know the location to start the removal of items is 1, and it removes items in the array up to 0, which is no items in the array. Then, the last part is to insert into the array item Megan.

Arrays can output other arrays. The slice() method will return a new array that contains values from the original array. The method takes two arguments: the start index and the end index. The start index will remove all the elements up to one less than the end index. If you omit the second parameter, the method will automatically use the length property and return all items from the start index to the length of the array.

JavaScript Code Sample

1 var names = ["Brandy", "Ferguson", "Megan"];

2 var arrayOfNames = names.slice(0,2);

3 console.log(arrayOfNames);

Results

1 [ 'Brandy', 'Ferguson' ]

JavaScript has full support for sorting an array into alphabetical order, meaning that if you have any numbers in an array they will take precedent over letters. The sort() method will mutate the current array and return that mutated array.

JavaScript Code Sample

1 var names = ["Megan", "Brandy", 323, "Ferguson"];

2 names.sort();

3 console.log(names);

Results

1 [ 323, 'Brandy', 'Ferguson', 'Megan' ]

JavaScript has full support for reversing an array. If you remember back to the code that reversed an array, it’s a trivial piece of code, but thanks to JavaScript support you won’t have to write this implementation yourself.

JavaScript Code Sample

1 var names = ["Megan", "Brandy", 323, "Ferguson"];

2 names.reverse();

3 console.log(names);

Results

1 [ 'Ferguson', 323, 'Brandy', 'Megan' ]

JavaScript supports the ability to combine two or more arrays to compose a new array. Using the concat() function, you can combine as many arrays as you like. The order you pass each of the arrays into the function is the order they will be combined into the new array.

JavaScript Code Sample

1 var girlsNames = ["Megan", "Brandy"];

2 var boysNames = ["Ferguson"];

3 var luckyNumbers = [323];

4 var combinedArrays = girlsNames.concat(luckyNumbers, boysNames);

5 console.log(combinedArrays);

Results

1 [ 'Megan', 'Brandy', 323, 'Ferguson' ]

JavaScript also supports the ability to find an item’s index based on its value with the indexOf() function. The way this function works is when you pass in a valid value within the array, it returns the index of that value. If the value does not exist in the array, the function will return -1 to signify an invalid item.

JavaScript Code Sample

1 var names = ["Megan", "Brandy", "Ferguson"];

2 var name = names.indexOf("Brandy");

3 var invalidName = names.indexOf("Becky");

4 console.log(name);

5 console.log(invalidName);

Results

1 1

2 -1

Summary

This is just a sample of what JavaScript can do. If you would like to see the full documentation for all the functions and methods that are available to you when working with arrays, check out the complete JavaScript Reference.

Numbers

JavaScript has only one type of number. Numbers can be written with, or without, decimals.

JavaScript Code Sample

1 var integer = 7;

2 var float = 3.14159;

Unlike many other programming languages, JavaScript does not define different types of numbers such as integer, short, long, and floating points. Numbers are always stored as double precision floating point numbers, following the international IEEE 754 standard.

Precision:

1. Integers are considered accurate up to 15 digits.

2. Decimals’ max length is 17 digits after the decimal, but are not always 100% accurate.

Numbers have Properties and Methods that are available to you as a programmer.

Number Properties

Property

Description

MAX_VALUE

Largest number possible in JavaScript

MIN_VALUE

Smallest number possible in JavaScript

NEGATIVE_INFINITY

Negative infinity

NaN

Not-a-Number value

POSITIVE_INFINITY

Infinity

You can use the Number object to obtain the properties of a number.

Example of properties:

JavaScript Code Sample

1 console.log(Number.MAX_VALUE);

2 console.log(Number.MIN_VALUE);

3 console.log(Number.NEGATIVE_INFINITY);

4 console.log(Number.NaN);

5 console.log(Number.POSITIVE_INFINITY);

Results

1 1.7976931348623157e+308

2 5e-324

3 -Infinity

4 NaN

5 Infinity

Number Methods

JavaScript provides several methods to you for working with numbers. Here is a list of the most common methods that are used in programs:

Method

Description

toExponential()

Converts a number into an exponential notation

toFixed(y)

Formats a number with y numbers of digits after the decimal point

toPrecision(y)

Formats a number to y length

toString()

Converts a number to a string

valueOf()

Returns the primitive value of a number

JavaScript Code Sample

1 var age = 32;

2 console.log(age.toExponential());

3 console.log(age.toFixed(2));

4 console.log(age.toPrecision(8));

5 console.log(age.toString());

6 console.log(age.valueOf());

Results

1 3.2e+1

2 32.00

3 32.000000

4 32

5 32

Summary

This is just a sample of what JavaScript numbers can do. If you would like to see the full documentation for all the functions and methods that are available to you when working with numbers, check out the complete JavaScript Reference.

Dates

Dates are an important part of any modern program. JavaScript provides you with the Date object. This object can be used to work with time zones or date mutations.

JavaScript’s Date object requires you to use the new operator. If you omit the new operator, the Date() function will return today’s current date as a string.

The most common use cases for dates are the following:

Get Methods

Method

Description

getDate()

Returns the day of the month (from 1-31)

getMonth()

Returns the month (from 0-11)

getFullYear()

Returns the year (four digits)

Set Methods

Method

Description

setDate(day)

Sets the day of the month of a date object

setMonth(month, day)

Sets the month of a date object

setFullYear(four digits)

Sets the year (four digits) of a date object

JavaScript Code Sample

1 var today = new Date();

2 console.log(today);

3 console.log(today.getDate());

4 console.log(today.getMonth());

5 console.log(today.getFullYear());

6

7 var yesterday = new Date();

8 yesterday.setDate(today.getDate()-1);

9 console.log(yesterday);

10

11 var lastMonth = new Date();

12 lastMonth.setMonth(today.getMonth()-1);

13 console.log(lastMonth);

14

15 var lastYear = new Date();

16 lastYear.setFullYear(today.getFullYear()-1);

17 console.log(lastYear);

Results

1 Sat Dec 05 2015 15:46:06 GMT-0700 (MST)

2 5

3 11

4 2015

5 Fri Dec 04 2015 15:46:06 GMT-0700 (MST)

6 Thu Nov 05 2015 15:46:06 GMT-0700 (MST)

7 Fri Dec 05 2014 15:46:06 GMT-0700 (MST)

Summary

This is just a sample of what JavaScript Dates can do. If you would like to see the full documentation for all the functions and methods that are available to you when working with Dates, check out the complete JavaScript Reference.

Regular Expressions

JavaScript supports regular expressions. You probably have not heard of regular expressions before. They tend to be called other names, such as “Regex” or “Regexp”.

In simplest terms, a regular expression is a way that we can express a description of a string.

Regular expressions have many useful use cases; for example, evaluating if a string matches a pattern, extracting specific parts of a string, or replacing parts of a string.

Regular expression syntax Every single regular expression starts with a / and ends with a /. What goes in between is the pattern that you are trying to match.

Pattern

At the end of the expression you can use a flag to specify a specific function. Here is the list of flags that JavaScript offers:

Flags

Flag

Description

g

Global match

i

Ignore case

m

Multiline

Flags

The flags specific order does not have any precedence; for example, gi and ig are the same.

Creating Patterns

JavaScript supports two methods for creating regular expressions.

1. Variable expressions

JavaScript Code Sample

1 var regex = /car/ig

2. Object Creation

JavaScript Code Sample

1 var regex = new RegExp('car', 'ig');

Now that you have a regular expression, you can use it to validate a string. Here is a list of the most common methods that you might use:

Method

Description

exec()

Search for a match in a string.

test()

Tests for a match in a string.

JavaScript Code Sample

1 var regex = new RegExp('car', 'ig');

2 var words = ["racecar", "chrome"];

3 console.log(regex.test(words[0]));

4 console.log(regex.test(words[1]));

Results

1 true

2 false

This regular expression is a simple one; it will match any string with the word car in it. To create more complex regular expressions, JavaScript provides a wide range of tokens for you to use.

Token

Description

.

The dot matches any single character except line terminators

\d

Matches a digit character in the basic Latin alphabet

D

Matches any character that is not a digit in the basic Latin alphabet

\w

Matches any alphanumeric character from the basic Latin alphabet, including the underscore

W

Matches any character that is not a word character from the basic Latin alphabet

JavaScript Code Sample

1 var regex = /c\w\wo/ig

2 var words = ["racecar", "chrome"];

3 console.log(regex.test(words[0]));

4 console.log(regex.test(words[1]));

Results

1 false

2 true

The regular expression matches any string that contains the pattern of c\w\wo where \w is used to denote any alphanumeric character.

Summary

This is just a sample of what JavaScript regular expressions can do. If you would like to see the full documentation for all the functions and methods that are available to you when working with regular expressions, check out the complete JavaScript Reference.