Calling vs Referencing Function

In Javascript, whenever there is a set of parenthesis in front of a function, it will be called so only put parenthesis in front if you want the result from the function immediately

  • When passing a function as a reference, leave the parenthesis out
    • addEventListener( 'click', myFunction)
  • If the function has arguments, wrap it in an arrow function or handler function to keep the reference
    • addEventListener( 'click', () => myFunction(arg1))
    • const handleFunc = () => myFunctino(arg1) and then using it: addEventListener('click', handleFunc)
  • If you the result of the function immediately, put parenthesis in front of it
    • if(!restoreState()) initialize();
    • addEventListener( 'click', myFunction()) myFunction will run immediately here instead of waiting for event trigger

Writing Javascript Functions

In Javascript, all variables outside of the function are at the modular-level, i.e. if 2 files imported the same Javascript file, they both gain access to the same object

  • Similar to static variables inside Java classes

Different Ways to Express a Function:

  • Declaration: function add(a, b) { return a + b; }
  • Expression: const add = function(a, b) { return a + b; }
    • Use the variable like a normal function: add(2,3);
  • Arrow Function: can only be used inline and not through named declaration unless the function is assigned to a variable
    • As Single Expression:
      • () => 'return message';
      • a => a**2;
      • (a,b) => a + b;
    • As a Block: requires curly bracket for multi-lines arrow function
    • () => {
        statements;
      }
      
      param => {
        statements;
      }
      
      (param1, paramN) => {
        statements;
      }
    • As an Object Literal: requires parenthesis around the function body; Javascript will read the content as an object and implicitly return it
    • () => (
          { key: value }
      )
      
      // Same thing
      () => {
          return { key: value };
      }
    • More on Arrow Functions: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
  • Named functions can also be declared in another function (useful in React to pass an event handler funtion to components)
  • function outerFunction() {
        function innerFunction() {
            return 'Hello';
        }
        const a = innerFunction();
        return a;
    }

Function Parameters

  • Default Parameter: function add(a, b = 5)
  • Rest Parameters: let the function accepts an indefinite number of arguments as an array
  • function sum(...theArgs) {
      let total = 0;
      for (const arg of theArgs) {
        total += arg;
      }
      return total;
    }
  • arguments Object: useful if the function was called with more arguments than they declared
  • function sum() {
      let total = 0;
      for (const arg of arguments) {
        total += arg;
      }
      return total;
    }
    • rest parameter is preferred over using arguments object

Promise & Async

Promise and Async allow Javascript to create background tasks and not block up the main thread.

Creating a background task

  • Method 1: using Promise
// Using new Promise()
function createPromise() {
    new Promise( function(onSuccess, onFailure) {
        // Do something
        onSuccess(successValue);
        onFailure(failureValue)
    });
}

// Arrow function form
createPromise = () => {
    new Promise ( (onSuccess, onFailure) => {
        //Do something
        onSuccess(successValue);
        onFailure(failureValue);
    });
}
  • Method 2: using async
// using async
async function createPromise() {
    // Do something
    if (successful)
        return successValue;
    else
        throw new Error(failureValue);
};

// Arrow function form
createPromise = async () => {
    // Do something
    if (successful)
        return successValue;
    else
        throw new Error(failureValue);
}

Consuming a promise/ resolving a background task

  • Method 1: using .then() .catch() .finally()
createPromise()
  .then( (successValue) => console.log(successValue) )
  .catch( (failureValue) => console.log('Error: ' + failureValue) )
  .finally( () => console.log('Gets called no matter what.') );
  • Method 2: using async and await
async function getPromise() {
    try{
        successValue = await createPromise();
        console.log(successValue);
    } catch (error){
        console.log('Error: ' + error)
    } finally {
        console.log('Gets called no matter what.');
    }
}
getPromise();

Notes:

  • await has to be used in an async function
  • async / await is cleaner when successive async calls are required (i.e. fetch data → convert json to data)

Reference: developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promise


Chaining Promises

createPromise()
  .then( (result1) => doSomething1(result1) )
  .then( (result2) => doSomething2(result2) )
  .catch( (rejected) => console.log('Error: ' + rejected) )

Notes:

  • Multiple catch should be avoided in a promise chain.
  • Mixing async and normal functions is allowed.

Fetch API

fetch is used to make HTTP requests, using a RequestInit dictionary to add options to the request and processing the response by returning a Response object

async function getData() {
    const url = 'https://example.org/products.json';
    try {
        const requestOptions = {
            method: 'POST',            
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer your-token-here'
            },
            body: jsonObj,
            mode: 'cors',
            cache: 'no-cache',
            credentials: 'include'
        };
        const response = await fetch(url, requestOptions);
        if (!response.ok) {
        throw new Error('Response status: ' + response.status);
        }
        const result = await response.json();
        return result;
    } catch (error) {
        console.error(error.message);
    }
}

RequestInit Parameters

  • method: 'POST', 'GET', 'PUT', 'DELETE'
  • headers:
    • 'Content-Type': application/json, text/plain, image/jpeg, etc.
    • 'Authorization'
  • body: a string, ArrayBuffer, Blob, File, FormData, etc.
  • mode: 'cors', 'no-cors', 'same-origin'
  • cache: 'default', 'no-cache', 'reload', 'force-cache', 'only-if-cached'
  • credentials: Whether to send cookies: 'omit', 'same-origin', 'include'.
  • redirect: Redirect behavior: 'follow', 'error', 'manual'.
  • referrer: referrer URL or 'about:client'
  • keepalive: true/false; Whether the request can outlive the page (useful for analytics pings).
  • signal: Allows aborting the request using AbortController.

