Profound comprehension: What is the fundamental reasoning behind the functionality of array indexing?

Questioning the Logic Behind Array Indexing

When delving into the world of programming, there is a certain excitement that comes with truly grasping the logic behind a language. The ability to navigate and problem-solve based on that logic is rewarding. However, encountering discrepancies in this logic can be puzzling.

Diving into Indexes

Exploring array indexes has led me to discover the following:

var fruit = ["Apple", "Orange", "Kiwi"]

fruit.length = 3 // gives the length of the fruit array

var rotten = fruit[2] // assigns "Kiwi" to the variable "rotten"

fruit[2] = "Melon" // changes the third element in the array from "Kiwi" to "Melon"
fruit[fruit.length] = "Melon" // adds a new element to the array after "Kiwi"

Unraveling the Mysteries of Logic

After using .length to determine my array's length, I naturally expected to access the third element with var rotten = fruit[3]. To my surprise, this returned undefined since indexing starts at 0, not 1.

A similar confusion arose when attempting to add an element with

fruit[fruit.length + 1] = "Melon"
, under the assumption that .length refers to the last element. In reality, as per the 0-based index, it represents 2, not 3.

Pondering the Nature of Arrays

Is there a deeper rationale behind the choice of starting indexing at 0 instead of 1? Does this non-intuitive approach enhance JavaScript's functionality, or is it simply a rule to be accepted without questioning?

Answer â„–1

When it comes to indexing arrays in programming languages, there are different conventions depending on the language family. In Fortran-based languages, arrays start at index 1 following standard mathematical practice. However, in languages like Algol-60/PASCAL, BCPL, and C, the starting index can be chosen by the programmer—ranging from 0, 1, or any other number. Most modern languages, excluding Julia, adopt the convention of starting array indices at 0.

It has been recognized over time that having a single convention is beneficial for code clarity and consistency. PASCAL-style indexing, where the starting index varies, can lead to confusion when merging code written by multiple programmers.

The debate between starting at 0 or 1 is somewhat arbitrary, but many experts argue that beginning at 0 simplifies operations and reduces errors. For instance, consider these two implementations of array interleaving, one based at 0:

if(i % 2 == 0)
    a[i / 2] = 42;
else
    b[(i - 1) / 2] = 42;

and another based at 1:

if(i % 2 == 1)
    a[(i + 1) / 2] = 42;
else
    b[i / 2] = 42;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Browsing through a collection of pictures, I find myself wanting to linger on the final image rather than swiftly exiting the window

