Forloop count isn't defined in JS? - javascript

Tried doing this for a class assignment but for whatever reason it is saying the count is not defined. Any suggestions?
var num = [1,2,3,4,5,6,7,8,9,10]
for(var num = 0; count < 11; num++) {
if(num % 3 ===0);
console.log(num);
}

I think you mean to use the num variable instead of count.
for(var num = 0; num < 11; num++) {
You are defining the 'num' variable. Setting it to 0 and then running the 'for' loop, adding 1 to 'num' for each loop until 'num' is no longer < 11.

try this...
var num = [1,2,3,4,5,6,7,8,9,10];
for (var count = 0; count < num.length; count++) {
if (num[count] % 3 == 0)
alert(num[count]);
}

Typically, Javascript for loops will have this format:
for (i = 0; i < 11; i++) {
//i = 0 > starting index
//i < 11 > ending index
//i++ > index increment
}
The reason why you ran into your error is because count is never defined as a variable, whereas the variable 'i' in my example was defined when I set the value of i=0.
Instead of thinking that you are looping through the integers within the num array, think of it like you're looping through the indexes of num. So within every loop, the i variable will represent which index of the array you're currently focusing on.
Helpful tips:
make sure you utilize num.length to get the ending index of your for loop
Use indexes to reference integers in an array: num[0] == 1,
num[1] == 2, num[2] == 3 ...

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

Print Prime Numbers (2,3,5,7)

I found the code for solving this problem, but I cannot figure out the logic of the solution.
let n = 10;
nextPrime:
for (let i = 2; i <= n; i++) {
for (let j = 2; j < i; j++) {
if (i % j == 0) continue nextPrime;
}
alert( i );
}
I can't understand how the second for works, if it has an increment like the first, then the result should have been all numbers from 2 to 10, since the beginning of both for is the same number (2) ..
Can you please explain each iteration, for example why 4 is not displayed?
It’s using label to break the inner loop when it finds number is not prime . Outer loop is iterating the number and inner loop checks if it’s divisible between 2 to number.
Label break
the continue nextPrime used for just continue in the loop to the next iteration without finish all the code inside the loop.
like:
data:
for (let i = 1; i <= 3; i++) {
if(i === 2)
continue data;
console.log(i)
}
here when I get to I equal to 2 the code continue to the next number without continue to the rest of the code

How to get value of a variable?

I am trying to figure out a script that adds 1 each time it runs to a variable, then console logs the total amount of times.
for (let i = 1; i <= limitFizzBuzz; i++) {
// Count the FizzBuzzes
let amountOfFizzBuzzes;
amountOfFizzBuzzes = amountOfFizzBuzzes += 1;
console.log(amountOfFizzBuzzes);
}
When I tried to run this in a loop, I get:
What am I doing wrong here?
First, a simpler version of the first problem:
let num;
num += 1;
console.log(num);
num += 1 is a correct statement that adds 1 to the value of num and stores the result back in num.
console.log(num); is a correct statement that writes the value of num to the console.
But let num; doesn’t give a starting value for num. When a variable isn’t initialized to a value in JavaScript, it gets the value undefined. Doing math on undefined as if it were a number results in NaN, which is what you see.
So, a fixed version of the simpler code gives an initial value to num, like zero:
let num = 0;
num += 1;
console.log(num);
The next issue is scope. If you declare a variable inside the loop, it’s a new variable each time around. Instead, you want to use the same variable for every iteration, and have it keep its value, so move the declaration outside:
let amountOfFizzBuzzes = 0;
for (let i = 1; i <= limitFizzBuzz; i++) {
amountOfFizzBuzzes += 1;
console.log(amountOfFizzBuzzes);
}
first you Define a var let amountOfFizzBuzzes; inside a loop so that should be outside the loop
second if you need to increment a number this is a right way to do it
let amountOfFizzBuzzes=0;
for (let i = 1; i <=limitFizzBuzz; i++) {
// Count the FizzBuzzes
amountOfFizzBuzzes+= 1;
console.log(amountOfFizzBuzzes);
}
.
.
//....
limitFizzBuzz = 5;
//if you want to start from zero & increment it X times
let amountOfFizzBuzzes = 0;
for (let i = 1; i <= limitFizzBuzz; i++) {
// Count the FizzBuzzes
amountOfFizzBuzzes += 1;
console.log(amountOfFizzBuzzes);
}
#Morrison is absolutely correct.
Just initialize your amountOfFizzBuzzes above the for loop.
let amountOfFizzBuzzes =0;
for (let i = 1; i <= 10; i++) {
// Count the FizzBuzzes
amountOfFizzBuzzes++;
//amountOfFizzBuzzes +=1;
console.log(amountOfFizzBuzzes);
}

Understanding a JavaScript For Loop

If I have variables and a for loop with a condition set-up like this:
var scores = [23, 53, 85];
var arrayLength = scores.length;
var i;
for(i = 0; i < arrayLength; i++)
Does the i refer to the scores array indexed position of 0, or is i just the counter number, which is set to 0?
I'm kinda confused on understanding what's happening.
Any help is appreciated!
Here you can see it in action:
var scores = [23, 53, 85];
var arrayLength = scores.length;
var i;
for(i = 0; i < arrayLength; i++) {
console.log('i = ' + i + ', scores[i] = ' + scores[i]);
}
console.log('End of for loop: i = ' + i);
One important thing to understand is that i will be incremented until the condition i < arrayLength is not met anymore. So it will reach the value 3 but the for loop will end immediately. Therefore, the code inside the loop is not executed for i = 3.
i is just a counter number which is initially set to 0 and increments up to arrayLength (3 in this case)
i just refers to a number that (in this case) counts up from 0 until arrayLength. You have to explicitly access the values in the array at each i by using scores[i], after which you can modify/use the value in any way you see fit.
i is the counter number.
A for loop works like so:
For each value of array length, use i as a counter variable
each time through the loop increment the variable of i when you are done (i++)
you could expand it like so...
for(i = 0; i < arrayLength; i++)
{
console.log('position ' + i + ' is ' + scores[i]);
}//now that I am done, increment i and go through again until i is no longer less than array length
Right so you have the set the i as a variable by initially going
var i;
Within the for statement you have set the i variable to 0.
for(i = 0; i < arrayLength; i++){
}
Then the for statement is saying if i is less than the array length run the for statement. Each time the for statement runs you are adding 1 to i because of i++;
Every time the for statement will check to see if i is less than the arrayLength if it isnt it will exit out of the for.
So for this instance the for each would run 3 times because the array length is 3.
Make sure you have open and closing brackets on the for statement
So your for statement should look like this.
for(i = 0; i < arrayLength; i++){
}

the if statement condition logic

I am in need of help in this script. I am trying to write a program, where each array element is assign to a "point". I concated all the arrays and assigned it to a variable. The array runs through an if statement to tally up the score.
For this instance, I am trying to get a total of 6. However, when I run the program I am getting "2" rather than "6" in the console log. How should I write my if condition to get the result of 6?
var zero = [1,2,3,5,7]; // 0
var one = [0,4,6,9]; // 1
var two = 8; //2
function calculate(){
var NUMBERS = zero.concat(one,two);
var TOTAL = 0; // 6
for(var i = 0; i < NUMBERS.length; i++){
if(NUMBERS[i] === one[i]){
TOTAL += 1;
}else if(NUMBERS[i] == two){
TOTAL +=2;
}else {
TOTAL += 0;
}
}
console.log(TOTAL);
}
calculate();
This will only match if the value in NUMBERS[i] is in the same position of the array one.
if(NUMBERS[i] === one[i]){
Change it to this:
if (one.indexOf(NUMBERS[i]) !== -1){
to test for the presence of NUMBERS[i] in one.
Also, you have a four in both the zero and one array.
As #TJCrowder mentioned - the answer is seven.
You can omit:
TOTAL += 0
Adding zero doesn't change anything.

Categories