2022-07-07 Whats a JavaScript library ? by https://fediverse.org/ChrisFerdinandi

What’s the difference between a library and a helper function ?

Generally speaking, a helper function is code written for a specific project or code base, while a library is abstracted and can be used in many projects.

For example, a function that calls an API specific to your app and automatically returns parsed JSON data is a helper function.

// This is a helper function
function sendData (params) {
    return fetch('https://jsonplaceholder.typicode.com/posts', {
        method: 'POST',
        body: new URLSearchParams(params).toString(),
        headers: {
            'Content-type': 'application/x-www-form-urlencoded'
        }
    }).then(function (response) {
        if (response.ok) {
            return response.json();
        }
        throw response.statusText;
    }).then(function (data) {
        return data;
    }).catch(function (error) {
        return error;
    });
}

// You might use it like this
sendData({
    title: 'Going to the beach',
    body: 'We can swim, read, and enjoy the nice weather.',
    userId: 1
}).then(function (data) {
    console.log(data);
});

However, a function that lets you call any API and abstracts away some of the repetitive tasks could be considered a library.

// This is a super simple library
function sendToAPI (endpoint, params = {}, useJSON = false) {
    return fetch(endpoint, {
        method: 'POST',
        body: useJSON ? JSON.stringify(params) : new URLSearchParams(params).toString(),
        headers: {
            'Content-type': useJSON ? 'application/json; charset=UTF-8' : 'application/x-www-form-urlencoded'
        }
    }).then(function (response) {
        if (response.ok) {
            return response.json();
        }
        throw response.statusText;
    }).then(function (data) {
        return data;
    }).catch(function (error) {
        return error;
    });
}

// You might use it like this
sendToAPI('https://jsonplaceholder.typicode.com/posts', {
    title: 'Going to the beach',
    body: 'We can swim, read, and enjoy the nice weather.',
    userId: 1
}, true).then(function (data) {
    console.log(data);
});