Frequently searched solutions for JavaScript

Frequently searched solutions for JavaScript


class CampingSpot {
  constructor(name, location) {
    this.name = name;
    this.location = location;
  }
    describeWater() {
      console.log("The water at " + this.name + " is very cold.");
    }
}

Now we can create instances of the CampingSpot Object as desired:


let willowCreek = new CampingSpot("Willow Creek", "Big Sur");
let sunsetStateBeach = new CampingSpot(“Sunset State Beach”, “Santa Cruz”);

6. Using remote APIs

Accessing APIs hosted on services is another common need in JavaScript programs. APIs provide access to external data and functions. Developers often look for solutions to retrieve data from remote APIs, parse responses, and integrate them into their applications.

Fortunately, modern JavaScript includes the Fetch API in both client and server environments. This is a simple and straightforward way to make HTTP calls. For example, we would fetch the list of Star Wars movies from the SWAPI service:


async function getStarWarsFilms() {
  try {
    const response = await fetch('https://swapi.dev/api/films');
    if (!response.ok) {
      throw new Error(`Error fetching Star Wars films: ${response.status}`);
    }
    const data = await response.json();
    console.log(data.results); 
  } catch (error) {
    console.error("Error:", error);
  }
}

getStarWarsFilms();

Since this is a GET request, we can simply fetch('https://swapi.dev/api/films')Please note that we use awaitthat I introduced earlier. This allows us to pause while the request goes out and the response comes back.

We use the response Object to determine if the request was good (an HTTP 200 response), using response.ok.

7. String manipulation

Strings are basic and are used in all sorts of situations. Consider the following string:


const taoTeChingVerse1 = 
  `The Tao that can be told is not the eternal Tao. 
  The name that can be named is not the eternal name. 
  The nameless is the beginning of heaven and earth. 
  The named is the mother of all things,`;

Let’s say we only wanted the first line of the first verse:


const firstLine = taoTeChingVerse1.slice(0, 48);

This means: Give us the substring between the first character (0) and the 48th character (inclusive).

To search for the first occurrence of the word “Tao,” type:


taoTeChingVerse1.indexOf("Tao"); // returns 4

Now, if you want to replace words, use a simple regular expression. Here we replace all occurrences of “told” with “spoken”:


const newText = text.replace(/told/g, "spoken");

The slashes indicate a regular expression that we match on “told”. The suffix g means “global”, i.e. all occurrences. The second argument for replace() is the token to be exchanged. (We end up with “The Tao that can be spoken is not the eternal Tao.”)

If we need to concatenate two strings, a simple plus operator (+) is enough:


let fullVerse = taoTeChingVerse1 + “Having both but not using them, Think of them as the constant.”);

And you can always calculate the string length as follows:


fullVerse.length; // return 261

8. Converting JSON objects to strings

Another common need is to take an actual JSON object and convert it to a string or vice versa. Here’s how to take a live JSON object and convert it to a string:


let website = {
  name: “InfoWorld”,
  url: “www.infoworld.com”
}

let myString = JSON.stringify(website);

And this is how you can take the string and return it to an object:


JSON.parse(myString);

9. Simple date operations

There is a lot you can do (and need to do) with JavaScript’s built-in Date Object.

To begin with, you can find today’s date as follows:


const today = new Date();

And get its components as follows:


console.log(today.getFullYear());  // Get the year (e.g., 2024)
console.log(today.getMonth());    // Get the month (0-indexed, e.g., 4 for May)
console.log(today.getDate());     // Get the day of the month (e.g., 21)
console.log(today.getHours());    // Get hours (e.g., 13 for 1 PM)
console.log(today.getMinutes());  // Get minutes (e.g., 27)
console.log(today.getSeconds());  // Get seconds (e.g., 46)

To go seven days into the future:


date.setDate(date.getDate() + 7);

10. Form, find and count numbers

These days, JavaScript is pretty good at handling numbers. It handles most numbers natively and offers a built-in library called Math for extra power.

You can create numbers:


let age = 30;
let pi = 3.14159;
let billion = 1000000000;

Or convert from a string:


let convertedNumber = Number(“42”);

In normal operations, the situation is obvious:


let addition = pi + 3; // addition now equals 6.14159

How to round numbers quickly:


Math.ceil(pi); // round to nearest upper integer (4)
Math.floor(pi); // round to lowest int (3)

Find the largest number:


Math.max(100, 5, 10, 73);  // returns 100

If you start with an array, you can use the spread operator:


let numbers = [100, 5, 10, 73];
Math.max(...numbers); // returns 100

Here’s how to check the uniformity:


let isEven = 10 % 2 === 0; // true (checks if remainder is 0)

Previous Article

Faulty CrowdStrike update causes major global IT outage, paralyzing banks, airlines and companies worldwide

Next Article

DJI Power 1000 review: With lots of power come lots of dongles

Subscribe to our Newsletter

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