I’m not sure that this is actually possible in vanilla Bubble.
The equivalent solution to what you want to do is to install Toolbox plugin. The JavaScript to Bubble Element there is essentially a JS-accessible custom state. The Run JavaScript action you get from Toolbox can be used to set its value. Similarly the Expression element found there is an element that holds the value of a dynamically updated JS function.
Short intro: