JavaScript - Array "undefined" error - javascript

I got a problem with this simple piece of code which i cant figure out.
Instead of printing the whole array in the console, i get the message "10 undefined". Altough if i put "var i" to 0 or below then it's all good and i get a full list from that number up to 10.
Why wont this work when "i" is set to a number above 0?
Took a picture of my console in chrome to show how it looks like:
var ar = [];
for (var i = 1; i <= 10; i++) {
ar.push(i);
console.log(ar[i]);
}

JavaScript array indices start at 0, not 1. The .push() method adds an element at the end of the array, which in the case of an empty array (as yours is when your loop begins) will be array element 0.
Your loop inserts the value 1 at array index 0, the value 2 at array index 1, and so forth up to the value 10 at array index 9.
Each of your console.log(ar[i]) statements is trying to log a value from an index one higher than the highest element index, and those elements will always be undefined. So the console logs the value undefined ten times.
You can log the last element of an array like this:
console.log(ar[ar.length-1]);
Or in your case where you (now) know that i will be one higher than the index that .push() used:
console.log(ar[i-1]);

"10 undefined" means that the console showed "undefined" 10 times.
As thefourtheye says in his comment, you're pushing the value i but the index of the element that you just pushed onto the end of the array is i - 1. This means that each time you console.log(ar[i]) you're logging something that's not yet defined.
This is all because the first element in the array is ar[0], not ar[1]. You can fix your problem by logging like so: console.log(ar[ i - 1 ]);

Because array indices start at zero. The current index is undefined that's why you get those. Try this instead:
var ar = [];
for(var i = 1;i <= 10;i++){
ar.push(i);
console.log(ar[i-1]);
}

Related

For Loop while referring to an array with Length

I'm very new to javascript and have just recently learned about For loops. I have a variable that consists of an array containing a bunch names, and I would like to add last names to each of them. I wrote the code as shown below and have a few questions.
let name = ["john", "maria", "brandon", "gaby", "jessica", "angel"];
function addLastName(array) {
for (let i = 0; i < array.length; i++) {
console.log(name[i] + " (please insert last name)")
}
}
console.log(addLastName(name))
Result :
john (please insert last name)
maria (please insert last name)
brandon (please insert last name)
gaby (please insert last name)
jessica (please insert last name)
angel (please insert last name)
undefined
Questions:
About the second statement for the loop. Correct me if I'm wrong, but when using length in an array, it will show the amount of data inside the array right? So in this case, name.length = 6. But to my understanding, when accessing a part of an array, the count always starts at 0. So I used array.length-1. But the result didn't show "Angel". When I used array.length, the result showed Angel. What logic am I missing here?
When I put the result on the console, there's always an "undefined" at the end of it, whether I used array.length or array.length-1. Can anybody tell me why it showed up?
For your first question:
Inside the for loop, if you start from 0, and the condition is i < array.length and the length of the array is 6, it will go from 0 to 5, and when it reaches 6 it will not respect the condition (6 < 6 false) so it will exit the for loop before executing the block inside (but when you exited the for, i will be 6).
For your second question:
You should not call console.log(addLastName(name)) because addLastName already logs to the console. That console.log is the one that prints undefined since it will print the result of the function, which is undefined by default if you do not return anything inside the function.

What is the function of 'i' in for loop in JavaScript when accessing arrays?

const rapperArray = ['Tupac', 'Jay-Z', 'Notorious B.I.G', 'Kendrick Lamar']
for (let i = 0; i < rapperArray.length; i++) {
console.log(rapperArray[i]);
if (i === 2) {
break;
}
}
console.log("And if you don't know, now you know.");
So how does i work in that console.log( rapperArray[ i ] );? I know that it accesses the elements in the array but I can't seem to get my head around how it actually functions.
The i is a variable. In a for loop, you have the following syntax:
for(initialization; condition; update) {
// for loop body
}
The for loop will begin by running the initialization portion first, which in this case declares the variable i with an initial value of 0. Before each iteration of the loop, condition is checked and the loop body will run as long as condition is true. Then, after the loop body runs, update will run. In this case, the variable i will have its value incremented by 1, i.e. i++ is basically the same thing as i += 1.
In other words, the for loop will use every value of i from 0 up until rapperArray.length - 1. So console.log(rapperArray[i]); will be the same as console.log(rapperArray[0]); in the first iteration, console.log(rapperArray[1]); in the second iteration, and so on.
You can see this more clearly by running the following:
const rapperArray = ['Tupac', 'Jay-Z', 'Notorious B.I.G', 'Kendrick Lamar'];
for (let i = 0; i < rapperArray.length; i++) {
console.log('When i is ' + i + ', rapperArray[i] is ' + rapperArray[i] + '.');
}
A for loop header consists of three parts:
Initial state let i = 0
Condition to check if loop should continue i < length
Increment per run i++
We start with 0, in the beginning i is lower than length, then we up it by 1 (i++ increases i by 1), if it's still lower than length - we continue until i has the same value as length and then we stop.
It indicates the current iteration of the loop. For each iteration, i is incremented. When used to get an array item, it represents the index of the item to retrieve from the array. You can read more about indexed collections here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections
Arrays in JavaScript are zero-index based, which means the first index is always zero. And they increment from there. Arrays are ordered collections, so the item at the first index (zero) is always the same, and so on.
If you have a list on paper in front of you, you may number the lines starting with 1 and going up from there. Each item in an array is somewhat like each line on that piece of paper, only the line numbers start at zero instead of one. If you want to get line n from the paper, you find the line numbered n and there you go.

