Create a variable within a JavaScript function that retains its value each time the function is called

Is there a way to declare a variable inside a JavaScript function so that it initializes once with the following behavior?

The initialization should occur only once.

function counter() {
  let_special count = 0;
  count++;
  if (count == 3) {
    count = 5;
  }
  return count;
}

let x = counter(); // x = 1
let y = counter(); // x = 2
let z = counter(); // x = 5
let m = counter(); // x = 6
let n = counter(); // x = 7

I vaguely remember there being a method to achieve this, but I cannot seem to find it on Google at the moment.

Thank you!

Answer №1

How can a variable inside a JavaScript function retain its value across multiple calls?

One approach is to declare the variable outside of the function.

let count = 0;

function counter() {
  count++;
  if (count == 3) {
    count = 5;
  }
  return count;
}

let a = counter(); // a = 1
let b = counter(); // b = 2
let c = counter(); // c = 5
let d = counter(); // d = 6
let e = counter(); // e = 7

This can even be done within another function scope.

function makeCounter() {
  let count = 0;

  function counter() {
    count++;
    if (count == 3) {
      count = 5;
    }
    return count;
  }

  return counter;
}

let count = makeCounter();
let count2 = makeCounter();
let a = count(); // a = 1
let b = count(); // b = 2
let c = count(); // c = 5
let d = count(); // d = 6
let e = count(); // e = 7

let f = count2(); // f = 1
let g = count2(); // g = 2

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to Insert PHP/MySql Data into JavaScript

As I delve deeper into PHP OOP, I feel like I'm making progress in transitioning my website. Currently, each user has their own page with a javascript grid tailored to their specific needs. For easier maintenance, I'm considering the idea of havi ...

How can CSS variables be applied to a hover property within an Angular directive?

Check out the directive below: import { Directive, ElementRef, HostListener } from '@angular/core'; @Directive({ selector: 'd-btn', host: {} }) export class ButtonDirective { constructor(private el: ElementRef){} @HostLis ...

Implementing a JavaScript Function to Retrieve a Value When a Button is Clicked

<!DOCTYPE html> <html> <body> <button id="one">Try it</button> <h1>JavaScript Functions</h1> <p id="demo"></p> <script> var x=document.getElementById("one").addEventListener("click", onefunction); ...

What is the quickest method to forward a page to a different web address?

I am looking to direct traffic from my Blogger website to an external URL and have found two possible methods to do so: One option is to use a meta tag: <meta http-equiv="Refresh" content="0; url='https://google.com' Alternativ ...

Issues with command functionality within the VS Code integrated terminal (Bash) causing disruptions

When using Visual Studio Code's integrated terminal with bash as the shell, I have noticed that commands like ng and tsc are not recognized. Can anyone shed some light on why this might be happening? ...

Identifying Canvas Scrolling in iOS Safari using the Touchmove Event

I have encountered an issue while trying to detect scroll canvas from a touchmove event. It works perfectly on all browsers except for Safari. In Safari, the pageY and screenY coordinates of the touchmove event are not consistent. When I touch and move d ...

AJAX causing issues with file upload functionality

I am currently utilizing AJAX in a file upload process, you can view it here. However, I am facing an issue where the value is not being passed from one page (upload.php) to another page (file_upload_submit.php). I am unsure of how to retrieve the file val ...

Having difficulty retrieving the value of a variable obtained from the Google Distance Matrix function

Utilizing the Google distance matrix API to calculate the distance between two locations, I encountered an issue with global variable access. Despite changing the variable within a function, I found that I was unable to retrieve the updated value of the va ...

Here is a way to trigger a function when a select option is changed, passing the selected option as a parameter to the function

Is there a way to call a function with specific parameters when the value of a select element changes in Angular? <div class="col-sm-6 col-md-4"> <label class="mobileNumberLabel " for="mobilrNumber">Select Service</label> <div cla ...

Tips for minimizing the need to copy the entire dojo library each time you create a new Java EE package for deployment on GlassFish

Currently, I am diving into comet programming and utilizing the cometd implementation along with the JavaScript dojo library before deploying my war files to GlassFish. The issue I have encountered is that every time I create a new project, I find myself i ...

Understanding the Significance of this Regular Expression

I need assistance with regular expressions as I am not very familiar with them. The issue I am facing is related to a jQuery dynacloud plugin that stops working when a regex match occurs in my code. Can someone please help me understand what this regex mat ...

What is the best way to handle JSON data errors when a value is undefined?

I am currently working on a piece of code that displays JSON data in HTML. However, if a value is undefined, it doesn't display anything. How can I handle this error so that if a value is undefined, it will show "N/A" instead of breaking the code? ...

What is the best way to access a variable from a different function in JavaScript?

In my current project, I have implemented a function that fetches a JSON string from an external URL. The JSON data is being retrieved successfully and is functioning as expected. However, I am facing an issue with the variable 'procode'. I need ...

Simultaneous beforeSave actions permitting repetitions

To prevent certain objects from being created, I incorporated a conditional in the beforeSave cloud function of that object type. However, when two objects are created at the same time, the conditional fails to work as expected. Check out my code snippet ...

Enabling third party cookies in incognito mode for iframes: A step-by-step guide

When integrating a Next.js form deployed on Netlify into a React.js project using an iframe, I encountered the following error: Error Message The console displayed the error message: "Uncaught DOMException: Failed to read the 'localStorage' pro ...

Guide to Embedding an Image in a List in HTML

How do I resize an image according to the size specified in CSS, and ensure that it fits within a list of items where each item consists of both an image and a name? Currently, my code only displays the image in its original size. for(var i =0; i< o ...

Determining the height of a <td> element and the font size of a <p> element using JavaScript

What is the best way to adjust the height of a <td> element and change the CSS property for font size in a <p> using JavaScript? ...

AngularJS view doesn't reflect changes made to the model

After exploring various questions on Stack Overflow, I have read numerous answers but still cannot seem to solve my issue. I am currently using Angular Material and struggling with the synchronization between the view and model. Here is the code for my c ...

Tips for Customizing Dialogs with CSS Classes in mui5 Using Emotion/Styled

When attempting to customize the styling of a mui Dialog, I encountered an issue where it wouldn't accept className even when placed inside PaperProps. While inline styles worked, my preference was to import styles from a separate stylesheet named Sty ...

Having difficulty retaining the value of a variable following the retrieval of JSON data

For my current project, I am utilizing the highstocks charting library in combination with JQuery. My goal is to create a single chart divided into three sections, each displaying different data sets. To import the data, I have referenced the sample code p ...