function demoInitialization() {
let array = [10, 20, 30, 40];
console.log(array.toString());
//[10, 20, 30, 40]
}
//Try It
demoInitialization()
function demoArrayLength() {
let array = [10, 20, 30, 40];
let len = array.length;
console.log("Length: " + len);
//prints 4
}
//Try It
demoArrayLength()
function demoAccessFirstElement() {
let array = [10, 20, 30, 40];
//Fixed array is zero-based (first element is index pos 0)
console.log("First Element: " + array[0]);
//prints 10
}
//Try It
demoAccessFirstElement()
function demoAccessThirdElement() {
let array = [10, 20, 30, 40];
console.log("Third Element: " + array[2]);
//prints 30
}
//Try It
demoAccessSecondElement()
function demoAccessLastElement() {
//Leverage the relationship between length and the last index
let array = [10, 20, 30, 40];
console.log("Last Element: " + array[array.length - 1]);
//prints 40
}
//Try It
demoAccessLastElement()
function demoSetSecondElement() {
let array = [10, 20, 30, 40];
array[1] = 101;
console.log(array.toString());
//prints [10, 101, 30, 40]
}
//Try It
demoSetSecondElement()
function demoElementIteration() {
//Iterate over elements
let array = [10, 20, 30, 40];
for (let nextElement of array) {
console.log("Next element in iteration: " + nextElement);
}
}
//Try It
demoElementIteration()
function demoIndexedIteration() {
let array = [10, 20, 30, 40];
for (let nextIndex = 0; nextIndex < array.length; nextIndex++) {
console.log("Next element in iteration: " + array[nextIndex]);
}
}
//Try It
demoIndexedIteration()