Learn some great JavaScript tips and techniques through recipes that clearly define the problem being solved with a working solution in this book that is not a blog.

You are free to copy, distribute, modify or display the book. However, I ask that you always attribute the book to me, Jamie Munro , and do not use it for commercial purposes. This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License

Redirecting a user to another webpage

Problem

You want to redirect a user from the current page to a new page inside a JavaScript function.

Solution

There are two possible solutions to redirect a user to a new page:

window.location.replace() window.location.href

Discussion

There are two different ways to redirect a user. The first way is to use the window.location.replace(). This function will not add the current page to the user's back button sessions. This means after the user is redirected to the new page with window.location.replace(), if they click back, they will not be taken to the page that performed the redirect. Instead they would return to the previous page before the redirect happened.

This solution is better when the page that performs the redirect is the only thing it does and you do not want the user to get stuck in an endless loop of pressing the back button and being redirected again.

Here is an example of redirecting the user to Google when they click a button:

See the Pen Javascript: window.location.replace by Jamie Munro (@endyourif) on CodePen.

The second approach to redirecting a user is to use the window.location.href. Unlike in the previous example, using the window.location.href will add the current page to browser's back button history.

This approach is the preferred approach if the page doing the redirect has additional functionality that would not cause an endless back button redirect forward loop. Let's look at an example:

See the Pen JavaScript: window.location.href by Jamie Munro (@endyourif) on CodePen.

Be sure to notice the difference that window.location.replace() is a function whereas window.location.href is a property and does not require brackets.

Search a string for a substring

Problem

You want to search a string variable to determine if it contains a matching substring value.

Solution

To search for a string inside of a string contains several different methods, each offering their own benefit. The most common solutions involve the indexOf function or using a regular expression with the match function.

Discussion

I've never been very good with regular expressions. It's one of those things that only seems to crop up (for me) when validating an email address or phone number. Thankfully, there are plenty of examples for both of those.

Having said that, my preference for searching a string for another string is by using indexOf function.

Let's take a look at an example:

See the Pen JavaScript - indexOf searching a string for another string by Jamie Munro (@endyourif) on CodePen.

When this JavaScript runs, it writes "Found JavaScript!" in the results area.

Notice that in the second iteration it is looking for "javascript" in all lowercase. This example outputs "Did not find javascript" because the indexOf is case sensitive.

If you want your match to be case sensitive then you are good to go. Otherwise, a common solution is to call the toLower function before the indexOf function to make it case insensitive.

Another important thing to note is the indexOf function returns -1 when it does not find the string. This is important as if the string you are searching is the very first thing in the string the indexOf will return 0; hence the >= 0 in the if statement.

The second solution is to use the regular express function match. This function accepts a regular expression and will return true or false based on whether it finds a match.

Let's take a look at an example:

See the Pen JavaScript - Search for a string with match by Jamie Munro (@endyourif) on CodePen.

In the first if statement we are passing a regular string of "JavaScript". This returns true. In the second if statement, we are passing a slightly more complicated regular expression of /javascript/i. This tells the match function to look for the string javascript and the /i makes it case insensitive.

Because the second instance in the example is case insensitive, both if statements return true and the message indicating that the string was found.

Retrieving a query string parameter

Problem

You want to retrieve the value of a parameter in the URL's query string. E.g. ?myString=javascript.

Solution

A new solution to extract query string parameters has been added to JavaScript and accomplished by using the URLSearchParams object. Unfortunately this is not supported by Internet Explorer (at the time of writing). For non-good browsers then some old school regular expressions are required to parse out the parameters from the URL.

Discussion

Let's look at the nice way of extracting query string parameters as this will be the new norm whenever Internet Explorer decides to be somewhat half-decent:

See the Pen JavaScript - URLSearchParams by Jamie Munro (@endyourif) on CodePen.

In the above example, I've created a function called getQueryStringParameter that accepts the name of the query string parameter. In the example above, the query string parameter being extracted is called value, so if the query string were: ?value=a value, then the result in the value variable would be: a value.

The getQueryStringParameter function instantiates the URLSearchParams with the browser's current location. This is stored in the params variable. This object then calls the get function with the name of the parameter to be extracted.

The second solution is slightly more complicated and uses regular expressions to both cleanup the parameter input and parse the value out of the browser's current location:

See the Pen JavaScript - Get Query String Parameter by Jamie Munro (@endyourif) on CodePen.

To simplify usage, the function signature in this solution is the same as the previous and the usage remains the same.

The first part of this function ensures the parameter being extracted doesn't contain an invalid characters and makes sure things are properly escaped. The second part sets up the regular expression to extract the value from query string parameter. It matches against both a ? and an &.

If the parameter is not found, null is returned. If the parameter is found but contains no results, an empty string is returned. This helps distinguish between it not existing and not containing a value. Otherwise, the value of the parameter is returned.