Javascript for() to add values to array

I have a program that displays errors like this:
wifi : 298
So, it says the type of error and the number.
Right now there are 8 errors, which I have divided by type and number, so 16 values. I would like to add them to an array like:
var array{type:'____', number:'____'}
I would like to add the values via function, so it can be automatic, in case I add ou remove errors to display, a for seems the best way to do it.
Problem is.. I'm horrible at math..
I've tried a for where i starts at -1 and its i++. The type would be value[i+1] and the number would be value[i+2].
This would be the result:
i=-1
type=value[0]
number=value[1]
i=0
type=value[1]
number=value[2]
So you see, value[1] appears twice:
0
1
1
2
When it should only appear once:
0
1
2
3
var errorSplit = errorlog.split(/:|;/);
var errors;
for(var i=-1;i<16;i++){
errors= {type: errorSplit[i+1], num: errorSplit[i+2]};
}
Just up it by 2 on every iteration. I would also suggest slight changes for readability (Replacing -1 by 0 and changing index acccessors).
You need to make the errors array an actual array and add things to it not overwriting them.
You can make the loop variable length too by just using the errorSplit length as a limiter.
var errorSplit = errorlog.split(/:|;/);
var errors=[]; // Make the array an actual array
for(var i=0; i<errorSplit.length; i+=2) { // Start at index 0, go until there are no errorSplit parts left, up it by 2 every iteration
if(errorSplit.length<(i+1)) // If the index is higher than errorSplit+1, exit the loop
break;
errors.push({type: errorSplit[i], num: errorSplit[i+1]}); // Add the element to the array
}

Undefined key coming

Below is the code:
var xx=[];
xx['1'] ={'a':'bb','c':'dd'}
debugger;
document.log(xx);
When I print xx it says undefined for key
https://jsfiddle.net/kjuhpgn2/
Can you let me know why "undefined" is coming instead of "1" as key?
Edit:
I got that, it should be {} instead of []
var xx={};
Array indexing start at 0.
What it's saying is that you have nothing at index 0.
When you set xx[1]=something starting from an array of size 0, you set the length of the array to 2, with your something at index 1 and with undefined "filling" the position at index 0.
If what you want is to store a dictionary, then don't use an array but an object as map:
var xx={};
xx['1'] ={'a':'bb','c':'dd'}
This way you wouldn't create a sparse array.

using .slice method on an array

I'm practicing the array section of JavaScript Koan and I'm not fully understanding why these answers are correct. I added my assumptions below if someone could please clarify/let me know if I'm wrong :
it("should slice arrays", function () {
var array = ["peanut", "butter", "and", "jelly"];
expect(array.slice(3, 0)).toEqual([]);
Why wouldn't it at least slice "jelly" since the slice begins with
3? How does the cut off of 0 make it empty instead?
expect(array.slice(3, 100)).toEqual(["jelly"]);
If the cut off index goes beyond what currently exists in the array,
does this mean that a new array created from slice would contain all
indexes starting at 3 until the end of the array?
expect(array.slice(5, 1)).toEqual([undefined];
Will it always be undefined if the starting index doesn't exist in the
array?
});
The second argument to Array.slice() is the upper bound of the slice.
Think of it as array.slice(lowestIndex, highestIndex).
When you slice from index 3 to index 100, there is one item (in your case) that has index >= 3 and < 100, so you get an array with that one item. When you try to take a slice from index 3 to index 0, there can't be any items that meet the conditions index >= 3 and < 0, so you get an empty array.
--EDIT--
Also, array.slice() should never return undefined. That's one of the advantages of using it. If there are no matching values in the array, you just get back an empty array. Even if you say var a = new Array() and don't add any values to it, calling a.slice(0,1) will just give you an empty array back. Slicing from outside of the array bounds will just return an empty array also. a.slice(250) will return [] whereas a[250] will be undefined.

Categories

Resources