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

2
  • 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. Commented Aug 29, 2016 at 6:39
  • @TravisRodman - No, that will just return undefined (if reading the value) or happily create the element at that index (if writing the value). Commented Aug 29, 2016 at 6:41

3 Answers 3

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'

Sign up to request clarification or add additional context in comments.

3 Comments

Ok. That makes sense. Any suggestions on how can I tackle this situation? Is there any other method for inserting elements in array?
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
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?
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

2 Comments

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 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
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.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.