Saturday, October 18, 2025
HomeLanguagesJavascriptp5.js getItem() Function

p5.js getItem() Function

The getItem() function is used to retrieve the value that has been stored using the storeItem() function under the given key name from the local storage of the browser. It returns a null value if the key is not found.

The local storage persists between browsing sessions and can store the values even after reloading the page unless it is cleared.

Syntax:

getItem(key)

Parameters: This function accepts a single parameter as mentioned above and described below:

  • key: This is a string which denotes the key for which the value has to be retrieved.

Return Value: It returns the value of the stored item, which can be a String, Number, Boolean, Object, p5.Color or a p5.Vector.

Below example illustrates the getItem() function in p5.js:

Example:




function setup() {
  createCanvas(500, 300);
  textSize(20);
  text("Use the button to set and retrieve random values", 20, 20);
  
  getBtn = createButton('Get items from storage');
  getBtn.position(20, 150);
  getBtn.mouseClicked(retrieveStorage)
  
  setBtn = createButton('Set items to storage');
  setBtn.position(20, 180);
  setBtn.mouseClicked(setStorage)
}
  
function retrieveStorage() {
  clear();
  text("Use the button to set and retrieve random values", 20, 20);
  
  // retrieve values from local storage
  num = getItem('savedNumber');
  string = getItem('savedString');
  bool = getItem('savedBoolean');
  
  // display the values
  text("The retrieved items are:", 20, 40);
  text("Number: " + num, 20, 60);
  text("String: " + string, 20, 80);
  text("Boolean: " + bool, 20, 100);
}
  
function setStorage() {
  // generate random values
  randomNum = floor(random(100));
  randomStr = "Random String " + randomNum;
  randomBool = randomNum > 50 ? true : false;
  
  // store values to local storage
  storeItem('savedNumber', randomNum);
  storeItem('savedString', randomStr);
  storeItem('savedBoolean', randomBool);
}


Output:

Online editor: https://editor.p5js.org/
Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/

Reference: https://p5js.org/reference/#/p5/getItem

RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS