The best JavaScript Tips for web development

The best JavaScript Tips for web development

Have you been looking for some cool JavaScript tips? This post will outline a variety of fun & effective JS tips to help you learn one of the most widely used programming languages on the internet.

We will cover the following JavaScript topics;

  • ArrayMethods in JS
  • Making API requests with JavaScript
  • An overview of `for` loops in JavaScript
  • An Introduction to Node.js

Array methods in JavaScript

The array is one of the most important components of JavaScript, and any programming language in general. Often misconceived as its own data type, it is actually a subset of the Object, along with functions. In simple terms, an array is a compound data structure that can hold a limitless amount of values of any type. Each of the values is numerically indexed (i.e. each value has a number, designating its position in the array). This makes the array extremely flexible for storing and organizing data. Arrays can store strings, numbers, objects, or even other arrays. This post will give an overview of some of the most commonly used built-in JavaScript array methods. You can use these methods or functions to manipulate and deal with the data inside an array.

The best JavaScript Tips for web development

concat()

The concat() method, short for “concatenate”, allows us to join two arrays together:

var colors = ["black", "white", "blue"];
var colors2 = ["green", "yellow", "purple"];

document.write(colors.concat(colors2));
// output: "black, white, blue, green, yellow, purple"

 

On its own, concat() will not alter the original array the method was called on. Calling colors will still output the original array with only 3 values. In order to update the original array, you’d need to call the method on the colors array, re-assigning the variable:

On its own, concat() will not alter the original array you call the method on. Calling colors will still output the original array with only 3 values. To update the original array, you’d need to call the method on the colors array, re-assigning the variable:

colors = colors.concat(colors1); 

 

push()

Often you will just want to add new items to the end of an array, which you can use the push() method for. You can push either a single or multiple values to an array in the same call:

var colors = ["black", "white", "blue"];
colors.push("green", "yellow");

document.write(colors);
// output: "black, white, blue, green, yellow"

 

Unlike concat(), push() does update the original array with the values that you’ve pushed to it.

unshift()

Similar to push(), unshift() will add one or more new values to the beginning of the array:

var colors = ["black", "white", "blue"];
colors.unshift("green");

document.write(colors);
// output: "green, black, white, blue"

 

pop()

pop() is the inverse of the push() method, in that it will “pop” off or remove the last element of an array:

var colors = ["black", "white", "blue"];
colors.pop();

document.write(colors);
// output: "black, white" 

 

Since pop() removes an item from an array, it is common to store the removed item into another variable for other uses:

var lastItem = colors.pop();

document.write(lastItem);
// output: "blue"

 

shift()

Similarly, shift() will remove the first item in an array:

var colors = ["black", "white", "blue"];
colors.shift();

document.write(colors);
// output: "white, blue"; 

 

You can also use shift() in tandem with storing the removed item in a new variable:

var firstItem = colors.shift();

document.write(firstItem);
// output: "black" 

 

reverse()

As the name implies, the reverse() method will reverse the ordering of the values in the array:

var myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var reversedArray = myArray.reverse();

document.write(reversedArray);
// output: 10, 9, 8, 7, 6, 5, 4, 3, 2, 1

 

reverse() will not alter the original array. You’ll need to store the reversed array in a new variable. Alternatively you can re-assign it to the original variable in order to keep the reversed changes.

join()

The join() array method will join all values in the array into a string, then returning the string:

var colors = ["black", "white", "blue", "green"];
console.log(colors.join());
// output: black,white,blue,green 

 

There is an optional “separator” parameter that can be included with join(). This parameter indicates a character (or set of characters) to separate each value in the string. The example below will separate each value with a comma followed by a whitespace character:

