-3

I have this javascript function and I want to alert 12, 24, 36 ... and so on in the multiples of 12 . I have attached the code below

<script type="text/javascript">
    function test() {
        var global1=12;
        var final;
        var check;
        if(check) {
            final=global1;
            check=true;
        } else {
            final=final+12;
        }
        alert(final);
    }

    test();
    test();
    test();
</script>
Pratik Gadoya
  • 1,420
  • 1
  • 16
  • 27
confused_geek
  • 249
  • 1
  • 14
  • 1
    You need to declare `global1` outside of your function. – Zenoo Feb 09 '18 at 12:40
  • You code does not make much sense; you only set `check` when it is `true` (never...) and all your variables are local: https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript – jeroen Feb 09 '18 at 12:42
  • Apart from that you have failed to tell us what the problem is and what you want to achieve exactly. – jeroen Feb 09 '18 at 12:43
  • If(check)... Never saticefy – Sumesh TG Feb 09 '18 at 12:43

3 Answers3

1

You could take a closure over the value and the final value and return a function for updating the value until it reaches the final value.

var test = function (final) {
        var value = 0;
        return function () {
            if (value < final) {
                value += 12;
            }
            console.log(value);
        };
    }(36); // call with final value

test();
test();
test();
test();
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

In addition to my comment, here is a much simpler version for your function :

var count = 0;

function twelve(){
  count += 12;
  console.log(count);
}

twelve();
twelve();
twelve();
Zenoo
  • 12,670
  • 4
  • 45
  • 69
0

Declare the variables globally instead of function block. Example:

var global1 = 12;
var final;
var check = true;

function test()
{
    if(check) {
        final = global1;
        check = false;
    } else {
        final = final + 12;
    }
    alert(final);
}

test();
test();
test();
MH2K9
  • 11,951
  • 7
  • 32
  • 49