Response Methods

  • arrayBuffer()
  • blob()
  • bytes()
  • clone()
  • json()
  • text()
  • formData()

Notes


GET & POST

When to use GET:

  • Retrieving data without changing anything on the server
  • The request can be cached, bookmarked, and shared via URL.
  • Limited by URL length (~2,000 characters in many browsers).
  • Should not be used for sensitive data — query parameters are visible in the URL

When to use POST:

  • Sending data that changes state on the server (e.g., creating/updating records).
  • Sending large amounts of data (no URL length limit).
  • Safer for sensitive data (data goes in request body, not URL — though still use HTTPS).
  • Not cached by default.

Notes

  • GET: safe, read-only operations
  • POST: state-changing or large/ sensitive data submissions (use POST if in doubt)

URL & URLSearchParams Object

URL and URLSearchParams objects are useful for constructing URL, especially for GET requests

const u = new URL('https://example.com/path?tab=home');
const queryParams = new URLSearchParams(u.search);

queryParams.set('lang','en');       // add or update query parameter
queryParams.set('tab','profile');
u.search = queryParams.toString();  // update query

console.log(u.href);                // 'https://example.com/path?lang=en&tab=profile'

Content-Type

Content-TypeDescriptionExample Usage
application/jsonJSON-formatted dataSending API requests with JSON bodies
application/x-www-form-urlencodedForm data encoded as key-value pairsHTML forms without enctype set to multipart/form-data
multipart/form-dataForm data with files or binary dataFile uploads in HTML forms
text/plainPlain textSending simple text in request/response
text/htmlHTML markupReturning HTML content from a server
application/xmlXML-formatted dataAPIs that require XML
text/xmlXML as plain textLegacy XML APIs
application/javascriptJavaScript codeSending or returning JS scripts
application/pdfPDF documentsSending or downloading PDFs
image/pngPNG image dataUploading or returning PNG images
image/jpegJPEG image dataUploading or returning JPEG images
image/gifGIF image dataUploading or returning GIF images
application/octet-streamArbitrary binary dataFile downloads, binary uploads
application/zipZIP archivesSending or downloading ZIP files

Timers, Date, & Number Formatting

  • timeoutId = setTimeout( function(), time ) and clearTimeout( timeOutId)
  • const timeOutId = setTimeout(() => {
        console.log('This message is shown after 3 seconds');  
    }, 3000);  // time in milliseconds
    
    clearTimeout(timeOutId);
  • intervalId = setInterval( function(), time ) and clearInterval( intervalId )
  • let count = 0;
    const intervalId = setInterval(() => {
        count++;
        console.log('This message is shown every 2 seconds');
        if (count === 5) {
            clearInterval(intervalId); // Stop after 5 times
        }
    }, 2000);  // time in milliseconds
  • Date Object
  • let now = new Date(); // Current date and time
    let specificDate = new Date('2023-10-01T10:00:00'); // Specific date and time
    let specificDateNum = new Date(2023, 9, 1, 10, 0, 0); // Note: month is 0-indexed (0=Jan, 9=Oct)
    
    console.log(now.toISOString());     // ISO format
    console.log(now.toLocaleString());  // Localized format
    console.log(now.getFullYear());     // Get year
    console.log(now.getMonth());        // Get month (0-11)
    console.log(now.getDate());         // Get day of month (1-31)
    console.log(now.getHours());        // Get hours (0-23)
  • Intl Object
  • // Formatting numbers
    let number = 1234567.89;
    let formattedNumber = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(number);
    console.log(formattedNumber); // '$1,234,567.89'

Reduce Method

reduce() method reduces an array to a single value by applying a function to each element, accumulating the result

  • reduce( function(total, currentValue), initialValue)
// Sum of an array of numbers
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => {
    return accumulator + currentValue;
}, 0);                     // Initial value is 0
console.log(sum);          // Output: 15

// Example with objects
const items = [
    { name: 'apple', price: 1.2 },
    { name: 'banana', price: 0.8 },
    { name: 'orange', price: 1.5 }
];
const totalPrice = items.reduce((accumulator, item) => {
    return accumulator + item.price;
}, 0);
console.log(totalPrice);  // Output: 3.5

// Example with functions
const asyncSequence = [func1, func2, func3];
asyncSequence.reduce((p, f) => p.then(f), Promise.resolve());
// Same as Promise.resolve().then(func1).then(func2).then(func3)

Map, Filter, Reduce, forEach Methods

These methods are used to manipulate arrays in a functional programming style.

  • forEach: Executes a function for each element in the collection.
    • forEach( function(element) )
    • Available for Array, Set, and Map
    • Use when there is a side effect to the loop (i.e. writing to a file)
  • map: Executes a function for each element in the array, and save the results in a new array
    • map( function(element) )
    • Available only for Array
    • Use when you want a new array after processing old array
  • filter: Creates a shallow copy of the elements that passed the test provided by the Boolean function.
    • filter( booleanFunction(element) )
    • Available only for Array
    • Use when you want a subset of the original array
  • reduce: Executes a function for each element in the array.
    • reduce( function(total, currentValue), initialValue)
    • Available only for Array
    • For creating a new object composed of items from your array

Notes

  • Use the spread operator to convert a Set into an Array to be able to use map(), reduce(), filter()
    • const arr = [...mySet];