Strings, dates, math, and APIs
Strings
length |
Returning the number of characters in a string (its length). Example: "Hello".length (returns: 5 ). |
toLowerCase() , toUpperCase() |
Converting a string to lowercase / uppercase. Example: "Hello".toLowerCase() (returns: "hello" ). |
split() |
Breaking a string into an array by dividing it every time a given delimiter is encountered. Example: "apple banana cherry".split(" ") (returns: ["apple", "banana", "cherry"] ). |
join() |
Joining the elements of an array into a single string by inserting a delimiter between each element. Example: ["apple", "banana", "cherry"].join(" ") (returns: "apple banana cherry" ). |
trim() |
Removing whitespace characters from both ends of a string. Example: " hello ".trim() (returns: "hello" ). |
replace() |
Replacing all occurrences of a substring with another substring. Example: "I like apples".replace("apples", "oranges") (returns: "I like oranges" ). |
includes() |
Checking if a string contains a specified substring. Example: "Hello World!".includes("World") (returns: true ). |
substring() |
Returning a part of a string. Example: "Hello World!".substring(6, 11) (returns: "World" ). Starting index - inclusive, stopping index - exclusive. |
indexOf() |
Finding the position of the first occurrence of a substring in a string (the index of the substring's first letter). If there are more than one - the index of the first one encountered. Example: "Hello World!".indexOf("World") (returns: 6 ). |
concat() |
Joining two or more strings into one. Example: "Hello".concat(" ", "World", "!") (returns: "Hello World!" ). |
str.split("").reverse().join("") |
Reversing a string (converting to an array, reversing, and joining into a string). |
Dates
let d = new Date()
a = d.getDay()
getDate() |
Day as a number (1-31) |
getDay() |
Weekday as a number (0-6) |
getFullYear() |
Four-digit year (yyyy) |
getMonth() |
Month (0-11) |
getHours() |
Hour (0-23) |
getMinutes() |
Minutes (0-59) |
getSeconds() |
Seconds (0-59) |
getMilliseconds() |
Milliseconds (0-999) |
getTime() |
Milliseconds since January 1, 1970 |
Math
The functions with no parameters listed take only one or none.
Math.round() |
Rounding a number to the nearest integer. |
Math.random() * 10 |
Returning a random number between 0 (inclusive) and 10 (exclusive). |
Math.floor() |
Rounding a number down to the nearest integer. |
Math.ceil() |
Rounding a number up to the nearest integer. |
Math.abs() |
Returning the absolute value of a number. |
Math.sqrt() |
Returning the square root of a number. |
Math.pow(base, exponent) |
Raising the base to the power of the exponent. |
Math.min(0, 3, 1) , Math.max(0, 3, 1) |
Returning the smallest / largest of the given numbers. |
NaN (Not a Number) is a special JavaScript value that represents an invalid number or the result of an invalid mathematical operation. A NaN value is, e.g., 0 / 0
. A comparison NaN === NaN
would return false
. To check if a value is NaN, we can use this function: Number.isNaN()
. NaN is commonly used in scenarios such as handling errors in mathematical computations, input validation, or when a function returns an undefined or impossible result.
APIs
An API (Application Programming Interface) is a set of rules and tools that allows different software applications to communicate and interact with each other. Fetching data from an API means requesting information from a remote server or service and receiving the response to use in our application. APIs often provide endpoints (URLs) that return data in a structured format like JSON. When we "fetch" data, we make an HTTP request to these endpoints, asking for specific information. The server processes the request and sends back a response, which we can use to, e.g., display content. APIs enable interactive web applications that rely on real-time or external data.
An exception is an error-caused event that disrupts the normal flow of a program. It can be handled to maintain program stability. We can "throw" exceptions if we know an error will occur (e.g., the user divides by zero), so they are handled in the catch
block.
<div id="dataContainer">Fetching data...</div>
<script>
const apiURL = "https://jsonplaceholder.typicode.com/posts" // an example URL
fetch(apiURL)
.then((response) => {
if (!response.ok)
throw new Error(`HTTP error! Status: ${response.status}`) // throwing an error if the response is not OK
return response.json() // parsing the response to JSON
})
.then((data) => {
const dataContainer = document.getElementById("dataContainer")
dataContainer.innerHTML = data
.slice(0, 1) // limiting to 1 item
.map((post) => `
<div>
<h5>${post.title}</h5>
<p>${post.body}</p>
</div>
`).join("") // combining the HTML strings
})
.catch ((error) => { // catching an error
document.getElementById("dataContainer").textContent = "Failed to fetch data."
})
</script>