var colors = ["black", "white", "blue", "green"];
console.log(colors.join(', ');
// output: black, white, blue, green 

 

join() will not modify the original array. You’ll need to assign the modification to a variable in order to save it.

var colorList = colors.join(', ');
console.log(colorList);
// output: black, white, blue, green

console.log(colors);
// output: ["black", "white", "blue", "green"]
// i.e. still the original array

 

sort()

sort() will sort the values of an array in alphanumeric order. sort() does update the original array:

var arr1 = [4, 9, 3, 2, 1];
arr1.sort();
console.log(arr1);
// ouput: [1, 2, 3, 4, 9]

 

sort() only orders values at the time you call the method. You’ll need to call it again to re-sort if you add or modify values in the array.

indexOf()

indexOf() will return the index value of a search term provided as a string parameter to the method:

var colors = ["black", "white", "blue", "green"];
colors.indexOf('white');
// returns 1

 

If there is no index match for the searchValue parameter, indexOf() will return -1:

var colors = ["black", "white", "blue", "green"];
colors.indexOf('orange');
// returns -1

 

indexOf() is case sensitive:

colors.indexOf('Blue');
// returns -1

 

There is also an optional fromIndex parameter. This indicates from which index value the search should begin. If not supplied, search begins at index 0 by default:

var names = ["Michael", "John", "Sarah", "Michael", "Matthew"];
names.indexOf('Michael', 2);
// returns 3 

 

slice()

The slice() method will return a “slice” of the array, indicated by optional parameters for beginning and ending points. slice() leaves the original array unmodified:

The slice() method will return a “slice” of the array. You can indicate beginning and ending points via its optional parameters. slice() leaves the original array unmodified:

var colors = ["black", "white", "blue", "green", "purple", "orange"];
var colors2 = colors.slice(2, 5);
console.log(colors2);
// output: ["blue", "green", "purple"]

var colors3 = colors.slice(1);
console.log(colors3);
// output: ["white", "blue", "green", "purple", "orange"];

console.log(colors);
// output: ["black", "white", "blue", "green", "purple", "orange"]; 

 

filter()

filter() is somewhat similar to the slice() method. The main difference is that it creates a new array based upon certain conditions. Each value in the array that passes a condition is “filtered” into the new array. The condition for filtering is set via the callback function:

var someWords = ["easy", "hard", "encryption", "society", "total", "fastidious", "complexity"];

function checkSize(w) {
    return w.length > 5;
}

var bigWords = someWords.filter(checkSize);
console.log(bigWords);
// output: ["encryption", "society", "fastidious", "complexity"] 

 

The example above uses the checkSize() callback function to filter out any words less than 6 characters long. It also puts all the remaining values in a new array called bigWords.

every()

The every() array method will check to see if every value in the array passes a condition or not. The condition here is also provided via a callback function. If it passed, the method will return true, if it does not, it will return false:

var nums = [20, 31, 18, 500];

function greaterThan10 (value) {
    return value > 10;
}

console.log(nums.every(greaterThan10));
// output: true

 

The example above tests to see if every value in the nums array is greater than 10, returning true.

isArray()

As the name implies, .isArray() will check to see whether a value passed to it is an array or not:

Array.isArray(['blue', 'yellow' 'green']);  // returns true
Array.isArray(3);                           // returns false
Array.isArray('hello');                     // returns false

 

findIndex()

findIndex() is almost the opposite of the indexOf() method. It will return the index of the first value in an array that satisfies a condition. The condition is set via a callback function. If no value is found that satisfies the condition then the function returns -1.

var colors = ['black', 'blue', 'yellow', 'green', 'purple'];

function greaterThanFive(e) {
    return e.length > 5;
}

var indexOfLargeValue = colors.findIndex(greaterThanFive);
console.log(indexOfLargeValue);
// output: 2

 

forEach()

The forEach() method will execute a callback function on every value in the array the method is called on. This is useful for adding values equally to each index in an array, as well as many other applications. This will not modify the original array, however, so the new values will need to be saved to another variable:

var nums = [1, 2, 3, 5, 8, 13];
var numsUpdated = [];

function addTwo(e) {
    e += 2;
    numsUpdated.push(e);
}

nums.forEach(addTwo);
console.log(numsUpdated);
// output: [3, 4, 5, 7, 10, 15]

 

This is similar to using a for loop to iterate over an array, with slightly more simple syntax.

includes()

You can use includes() to check whether a certain array contains a given a value or not. If the array does, it will return true, if it does not it will return false.

var colors = ['black', 'blue', 'yellow', 'green', 'purple'];

console.log(colors.includes('blue'));
// output: true

console.log(colors.includes('red'));
// output: false

 

There is an optional second parameter, fromIndex. This will indicate where to start the search from:

var colors = ['black', 'blue', 'yellow', 'green', 'purple'];

console.log(colors.includes('blue', 2));
// output: false

console.log(colors.includes('blue', 1));
// output: true

 

lastIndexOf()

Similar to indexOf(), lastIndexOf() will find the last instance of a given value in an array, as opposed to the first. The method will start its search from the end of the array and work its way to the beginning until a suitable match is found. If no match is found, the method will return -1:

var food = ['sushi', 'pizza', 'cheeseburger', 'sushi', 'pasta'];

console.log(food.lastIndexOf('sushi'));
// output: 3

console.log(food.lastIndexOf('burrito'));
// output: -1

 

.toString()

.toString() is somewhat similar to the .join() method, in that both can return the full index of values as a string. toString() is a far simpler method. It has no optional parameters for specifying “separator” characters to place between each value. All values in an array will simply be separated with a comma (with no spaces). This can be good or bad, depending on the application.

Making API requests with JavaScript

One of, if not the most important component of interacting with third-party services is communicating with their APIs. Standing for Application Programming Interface, this is the primary way in which different websites, applications and web services can talk to each other, receiving and sending data back and forth. This tutorial will serve as a basic introduction to connecting to a web API via JavaScript, and being able to receive or read GET requests that return data in JSON (or JavaScript Object Notation) format. This tutorial assumes basic knowledge of JavaScript objects and accessing properties, but is otherwise intended for individuals with no prior experience working with APIs.

Introduction

For this tutorial, we will be going through the Ghibli API, which was set up to introduce people to using Application Programming Interfaces (as well as for aficionados of the films of Studio Ghibli).

The API is broken up into 5 different modules or components for different classes of data related to Studio Ghibli (Films, People, Locations, Species and Vehicles). Each one of these components is more formally referred to as an endpoint. When making a call to the endpoint via GET (or another similar method, such as fetch), the endpoint will return an array of data specific to that category, in JSON format. For example, the endpoint for Films would look something like this:

API requests with JavaScript

We’ll take the endpoint for Films (available here), make a call via GET, then log various parts of the data to the console.

// Make a new XMLHttpRequest and save it to a variable
var receive = new XMLHttpRequest();

// Indicate the endpoint we'd like to open, via the `GET` method
receive.open('GET', 'https://ghibliapi.herokuapp.com/films', true);

// Execute the code within the function once the endpoint is loaded
receive.onload = function () {

  // Parse the incoming data into JSON format  
  var incoming = JSON.parse(this.response);
  
  // Use the .map array method to iterate over each index in the Films
  // endpoint, then access the releae date, title and Rotten Tomatoes 
  // score from each, logging them to the console with some additional
  // formatting
  incoming.map(films => {
      console.log(films.release_date + " : " + films.title + " -- (" +  films.rt_score + "% on Rotten Tomatoes)");
    });
};

// Send the actual request, to execute the function assigned to 
// `receive.onload`
receive.send();    

Inputting the code above into your browser console, or by running as a JavaScript file linked to a webpage should return the following:

API requests with JavaScript

…where we are displaying the release year, the name of the film and its overall rating on Rotten Tomatoes (along with some additional formatting for better legibility)

The API Call Explained

The documented notes within the script above should make most of the API call explanatory, but the manipulation of the data within receive.onload is worth further details.

The .map() array is used to iterate over each individual index within the Film endpoint (i.e. each film). A for loop could be used here just as well, although .map() does the same thing with far less code. .map() takes a callback function (written here in ES6 syntax). The code within the callback function is executed for each item in the endpoint, retrieving its release date (films.release_date), title (films.title) and score on Rotten Tomatoes (films.rt_score).

For simplicity’s sake, a console.log message is used for each item, but this data could easily be added to HTML elements on the page, or sorted further with other array methods (i.e. filter out only films from the 1980s). While there is much more to working with API services, this is a high-level overview of the mechanics of retrieving data from an API’s endpoints.

An overview of `for` loops in JavaScript

An overview of `for` loops in JavaScript

A fundamental principle of computer programming is the long-held adage of “DRY”, or “Don’t Repeat Yourself”. Anytime you find yourself re-writing the same code over and over again, chances are there is a better way to re-factor, without the need for duplicate lines of the same code. One of the best ways of accomplishing this is via loops. There are several different kinds of loops, all of which exist in various forms across all programming languages. In this post, we’ll take a look at one of the most common and useful forms of loops, the for loop.

A basic example

As an introduction to show where loops are very useful, let’s say you wanted to print, “Hello World” to the JavaScript console. Without the use of a loop, you would have to write something along the following:

console.log("Hello World");
console.log("Hello World");
console.log("Hello World");
console.log("Hello World");
console.log("Hello World");
console.log("Hello World");
console.log("Hello World");
console.log("Hello World");
console.log("Hello World");
console.log("Hello World");

 

This is extremely tedious and inefficient. The above 10 lines of code can drastically be simplified with just the following 3 lines:

for (var i = 0; i < 10; i++) {
  console.log("Hello World");
}

 

The above example is what’s known as a for loop, one of the most common and useful forms of loops.

The for loop

There are several components that go into writing a for loop: the counter or initial expression, the condition, increment expression, and the code to excecute within the loop. We’ll break down our example above of creating a loop that prints “Hello World” to the console 10 times.

All for loops start with the keyword for, followed by a set of parentheses, then followed by brackets. The code to execute is placed inside the brackets. The skeleton structure of a for loop can be seen as:

for (counter; condition; increment) {
  // Code to execute goes here
}

 

The counter must be set as a variable; in programming this is frequently set as i, although it could be x, n or any variable name allowed by the language. This tells the loop its starting value, in this case, 0.

The next part of the loop tells JavaScript the condition: in this case, execute the loop as long as the value of i is less than 10. As soon as the loop reaches 10 it will stop. It’s extremely important to have a conditional set before trying to run your loop, otherwise you’ll end up with an infinite loop, which will end up overloading and crashing your browser.

The last part of the loop in parentheses is the increment: i++. i++ is shorthand in JavaScript for i += 1 or i = i + 1. In other words, it adds 1 to the value of i each time the loop is run. This is also a crucial component of the loop, as if it doesn’t actually increment it will also not terminate.

Whichever code is placed inside the brackets will run through each iteration of the loop. If you would like to get some sort of indication of what iteration the loop is on each time is run, you can simply add the counter variable to be included in the code that should be returned each time (i.e. the code run inside of the brackets):

for (var i = 1; i <= 10; i++){
  console.log("The loop is now on iteration " + i);
}

 

The above code, when run, will print:

The loop is now on iteration 1
The loop is now on iteration 2
The loop is now on iteration 3
The loop is now on iteration 4
The loop is now on iteration 5
The loop is now on iteration 6
The loop is now on iteration 7
The loop is now on iteration 8
The loop is now on iteration 9
The loop is now on iteration 10

An Introduction to Node.js

An Introduction to Node.js

JavaScript development has come a long way since it was first introduced in 1995, by Mozilla co-founder Brendan Eich. Originally used as a client-side scripting language, JavaScript has expanded its use to applications far beyond its original intentions. No longer is the language solely used on the client-side. With the introduction of Node.js, JavaScript is now being used on the server side as well, replacing the need for other back-end languages such as PHP, Python or Ruby.

More than just a novelty, more and more developers and companies are embracing using JavaScript on the back-end, allowing for all development work to be done in a single language. To get a better idea as to why this is becoming a growing trend, this post will take a look at what Node.js is, and what it is best used for.

An explanation of Node.js

Node.js is a JavaScript framework or library developed to be able to use JavaScript as a primary server-side scripting language. It is not a new language, simply a subset of code written for the JavaScript language. Originally created by Ryan Dahl in 2009, it is built on Google Chrome’s JavaScript V8 Engine, which in itself was developed to offer better performance than other existing JavaScript engines. Node.js is fully open source, runs on every operating system, and is constantly being improved by the large developer community surrounding the project.

Since it is intended specifically for backend use, Node.js comes with a variety of modules to handle common tasks one would use a server-side scripting language for. This can speed up the development process immensely, abstracting common features that you would otherwise have to write from scratch.

The basic features of Node.js

Here are some of the fundamental features of Node.js that separate from other scripting frameworks:

Event-Driven, Asynchronous Programming

APIs used as apart of the Node.js framework are totally asynchronous, otherwise known as non-blocking. This equates to Node.js never having to wait on a specific API to send data without moving on to another task. Node.js will move on to another API, keeping track of the data it is still waiting to receive from other APIs.

High Performance

Node.js is extremely fast compared to other server-side alternatives, having been built on Google Chrome’s V8 Engine. Depending on the versions compared, Node.js has outperformed PHP and Python in benchmark tests.

Avoids buffering

Node.js applications always output data in chunks, in order to avoid buffering.

Scalable

Node.js was developed to be used for both small projects and large, enterprise systems. Node.js utilizes a single-threaded model to allow for asynchronous events, whereas common server languages utilize a limited number of threads to deal with data requests. This ultimately means that Node.js can handle a larger number of server requests at one time than a more typical server setup such as Apache HTTP.

Node.js in Practice

Node.js is being used for a wide-array of uses, from open-source projects or small startups, to Fortune 500 companies. A short list of companies utilizing Node.js include PayPal, Uber, Microsoft, eBay, and GoDaddy.

What Node.js is best for

Some of the uses in which Node.js really shines include I/0 bound applications, such as chat messaging, data streaming services such as live video, Data Intensive Real-Time Applications (DIRT), single page web applications, and applications utilizing a lot of JSON-based APIs.

Conclusion

We hope you found some helpful JavaScript tips from this article. Feel free to post your feedback & JS tips via the comments section below.

angelo frisina sunlight media

Author Bio

Angelo has been involved in the creative IT world for over 20 years. He built his first website back in 1998 using Dreamweaver, Flash and Photoshop. He expanded his knowledge and expertise by learning a wider range of programming skills, such as HTML/CSS, Flash ActionScript and XML.

Angelo completed formal training with the CIW (Certified Internet Webmasters) program in Sydney Australia, learning the core fundamentals of computer networking and how it relates to the infrastructure of the world wide web.

Apart from running Sunlight Media, Angelo enjoys writing informative content related to web & app development, digital marketing and other tech related topics.

Post a Comment

Comments are moderated. Your email is kept private. Required fields are marked *

© 2020 Sunlight Media LLC