0

I have created the following function in JavaScript which is working as expected:

<script>
    function add(a, b, c) {
        document.write('A: ' + a + '<br>');
        document.write('B: ' + b + '<br>');
        document.write('C: ' + c + '<br>');
    }
add(10, 20);
</script>

Output:

A: 10
B: 20
C: undefined

However, the following function in JavaScript is not working as expected wherein it is not displaying undefined value

<script>
    function addArray(a = [101]) {
        document.write('A: ' + a[0] + '<br>');
        document.write('B: ' + a + '<br>');
        document.write('C: ' + c + '<br>');
    }
    addArray([110]);
</script>

Output:

A: 110
B: 110

As per my understanding the output should be as below:

Expected Output:

A: 110
B: 110
C: undefined

Also, what is difference between a[0] and a in the above example?

meallhour
  • 13,921
  • 21
  • 60
  • 117

2 Answers2

0

c is never declared

    function addArray(a=[101],c) {
        document.write('A: ' + a[0] + '<br>');
        document.write('B: ' + a + '<br>');
        document.write('C: ' + c + '<br>');
    }
    addArray([110,120]);
DCR
  • 14,737
  • 12
  • 52
  • 115
0
 The difference between a[0] and a is that a[0] is displaying the first index value of an 
 array and a is displaying all the values of the array.

 Imagine A=[100,200]
 document.write('A: ' + a[0] + '<br>');
 Would write 100
 document.write('A: ' + a + '<br>');
 Would write 100,200
Arundeep Chohan
  • 9,779
  • 5
  • 15
  • 32