Skip to content Skip to sidebar Skip to footer

What Is The Correct Javascript Term For The Square Brackets In This Context?

In the lines of the script marked 1) and 2) near the end, where I have commented, my question is about the square brackets? What is the correct javascript term for the square brack

Solution 1:

These are called Index or Bracket Property Accessors. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors

Property accessors provide access to an object's properties by using the dot notation or the bracket notation.

In Javascript you access elements of an array using the Index, or simply Bracket, notation. Which is exactly what you have in the code.

Similarly, you can access an object's properties using either the Dot notation:

  • myObj.property1

Or the Index/Bracket notation:

  • myObj["property1"]

To be exact, the Index terminology is more appropriate when referring to elements of an array, and the Bracket terminology is more appropriate when referring to properties of an object. Personally, I use the terminology interchangeably.


On your second question, no! Brackets [] are distinct from parentheses (). Parentheses are used for calling functions. Brackets are only used for accessing array elements or object properties.

function sayHello() { // Function definition. Parentheses needed. return"Hello!";
} 

var result = sayHello(); // Calling a function. Parentheses needed.var obj = { // Object definition. No parentheses.
    name: "Emma"
}

var objName1 = obj.name;  // Accessing a property using Dot notation.var objName2 = obj["name"]; // Accessing property using Bracket notation. 

Solution 2:

It is called property accessor with bracket notation.

object.property// dot notationobject['property']// bracket notation

You can use a stringified index, like 1 or just 1. If the given property accessor is not a string, it gets converted to string in advanve.

You use document.getElementsByClassName:

Returns an array-like object of all child elements which have all of the given class names. When called on the document object, the complete document is searched, including the root node. You may also call getElementsByClassName() on any element; it will return only elements which are descendants of the specified root element with the given class names.

var x = document.getElementsByClassName("mySlides"); // returns an array like object// iterable with index and// has a length propertyfor (i = 0; i < x.length; i++) {
    x[i].style.display = "none";
//   ^^^                                             // take the element at index i
}

x[slideIndex - 1].style.display = "block";
//^^^^^^^^^^^^^^^                                    // calculate an index

Post a Comment for "What Is The Correct Javascript Term For The Square Brackets In This Context?"