Big Data

Frequently sought 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 at will:


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 functionalities. Developers often seek solutions to fetch 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 direct way to make HTTP calls. For example, here’s how we’d get 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();

Because this is a GET request, we can just use fetch('https://swapi.dev/api/films'). Notice we use await, which I introduced earlier. That lets us 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 fundamental and used in all kinds 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 wanted only the first line of the first verse:


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

This says: Give us the substring between the first character (0) until the 48th character, inclusive.

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


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

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


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

The slashes indicate a regular expression, which we match on “told.” The suffix g indicates “global,” meaning all occurrences. The second argument to replace() is the token to swap in. (We wind up with “The Tao that can be spoken is not the eternal Tao.”)

If we need to concatenate two strings, a simple plus (+) operator will do the trick:


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

And, you can always count the string length with:


fullVerse.length; // return 261

8. Converting JSON objects to strings

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


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

let myString = JSON.stringify(website);

And here’s how to take the string and return it to an object:


JSON.parse(myString);

9. Simple date operations

There’s a lot you can do (and must do) with JavaScript’s built-in Date object.

To start, you can get today’s date like so:


const today = new Date();

And get its constituent parts like this:


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)

Here’s how to get seven days in the future:


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

10. Creating, finding, and counting numbers

JavaScript today is pretty good with numbers. It natively handles most numbers and offers a built-in library, 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”);

Normal operations behave in obvious ways:


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

You can 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

Finally, here’s how to check for evenness:


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



READ SOURCE

This website uses cookies. By continuing to use this site, you accept our use of cookies.