Skip to content
tinytip

Latest tips / 11

Create an array with the map function of Array.from

September 4, 2021
#javascript #array

The Array.from function has a second parameter that lets you map each item to a new value.

The first argument of the map function is the current value or undefined if you don't have an existing list (as in the example below). The second argument is the index.

const items = Array.from({ length: 5 }, (value, idx) => idx + 1);
console.log(items); // [1, 2, 3, 4, 5]

Configure default branch name in Git

September 4, 2021
#git
Credits: Donavon West

A newly created Git repo (git init) has a default branch with the name master. You can configure that name for all new repositories with the following command:

git config --global init.defaultBranch main

Now every new Git repository will automatically create a branch main instead of master.

setTimeout accepts arguments for the function

August 15, 2021
#javascript

The setTimeout function accepts optional arguments that are passed to the provided function. This way you can pass arguments without wrapping the actual function in another function.

// Instead of this...
setTimeout(() => search("hello", "world"), 1000);

// ... you can do this
setTimeout(search, 1000, "hello", "world");

Function parameters can have default values based on other parameters

August 15, 2021
#javascript

A function with parameters can have default values that are used when the caller does not provide a value for that parameter (by omitting the parameter or providing undefined). The default value does not have to be a static value. You can run JavaScript and use previous parameters of that function.

// "timestamp" has a dynamic default value
function logMessage(message, timestamp = Date.now()) {
// ...
}
function someFunction(
value,
max = value.length,
suffix = value.length > max ? "..." : ""
) {
// ...
}

someFunction("hello") // max = 5, suffix = ""
someFunction("hello" 2) // max = 2, suffix = "..."
someFunction("hello", undefined, ".....") // max = 5, suffix = "....."

Create a string type in a specific format in TypeScript

July 29, 2021
#typescript

TypeScript supports template string types that lets you create string types in a specific format. Here are a few examples:

type Locale = `${string}-${string}`;
const locale: Locale = "en-US";

type Url = `https://${string}`;
const url: Url = "https://tinytip.co";

type CssCustomProp = `var(--${string})`;
const cssCustomProp: CssCustomProp = "var(--color-primary)";

type CurrencySymbol = "€" | "$" | "£" | "¥";
type AmountWithCurrency = `${CurrencySymbol} ${number}`;
const bankBalance: AmountWithCurrency = `$ 42`;