The functionality currently implemented is as follows: $("#btnNextImage").click(function (e) { var win = window.opener.parent; win.postMessage('next', '*'); window.close(); //close ...

Learn how to creatively style buttons with dynamic effects using tailwindcss

My Desired Button: I have a Button component that can accept a variant prop. My goal is to have the button's className change dynamically based on the prop passed to it. Instead of using if/else statements for different buttons, I want to use a sing ...

What is the best way to change an existing boolean value in Prisma using MongoDB?

Exploring prisma with mongoDb for the first time and faced a challenge. I need to update a boolean value in a collection but struggling to find the right query to switch it between true and false... :( const updateUser = await prisma.user.update({ where: ...

JavaScript code for modifying style properties

Is there a way to modify this function so that when the heading is changed successfully, a "Change Back!" button appears? And then, with a click on the button, the heading is reset and the button disappears again. function changer () { var textArea = ...

Ways to execute a script from termly on NextJS using JSX

I've been utilizing termly to assist in creating legal terms for a website I'm developing. They provided me with some HTML containing a script, but I am struggling to get it to execute on a page in JSX. I attempted to use both Script and dangerou ...

Tips and tricks for sending variables to an iFrame using jQuery functions

My goal is to dynamically change the source, width, and height of an iframe based on the link that is clicked. Currently, I am able to fire the iframe with hardcoded values using the following code: This is what works: $('.myLink').click(functi ...

Struggling to incorporate z-index for a tooltip component that overlaps in a project utilizing React, Tailwind, and DaisyUI

Hello everyone, I trust you are all doing great. I have a query regarding a Fireship IO tutorial on incorporating TailwindCSS and DaisyUI into React. I've managed to create a side navbar similar to Discord, complete with tooltips that display as span ...

What is the best way to show and hide the information in a FAQ section when each one is clicked?

const faqItems = document.getElementsByClassName("faq-question"); const faqContents = document.getElementsByClassName("faq-content"); for (item of faqItems) { console.log(item); item.addEventListene ...

The navigation links will remain visible even when the unordered list is set to 0% opacity

I've been working on creating a side navigation menu using HTML, CSS, and Javascript. I successfully implemented the function to toggle open and close the navigation, but upon adding a background image, I noticed that the links still appear even when ...

Utilize DTOptionsBuilder and AngularJs ColVis to trigger actions when there are changes in column visibility

In my AngularJs project, I am using DTOptionsBuilder with ColVis plugin to show and hide columns in a datatable. I need to perform certain operations when the visibility of the columns changes. I came across an event called 'column-visibility.dt' ...

What is the best way to implement a useState within a context for testing with jest?

function CustomComponent() { const {val, change} = useContext(ProviderContext) return ( <TextField> onChange={({target}) => { change(target) }} value={val} </TextField> ); } describe('test', ( ...

Using JavaScript within WordPress to achieve a seamless scrolling effect

I am seeking to implement a Smooth Scroll effect on my website located at . The site is built on WordPress and I am facing difficulty in connecting JavaScript/jQuery in WordPress. I have come across various WordPress plugins, but they either do not meet my ...

Attempting to execute a PHP script through a JavaScript if statement

I have a form that requires validation with JavaScript. In one of the if statements, after all other conditions have been validated, I want to execute my PHP script that updates an SQL database with one of the passwords. Here is the final validation code: ...

Avoiding Scroll Reset on Browser Navigation with Delayed Transition

I've recently implemented a delay in my router configuration on my website. However, I've noticed that when I try to navigate using the browser's back and forward buttons, it first jumps to the top of the page because of the delay set with { ...

Can you provide instructions on executing package dependencies using yarn in the command line? For example, is there a command similar to npx tsc init for initializing a npm

When utilizing yarn, the node_modules folder is not present. Instead, dependencies are stored in a .yarn/cache folder. I attempted to use yarn dlx tsc init and npx tsc init, but they did not achieve the desired result. There are various development depend ...

Assign AngularJS directives to DOM element using controller

I'm experimenting with the idea of controlling the angular directive('ng-show') from the controller. Here is what I'm attempting to do: var node = `<div ng-show="this.length > 5">...</div>`; var child = document.creat ...

The click event fails to trigger on dynamically loaded Ajax content

I've encountered an issue while loading content using ajax from external HTML Files. After the content is loaded, the click event doesn't seem to be working in Safari (including mobile safari) for any of the newly loaded elements such as ul, li, ...

Display more/hide less form using div elements in a NextJS project

Looking to create a hidden block of amenities on my hotel website that can be expanded and collapsed with buttons in NextJS using tailwind-css. How can I achieve this functionality? Example 1: https://i.stack.imgur.com/BbrUj.png Example-2: https://i.stac ...

Ways to navigate to a different page in React when a user clicks?

When working on my react app, I encountered an issue where the useHistory hook was undefined. How can I troubleshoot this problem and ensure that useHistory is properly defined? App.js import 'bootstrap/dist/css/bootstrap.css' import React f ...

Python code to transform an integer array into a binary array

I'm attempting to convert an array of integers into binary format using Python 2.7. Here's a simplified version of the code I'm working with: #!/usr/bin/python import numpy as np a = np.array([6, 1, 5, 0, 2]) b = np.zeros((5)) for i i ...