2

I am creating a JavaScript application where I want to generate an ArrayIndexOutOfBound Exception. I have created an array of size 5 and I am trying to insert elements from the Fibonacci series into it. Ideally, it should throw an exception after inserting 6th element, but it is not throwing any exception. Please check the code and let me know your views. Attached code and screenshots of the output.

<!DOCTYPE html>
<html>

<head>
    <title>Error Handling Demo</title>
    <script type="text/javascript">

    var i = 1;
    var fibona = [];
    fibona.length=5;

        function generateNext()
        {   
            if(i>1)
                {
                    number1.value = number2.value;
                    number2.value = number3.value;
                }

            number3.value = parseInt(number1.value) + parseInt(number2.value);
            i++;

            fibona.push({'num1':number1.value, 'num2':number2.value, 'num3':number3.value});
        }

    </script>
</head>

<body>
    <h1>Fibonacci Series Game</h1>

    <p>
        Number 1 :
        <input type = "number" name = "number1" value = 0 id = "num1">
    </p>

    <p>
        Number 2 :
        <input type = "number" name = "number2" value = 1 id = "num2">
    </p>

    <p>
        Next Number :
        <input type = "number" name = "number3" id = "num3">
    </p>

    <p>
        <input type = "button" name = "generatenext" value = "Generate Next Number" onclick = "generateNext()">
    </p>

</body>

</html>

enter image description here

Kristijan Iliev
  • 4,901
  • 10
  • 28
  • 47
pavan shah
  • 129
  • 2
  • 13
  • In JS, setting an array's `.length` property does *not* set the maximum number of elements that the array can contain. I'm not aware of any way to restrict the number of elements. – nnnnnn Aug 29 '16 at 06:39
  • @TravisRodman - No, that will just return `undefined` (if reading the value) or happily create the element at that index (if writing the value). – nnnnnn Aug 29 '16 at 06:41

3 Answers3

2

What you are experiencing is the normal behavior of the push method.

The push() method adds new items to the end of an array, and returns the new length.

Note: The new item(s) will be added at the end of the array.

Note: This method changes the length of the array.

Please read more here http://www.w3schools.com/jsref/jsref_push.asp

UPDATE: If you want to be able to constraint the max length of the array, the simplest way would be with a constant variable setting holding the length of the array and checking this value with the array's length. If you still wanna throw an exception when/if the index is greater than this max value, then you can do it by throwing your exception like this throw 'your exception message'

Kristijan Iliev
  • 4,901
  • 10
  • 28
  • 47
  • Ok. That makes sense. Any suggestions on how can I tackle this situation? Is there any other method for inserting elements in array? – pavan shah Aug 29 '16 at 06:58
  • the simplest way that came to my mind is to keep additional const variable with the max length of the array and compare the length of the array with it – Kristijan Iliev Aug 29 '16 at 07:06
  • Yes. We can use that to check if array exceeds the length. But It's not only about checking if the array exceeds length, I need to generate an ArrayOutOfBoundException. Any suggestions on that? – pavan shah Aug 29 '16 at 07:13
1

Javascript Array push would increase the length anyway.

Eg. if you declare var arr = []; and arr.length = 2 then push something arr.push("4") would give the final length as 3 which adds to your initial length. The only way to check if the array exceeds length is by traversing the array and comparing if index is greater than length of the array. The other way is to prevent the push by validating through a variable with predefined length.

You can prevent the push by comparing it with the predefined length and in else raise your custom error like this

throw new Error("outOfBoundException")

Learn more about custom exception in javascript here Custom Exceptions in JavaScript

Community
  • 1
  • 1
ajaykumar
  • 646
  • 7
  • 17
  • Ok. That makes sense. Can you elaborate your views on how to tackle this situation? It's not only about checking if the array exceeds the length, I need to generate ArrayOutOfBoundException. – pavan shah Aug 29 '16 at 07:07
  • @Pavan This you can do by enclosing the push in an if cond by comparing the length by predefined length variable. and in else statement just throw your custom error using throw new Error("outOfBoundsExcdption"). This way you prevent the push and raises the exception – ajaykumar Aug 29 '16 at 07:10
0
  1. Regarding your comment: You can just store the length in some variable, e.g.

    var data = [];
    var length = 5; // user defined length
    
    for(var i = 0; i < length; i++) {
        data.push(createSomeObject());
    }
    

In your case your doing the same as above but your not looping through the length.

  1. You might also think of using new Array() like below

new Array(4); creates an empty array of length 4. But

new Array('4'); creates an array containing the value '4'.

But not suggested as jsLint does not like new Array() because the constructer is ambiguous.

Keshan Nageswaran
  • 8,060
  • 3
  • 28
  • 45
  • I have tried using new Array(5). It gives the issue. It looks like push method increases the index of array every time while inserting elements. – pavan shah Aug 29 '16 at 07:02