Luc
Luc

Reputation: 9

Getting a percentage of a variable

I'm a beginner in Javascript en Google Tag Manager, so I have a problem. I need to make a new variable that takes a certain percentage of an eCommerce variable (revenue). I tried different things but I keep getting errors. Thus far I got this:

var percentage = (function() {
    return function(n,percent){
     return n*percent/100;
    };
    
})();
    
console.log(percentage(98, {{Ecommerce - Revenue}}));

I hope someone can help me with this!

Upvotes: 0

Views: 125

Answers (2)

Liam
Liam

Reputation: 29714

You just need a simple function and invocation:

//declare the function
function percentage(n,percent){
     return n*percent/100;
    };
    
//invoke it
console.log(percentage(98, 10));

Unless you're specifically trying to create some kind of closure/IIFE then do:

//function closure
var funcHolder = function(){

   function percentage(n,percent){
     return n*percent/100;
    };
    
    //return enclosed function for usage outside of the function
    return { percentage: percentage};
   }();
    
//invoke the returned function using the closure
console.log(funcHolder.percentage(98, 10));

The above is an example of the revealing module pattern

Upvotes: 1

Mark Baijens
Mark Baijens

Reputation: 13222

If you define your own scope using the self calling function construction then you have to place your code within this self calling function.

(function() {
  var percentage = function(n, percent) {
    return n * percent / 100;
  }
  console.log(percentage(98, 200));
}());

Upvotes: 0

Related Questions