user3247128
user3247128

Reputation: 359

Javascript brackets

I have a piece of code that looks like this;

var x(10);
var i = 3;
x(i) = 7
document.write("The stored value is " + x(3) +"

This is a piece of code in the book I am reading from, but they don't explain what the brackets mean? Does x(10) mean that x is 10? That wouldn't make sense. Same with x(i), what does that even mean? I don't understand what output I would get from this! I want to understand it before I move on to the next section so I'm not confused. I'm thinking the output would be 7, but I still would like to understand the meaning behind the brackets.

Upvotes: 2

Views: 253

Answers (3)

wandering-geek
wandering-geek

Reputation: 1380

You could always try the below

var x = [10]; // Declare an array with a single element, which is 10
var i = 3; // Declare another variable

x[i] = 7; 
/* Assign a value to index 3 of the array. Index 0 is occupied by 10. So indices 1 and 2 will be undefined. JS arrays grow automatically when new elements are added. */ 

document.write("The stored value is " + x[3]); // Print the value in the 3rd index of the array, which you set in the last line.

This will execute in your browser console.

Upvotes: 3

John
John

Reputation: 2852

The example tells that your are reading Arrays. Below is the explanation.

var x(10);

An array is defined with size 10

var i = 3;
x(i) = 7;

The 4th element of the array is assigned a value of 7. The first element count always starts from 0

document.write("The stored value is " + x(3) +"

document.write method is used to print the output. BTW, your syntax is wrong, you missed the ; on the third line.

Upvotes: 0

Joy
Joy

Reputation: 9550

var x(10); is trying to define a variable whose name is x(10) and value is undefined.

However, x(10) is an illegal javascript variable name. Your snippet would not run on Chrome console.

A javascript variable name validator: https://mothereff.in/js-variables

Reference: https://mathiasbynens.be/notes/javascript-identifiers

Upvotes: 0

Related Questions