Back to the 2023 paper

Module III: Basics of Web Programming

20237m

Illustrate with suitable code samples, the different ways of Array declaration in Java Script. Arrays in Java Script are said to be more flexible, why?

Worked SolutionAI Assisted

Ways to declare arrays in JavaScript

1. Array literal (most common)

const fruits = ["apple", "banana", "mango"];
const empty  = [];

2. new Array() constructor

const a = new Array("red", "green", "blue");
const b = new Array(5);        // 5 empty slots (length 5)

Caution: new Array(3) makes an array of length 3, whereas new Array(3, 4) makes [3, 4].

3. Array.of()

const c = Array.of(3);         // [3]

4. Array.from()

const d = Array.from("abc");            // ['a','b','c']
const e = Array.from({length: 4}, (_, i) => i * 2);   // [0,2,4,6]

5. Spread syntax

const f = [...fruits, "kiwi"];          // copy and extend

6. Declaring then filling by index

const g = [];
g[0] = 10;
g[1] = 20;

Why JavaScript arrays are called flexible

  1. Dynamic size: they grow or shrink automatically; there is no fixed length. Use push, pop, shift, unshift, splice, or set length.
  2. Mixed types: one array can hold numbers, strings, booleans, objects, functions, or other arrays.
    const mix = [1, "two", true, {id: 3}, [4, 5], () => 6];
    
  3. No need to declare a size or type up front.
  4. Sparse arrays: indexes can be skipped (g[100] = 1 leaves gaps).
  5. Rich built-in methods: map, filter, reduce, forEach, sort, slice, find, includes.
  6. Behave like objects: they can carry extra properties, and length can be changed directly.

This flexibility comes at a small performance cost compared to fixed-type arrays in languages like Java or C.

Similar questions

Official AppAndroid App

PYQDeck for Android

Solve BEU previous-year exam papers anywhere, anytime. Fast search, offline paper viewing, and step-by-step solutions designed specifically for your phone.