Why does my code always end with undefined? - javascript

I wrote this JavaScript code, but it always ends **undefined**mycode? What have I done wrong/ how can I prevent this in the future. I am running my code through the chrome javascript console.
Here is my code
//Reverse a string
//-------------------------//
//Input a string
var string = prompt("Please enter string");
//console.log(string);
//Find length of string
var stringLength = string.length;
//console.log(stringLength);
//Creating an empty string for outputting answer
var reversedString = "";
//Start from length of the string and work backwards, inputting letter 1 at a time.
for (var i = stringLength; i >= 0; i--){
reversedString += string[i];
//console.log(string[i]);
}
//Outputting the reversed string;
alert(reversedString);
Thanks for any answers in advance

Change your loop from
for (var i = stringLength; i >= 0; i--){
to
for (var i = stringLength-1; i >= 0; i--){
The problem is, the array indices in javascript are 0 based.
Lets say the string entered in the prompt is "abc", the length of the string is 3. In the loop, you access it as string[3] which is undefined. Hence the error.
Here is the fiddle demonstrating the updated code:
http://jsfiddle.net/rf1vmyzg/

adding string[i] is the last thing this code does before alerting you, so therefore the last string[i], (first element in your array, I assume) has the value of undefined.
for (var i = stringLength; i >= 0; i--){
reversedString += string[i];
//console.log(string[i]);
}
I do not know on the top of my head why this is, but I know that it is always a good idea to stick to conventions, and the one for for loops is:
for(var i = 0; i < [length variable];i++) {
...
}

Right code
for (var i = stringLength-1; i >= 0; i--){
reversedString += string[i];
console.log(string[i]);
}

You should not do string[i] instead do string.charAt(i); Also change stringLength to stringLength - 1. That should fix your problem. If you want this to work across different browsers use charAt notation. Javascript arrays start at 0 not 1 that is why you do length - 1 to get the last element. For example:
for a 10 element array indexes are 0-9. 10 is outside the boundaries of the array.
for (var i = (stringLength - 1); i >= 0; i--){
reversedString += string.charAt(i);
This is the correct answer.

Related

Difference between two loops

The code below is the correct, working solution to an exercise I had to work out. I am wondering why my solution did not work.
The only difference I had was this line:
for (var i = contacts.length; i > 0; i--) {
Why it did not do the same just reversed direction?
for (var i = 0; i < contacts.length; i++) {
if (contacts[i].firstName == name){
if (contacts[i].hasOwnProperty(prop)){
return contacts[i][prop];
} else{
return "No such property";
}
}
}
return "No such contact";
There are multiple problems in your code.
the first problem is that you start i = contacts.length and as you know there is no element in the array at the array length position
because arrays go from 0 to array.length-1.
the solution for that problem is var i = contacts.length - 1.
the second problem is that i never goes to zero because your stop condition is i > 0
then you never reach the first element of the array.
the solution is changing the stop condition to i >= 0
The two loops have different ranges.
If contacts.length had equalled 4, then i would have taken on these values:
console.log('ascending loop');
for (var i = 0; i < 4; i++) {console.log(i);}
console.log('descending loop');
for (var i = 4; i > 0; i--) {console.log(i);}
Array Start with 0.
Length Start with 1.
let say i want the last element from contact array
let contact = ['mo','so','do'];
console.log(contact[length])
It won't show a console. Y ? Because To get a last array.
You always need to -1 from the array.length
On the answer, the for counter go like 0 ... n, and on your for loop, the counter goes like n ... 1.
So, on your code, the index never is 0

JS for Kids Hangman game

I don't know what the [i] in answerArray[i] does/means. If someone could explain what it does it would mean a lot. This code came from the book "JavaScript for kids" and I'm trying to get started with just any kind of coding
var words = [
"money",
"pillow",
"maracas"
];
var word = words[Math.floor(Math.random() * words.length)];
var answerArray = [];
Here
for (var i = 0; i < word.length; i++) {
*answerArray[i] = "_";*
}
var remainingLetters = word.length;
while (remainingLetters > 0) {
alert(answerArray.join(" "));
var guess = prompt("Guess a letter, or click cancel to stop playing.");
if (guess === null) {
break;
} else if (guess.length !== 1) {
alert("Please enter a single letter.");
} else {
And here
*for (var j = 0; j < word.length; j++) {
if (word[j] === guess) {
answerArray[j] = guess;*
remainingLetters--;
}
}
}
}
alert(answerArray.join(" "));
alert("Good job! The answer was " + word);
Here's an example
https://www.w3schools.com/js/tryit.asp?filename=tryjs_loop_for_ex
The letters i or j or litterally anything put in that slot when you write for (i = 0; i < 5; i++) represents the current itteration. This is thing called a for loop and you should definitely get to know it if you are just getting started with javascript.
The letter, in short, represents the current itteration of the loop.
for (i = 0; i < 5; i++) { }
What this loop is saying is first i = 0. the variable "i" is 0. Then it says i < 5. This part is the "test". If the test passes, the loop with run again. Then it says i++. This is something that happens after the loop has been run. In this example it increases i with 1.
What happens inside { } will occure 5 times, and the letter i will increase in value, representing the "current loop".
In the demo i linked, you see that the sentence "The number is x" appears in increasing order, starting with 0.
The loop essentially means "While i is less than 5, do this" and the i increases in value each loop and the test inside () is rerun.
In arrays, each slot is represented by a number. MyArray[1] refers to the second item in the array.
If you have an array like this var myArray = ["fi", "fa", "fo"] then you can write console.log[2] to print the third item.
Lets combine this knowledge like this!
var myArray = ["fi", "fa", "fo"];
for (i = 0; i < 3; i++) {
alert(myArray[i]);
}
The for-loop is run 3 times, and each time it is run, i has a bigger value. This lets us refer to every item in the array. A better loop to write would be for(var i = 0; i < myArray.length; i++. This makes us compare i to the size of your array, so the array can be any size it wants to be
1 > the answer array initially empty array=[];
2 > then words[Math.floor(Math.random() * words.length)] this will return a
random string from words array .
3 > then the for loop is just counting the number of characters present in the
selected word and that same time number of _ is inserted in answers Array
4 > then this will just joining all the underscores and make a single string (with in the spaces).
eg -> word "pillow" is selected
then answers Array= ['_','_','_','_','_','_']
then answerArray= "_ _ _ _ _ _" ( Join with spaces).
Thanks.

Understanding get second lowest and second highest value in array

Good day fellow Stack-ers,
I must ask your pardon if this question has been asked before or if it seems elementary (I am only a Javascript novice).
I have been doing w3c js challenges lately: Write a JavaScript function which will take an array of numbers stored and find the second lowest and second greatest numbers.
Here is my answer:
var array = [3,8,5,6,5,7,1,9];
var outputArray = [];
function arrayTrim() {
var sortedArray = array.sort();
outputArray.push(sortedArray[1],array[array.length-2]);
return outputArray;
}
arrayTrim();
and here is the answer that they have provided:
function Second_Greatest_Lowest(arr_num) {
arr_num.sort(function(x,y) {
return x-y;
});
var uniqa = [arr_num[0]];
var result = [];
for(var j=1; j < arr_num.length; j++) {
if(arr_num[j-1] !== arr_num[j]) {
uniqa.push(arr_num[j]);
}
}
result.push(uniqa[1],uniqa[uniqa.length-2]);
return result.join(',');
}
alert(Second_Greatest_Lowest([1,2,3,4,5]));
I know that the for loop runs through until the length of the input, but I don't understand the if statement nested within the for loop. It seems like a long way around to the solution.
Thank you!
Your answer does not perform correct for input such as f.e. [3,8,5,6,5,7,1,1,9]. Your proposed solution returns 1 as the second lowest number here – whereas it should actually be 3.
The solution suggested by the site takes that into account – that is what the if inside the loop is for, it checks if the current number is the same as the previous one. If that’s the case, it gets ignored. That way, every number will occur once, and that in turn allows to blindly pick the second element out of that sorted array and actually have it be the second lowest number.
It seems like a long way around to the solution
You took a short cut, that does not handle all edge cases correctly ;-)
The loop in question:
for(var j=1; j < arr_num.length; j++) {
if(arr_num[j-1] !== arr_num[j]) {
uniqa.push(arr_num[j]);
}
}
Provides some clue as to what it's doing by using a (reasonably) descriptive variable name: uniqa - or "unique array". The if statement is checking that the current element is not the same as the previous element - having sorted the array initially this works to give you a unique array - by only filling a new array if the element is indeed unique.
Thereafter the logic is the same as yours.
import java.util.Arrays;
public class BubbleWithMax_N_Min
{
public static void main(String[] agrs)
{
int temp;
int[] array = new int[5];
array[0] = 3;
array[1] = 99;
array[2] = 55;
array[3] = 2;
array[4] = 1;
System.out.println("the given array is:" + Arrays.toString(array));
for (int i = 0; i < array.length; i++)
{
System.out.println(array[i] + "");
}
for (int i = 0; i < array.length; i++)
{
for (int j = 1; j < array.length - i; j++)
{
if (array[j - 1] > array[j])
{
temp = array[j - 1];
array[j - 1] = array[j];
array[j] = temp;
}
}
}
System.out.println(" 2nd Min and 2nd Highest:");
for (int i = 0; i < 1; i++)
{
System.out.println(array[i+1]);
}
for (int i = 0; i < 1; i++)
{
int a= array.length-2;
System.out.println(array[a]);
}
}
}

Removing Duplicate Items in an Array without Regex or filter

I have been stumped on this problem for a few hours now and am making no progress. I feel like this should be simple. I am trying to Remove duplicate characters in a String without using methods such as Filter or a Reg ex.
Here is my current code:
var duplicate = function(string) {
var newString = string.split("");
var finalArrayWithNoDuplicates = []
for (var i = 0; i < newString.length; i++){
for (var=0; j < newString.length; i++){
while(newString[i])
if (newString[i] !== newString[j]){
}
}
}
return finalArrayWithNoDuplicates.join("");
};
I am able to filter one letter at a time but as I progress down the chain in the while statement I am adding letters that were filtered out originally.
All of the algorithm tutorials for this algorithm are in Java that I have been finding. Is there a way to do this with only using a a for and while loops?
There are several things wrong with the proposed code:
It has serious errors (the inner loop is written all wrong)
You don't need to involve arrays at all, strings will do just fine
The "if char !== other char" check will never provide enough information to act on
Here's an alternative version using for loops and the same basic idea:
function deduplicate(str) {
var result = "";
for (var i = 0; i < str.length; ++i) {
var found = false;
for (var j = 0; j < i; ++j) {
if (str[i] == str[j]) {
found = true;
break;
}
}
if (!found) result += str[i];
}
return result;
}
Each character str[i] in the input string is compared to all characters str[j] that precede it (there is no point in comparing to characters that follow it because we are going to process those when their turn comes up anyway). If the character is not equal to any of those that precede it then we know it's the first of its kind to appear and include it in the result.
Note that this algorithm has O(n²) performance, which is very poor compared to other possible approaches. Its main selling point is that it is straightforward and that everything happens "in front of your eyes".
Here is a slightly modified version of your function that uses an object to keep track of which letters have already been encountered:
var duplicate = function(string) {
var finalArrayWithNoDuplicates = [];
var seen = {};
for (var i = 0; i < string.length; i++) {
if (!seen[string[i]]) {
finalArrayWithNoDuplicates.push(string[i]);
seen[string[i]] = 1;
}
}
return finalArrayWithNoDuplicates.join("");
};
No need for two nested for-loops
No need for "while" loop as well
in the following line of code there are two errors: for (var=0; j < newString.length; i++){ first one is var=0 (compilation error) and second is theat you increment i instead of j
It can be done by adding only unique elements (that don't appear twice) to finalArrayWithNoDuplicates
as follows:
var duplicate = function(newString) {
var finalArrayWithNoDuplicates = []
var x = 0;
for (var i = 0; i < newString.length; i++){
// if the char appears in another index
// or if it's already in the result - don't add it
if (newString.lastIndexOf(newString[i]) !== i || finalArrayWithNoDuplicates.indexOf(newString[i]) > -1){
continue;
}
else{
finalArrayWithNoDuplicates[x++] = newString[i];
}
}
return finalArrayWithNoDuplicates.join("");
};
var arr = [1,2,3,4,5,4,5,6,7];
alert(duplicate(arr));
OUTPUT:
1234567

Comparing array to var during iteration(cont.)

So here's my problem.. Might just be tired but, I want counter to ++ only if number has not occurred in array.
Meaning during the 4 iterations, counter should ++ only on iteration 1,3,4
var array = [], number, temp = [4,2,5,9], counter = 0;
for(var i = 0; i <= 3; i += 1) {
array.push(i);
number = temp[i];
}
document.write(counter);
But I'm drawing a blank here... Help?
(No this isn't homework)
if (array.indexOf(number) < 0)
counter++;
unfortunately JS doesn't have an "in_array", but it's pretty straight forward:
#MikeSamuel pointed out you can use indexOf (thanks Mike). So with that being said:
var array = [], number, temp = [4,2,5,9], counter = 0;
for(var i = 0; i <= 3; i += 1) {
array.push(i);
number = temp[i];
if (temp.indexOf(i)==-1) // much simpler, assuming you're checking if i is in temp.
counter++; // increase counter if it is not.
}
document.write(counter);
I'm not sure where you want the logic, so you'll have to figure that out or be more specific. Just know that you need to iterate through the array you're checking and check if the "needle" is in the "haystack" array.
EDIT Had the opposite, just added bool to check for existence.

Categories