Hopefully Internet Explorer will give in and adopt the much cleaner URLSearchParams in the next decade or so...

var functionName = function() {} vs function functionName() {}

Problem

You want to understand the difference between declaring a function as an expression and as a declaration.

Solution

The difference between a function expression: var functionName = function() and a function declaration: function functionName() is that a function expression contains a reference to an anonymous function whereas a function declaration is a named function. With a function expression it's important to define the function first to the variable that contains the anonymous function to avoid errors.

Discussion

In the following example:

See the Pen JavaScript - Function Expression by Jamie Munro (@endyourif) on CodePen.

Two functions are created, one as an expression and the other as a declaration. Then I've outputted HTML to a div and a called toString() on both functions. As you can see my the output, the function expression is an anonymous function that does not have a name, whereas the function declaration contains the name it was defined as.

Both methods are valid; however, a function created as an expression must be created before it is executed whereas a function declaration can be called before it is created allowing for a different organization of code. Meaning function expressions would be defined before calling them and function declaration can be created after calling them.

Remove specific element from an array

Problem

You have an array of elements and you need to remove a specific element from said array.

Solution

Removing an element from an array requires two steps. The first step is to use the indexOf function to find the elements position in the array. Once you have the position you use the splice function to remove the element at the index in the array.

Discussion

Let's look at an example where an array is created, then the element being removed is found and deleted from the array:

See the Pen JavaScript - Remove element from an array by Jamie Munro (@endyourif) on CodePen.

In the example above, an array is created with 5 elements. This is outputted to a div to show the elements before one is removed. After the output, the index of the element with the number 4 is found. When the value is greater than -1 (meaning it was found) then that element is removed from the array by using the splice function with the index of the element as the first parameter and 1 as the second parameter because it is removing a single element. After the splice, the value of the array is appended to the original element.

As you can see based on the output of the example that the array had the value 4 at the beginning but does not have it at the end once it is removed from the array.

Difference between === and == operator

Problem

JavaScript contains two operators for an equals comparison: === and == and you want to know which one should be used.

Solution

The key difference between the === and == operator is that the triple equals must have the same type to be equal. For example, 1 === "1" is false and 1 == "1" is true because a type conversion is done to convert the string "1" to the int 1.

Discussion

In the following example, several different equal statements are performed to identify the difference:

See the Pen JavaScript: === vs == by Jamie Munro (@endyourif) on CodePen.

In the above example, I've created a function called logOutput that is used to append a div element inside another div to make the example more clear.

This function is then called with a variety of different equal operations and the operation and result are outputted on screen.

The clear examples of things like 1 === true evaluates to false where as 1 == true evaluates to true.

The conclusion here is, if you care about the object types in the comparison use the === oppose to if the object types do not matter use the == operator.

Deep clone an object

Discussion

You have a JavaScript object and you want to clone/copy it to a new object.

Solution

To copy/clone an object using JavaScript, you will want to leverage the JSON.parse function in combination with the JSON.stringify function.

If you are looking for a jQuery solution, you will want to leverage the extend function which can be found in our jQuery Recipes book.

Discussion

In the following example two objects will be created: objectA and objectB. objectA will be used as the existing object that will be copied/cloned into objectB.

See the Pen JavaScript - Clone an object by Jamie Munro (@endyourif) on CodePen.

Once objectA has been cloned to objectB using the JSON.parse function in combination with the JSON.stringify function, the output of the copy is outputted on screen and shows that the full object, including child properties, have been copied to the new object.

Remove property from an object

Problem

You have an object, but there is a property/properties on the object that you wished removed.

Solution

To remove a property from an object you will want to use the JavaScript delete operator on the property in question.

Discussion

Let's take a look at an example where an object is created then the unwanted property is removed from the object:

See the Pen JavaScript - Removing property from an object by Jamie Munro (@endyourif) on CodePen.

A div has been created to output the object before and after the delete operation has been run as follows: delete myObject.property2.

I've additionally added a comment to identify a secondary way of deleting the object as follows: delete myObject["property2"]. This method of deleting can be extremely useful when the "property2" value is a variable that is set at runtime.

Replace all occurrences of a string

Problem

You have an existing string object and you want to replace all instances of a specific string inside the existing object.

Solution

To replace a value inside a string you should use the replace function on the string object itself.

By default it will replace the first instance only, but see the discussion for examples of how to replace all instances.

Discussion

Let's take a look at the string's replace function in action:

See the Pen JavaScript - String replace by Jamie Munro (@endyourif) on CodePen.

In this example a string is created with a sentence of words. In the first part of the example, the replace function is called as follows: myString.replace(" ", ""). As you can see based on the output, this only removes the first instance of a space in the sentence.

In the second part of the example, the replace function is called again with a slightly different implementation: myString.replace(/ /g, ""). In this example, the function is called with a simplistic form of a regular expression. The /g identifies that it should replace the space globally on the string.