How to get value of a variable? - javascript

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);
}

Related

why my code doesn't work when I am trying to concatenate a function's return value with a string?

So, in this code I have a string of 0's and 1's and the length of the string is 32, which will be split in 6 equal parts but the last part will have the length of 2 so I will add (4) 0's after that which will make its length 6. So I wrote a function that will add the remaining 0's which is padding(num).
And that function will be invoked in side the slicing(str) function.
But the code breaks when I try to do execute.
Any help?
Thanks.
// This code works.
function padding0s(num) {
let s = "";
for (i = 0; i < 6 - num; i++) {
s += "0";
}
return s;
}
function slicing(str) {
let k = 6;
let res = [];
let temp1 = 0;
let f = padding0s(2);
for (i = 0; i < str.length; ) {
res.push(str.slice(i, k));
i += 6;
k += 6;
if (res[temp1].length !== 6) {
res[temp1] += f;
}
temp1++;
}
console.log(res);
}
slicing("01000011010011110100010001000101");
// But this does not..
function padding0s(num) {
let s = "";
for (i = 0; i < 6 - num; i++) {
s += "0";
}
return s;
}
function slicing(str) {
let k = 6;
let res = [];
let temp1 = 0;
for (i = 0; i < str.length; ) {
res.push(str.slice(i, k));
i += 6;
k += 6;
if (res[temp1].length !== 6) {
let f = padding0s(res[temp1].length);
res[temp1] += f;
}
temp1++;
}
console.log(res);
}
slicing("01000011010011110100010001000101");
Always define variables before using them
Not doing so can result in undefined behaviour, which is exactly what is happening in your second case. Here is how:
for (i = 0; i < str.length; ) {...}
// ^ Assignment to undefined variable i
In the above for-loop, by using i before you define it, you are declaring it as a global variable. But so far, so good, as it doesn't matter, if not for this second problem. The real problem is the call to padding0s() in your loop. Let's look at padding0s:
function padding0s(num) {
...
for (i = 0; i < 6 - num; i++) {
s += "0";
}
}
This is another loop using i without defining it. But since i was already defined as a global variable in the parent loop, this loop will be setting its value. So in short, the value of i is always equal to 6 - num in the parent loop. Since your exit condition is i < str.length, with a string of length 32 the loop will run forever.
You can get around this in many ways, one of which you've already posted. The other way would be to use let i or var i instead of i in the parent loop. Even better is to write something like this (but beware that padEnd may not work on old browsers):
function slicing(str) {
return str.match(/.{1,6}/g).map((item) => {
return item.padEnd(6, "0");
});
}
console.log(slicing("01000011010011110100010001000101"));

JavaScript neglecting the else statement

I created a function which takes in two values..
Both are numbers represented by n & p. What the function does is that it gets the number n and splits it up then squares it to the value of p and sums them in an increasing order like this: n^p + n^(p+1) + n^(p+2) + ...
Here is the function
function digPow(n, p) {
// ...
let num = n.toString();
let pow = p;
let arrn = [];
let arrp = [];
for (let i = 0; i < num.length; i++) {
arrn.push(JSON.parse(num[i]));
}
let index = arrn.join('');
let sindex = index.split('');
for (let j = 0; j < sindex.length; j++) {
let power = p + j;
let indexs = sindex[j];
let Mathpow = Math.pow(indexs, power);
arrp.push(Mathpow);
}
let total = 0;
for (let m in arrp) {
total += arrp[m]
}
let secondVal = total / n;
let totals = total / secondVal;
let mx = [-1]
if (totals.length == n.length) {
return secondVal
} else {
return -1
}
}
Now i created variables and arrays to store up the values and then the if part is my problem.. The if/else statement is meant to let the program check if a particular variable totals is equal to n which is the input.. if true it should return a variable secondVal and if not it should return -1..
So far its only returning secondVal and i'snt returning -1 in cases where it should like:
digPow(92, 1) instead it returns 0.14130434782608695
What do i do?
totals and n are both numbers. They don't have a .length property, so both totals.length and n.length evaluate to undefined. Thus, they are equal to each other.
There are plenty of other weird things going on in your code, too. I'd recommend finding a good JavaScript tutorial and working through it to get a better feel for how the language (and programming in general) works.
Let's start by stripping out the redundant variables and circular-logic code from your function:
function digPow(n, p) {
let num = n.toString();
// let pow = p; // this is never used again
// let arrn = []; // not needed, see below
// let arrp = []; // was only used to contain values that are later summed; can instead just sum them in the first place
// this does the same thing as num.split(''), and isn't needed anyway:
//for (let i = 0; i < num.length; i++) {
// arrn.push(JSON.parse(num[i]));
//}
// this is the same as the original 'num' variable
// let index = arrn.join('');
// This could have been num.split(), but isn't needed anyway
// let sindex = index.split('');
let total = 0; // moved this line here from after the loop below:
for (let j = 0; j < num.length; j++) { // use num.length instead of the redundant sindex
let power = p + j;
// The only reason for the sindex array was to get individual characters from the string, which we can do with .charAt().
//let indexs = sindex[j];
let indexs = num.charAt(j);
let Mathpow = Math.pow(indexs, power);
//arrp.push(Mathpow); // No need to collect these in an array
total += Mathpow; // do this instead
}
// No need for this loop, since we can sum the total during the previous loop
// let total = 0;
//for (let m in arrp) {
// total += arrp[m]
//}
let secondVal = total / n;
// let totals = total / secondVal;
// The above is the same thing as total / total / n, which is:
let totals = 1/n;
// This is never used
//let mx = [-1]
// This was totals.length and n.length, which for numbers would always be undefined, so would always return true
if (totals == n) {
return secondVal
} else {
return -1
}
}
So the above reduces to this functionally identical code:
function digPow(n, p) {
let num = n.toString();
let total = 0;
for (let j = 0; j < num.length; j++) {
let power = p + j;
let indexs = num.charAt(j);
let Mathpow = Math.pow(indexs, power);
total += Mathpow;
}
let secondVal = total / n;
let totals = 1 / n;
if (totals == n) {
return secondVal
} else {
return -1
}
}
Now let's talk about the logic. The actual output will always be -1, unless the input is 1, due to what's clearly a logic error in the totals variable: the only case where 1/n == n is true is when n==1.
Setting that aside, and looking only at the secondVal variable, some examples of what it's calculating for a given input would be
digPow(123,1) --> (1^1 + 2^2 + 3^3) / 123 --> 14/123
digPow(321,2) --> (3^2 + 2^3 + 1^4) / 321 --> 21/321
digPow(92, 1) --> (9^1 + 2^2) / 92 --> 13/92
I'm pretty sure from your description that that's not what you intended. I'm not at all sure from your description what you did intend, so can't be much help in correcting the function beyond what I've done here.
What I'd suggest is to sit down and think through your algorithm first; make sure you know what you're trying to build before you start building it. There were some syntax problems with your code, but the real issues are with the logic itself. Your original function shows clear signs of "just keep throwing more lines of code at it until something happens" rather than any planned thinking -- that's how you wind up with stuff like "split a string into an array, then join it back into a string, then split that string into another array". Write pseudocode first: break the problem down into steps, think through those steps for some example inputs and make sure it'll produce the output you're looking for. Only then should you bust out the IDE and start writing javascript.

Forloop count isn't defined in JS?

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 ...

Javascript - for loop iterates only once?

I have a for loop but it gets executed once where it should execute two times.
The $appointments variable holds the returned data from an ajax call. When I console.log($appointments.length) I get two which is correct but the iteration happens only once and I can't figure out why.
for (var i = 0; i < $appointments.length; i+=1) {
var rangeStart_hour = $appointments[i].timerange.substring(0, 2);
var rangeStart_minutes = $appointments[i].timerange.substring(3, 5);
var rangeEnd_hour = $appointments[i].timerange.substring(11, 13);
var rangeEnd_minutes = $appointments[i].timerange.substring(14, 16);
var rangeS = rangeStart_hour + rangeStart_minutes;
var rangeE = rangeEnd_hour + rangeEnd_minutes;
var rangeStart = parseInt(rangeS);
var rangeEnd = parseInt(rangeE);
var range=0;
if(parseInt(rangeStart_hour) == 12){
if(parseInt(rangeStart_minutes) == 0){
range = rangeEnd - 0;
}else{
range = rangeEnd - (parseInt(rangeStart_minutes)+20);
}
}else{
if(parseInt(rangeStart_minutes) == 30 && parseInt(rangeEnd_minutes) == 0){
// if start time 1:30 ,end time 3:00
range = (rangeEnd - (rangeStart + 20)); // 300 - 150 = 150
}else if(parseInt(rangeStart_minutes) == 0 && parseInt(rangeEnd_minutes) == 30){
range = ((rangeEnd+20) - rangeStart);
}else{
range = rangeEnd - rangeStart;
}
}
console.log(range);
for(var i=1; i<(range/50); i++){
$("a[data-time='"+(rangeStart)+"']").addClass('time');
rangeStart += 50;
};
};
This structure seems like a bad idea:
for (var i = 0; i < $appointments.length; i += 1) {
//...
for (var i = 1; i < (range/50); i++){
//...
}
}
You probably want to use different variable names for your nested loop counters.
You reinitialize the variable i in the second for loop, if you change
for(var i=1; i<(range/50); i++){
$("a[data-time='"+(rangeStart)+"']").addClass('time');
rangeStart += 50;
};
to use a different variable, say j it should work fine.
In JavaScript, the scope of variable is function scope. It means that all variable declarations are hoisted to the top of the function.
So, in your case:
for (var i = 0; i < $appointments.length; i += 1) {
...
for (var i = 1; i < (range/50); i++){
...
};
};
equals with
var i; // two variables with the same name are hoisted as the same variable.
for (i = 0; i < $appointments.length; i += 1) {
...
for (i = 1; i < (range/50); i++){
...
};
};
So, at the end of the second loop, "i" will be greater than or equal to range/50. If this value is not less than $appointments.length, the first loop will terminate after the first round.
Important: JavaScript does not have block scope. Variables introduced with a block are scoped to the containing function or script, and the effects of setting them persist beyond the block itself. In other words, block statements do not introduce a scope. Although "standalone" blocks are valid syntax, you do not want to use standalone blocks in JavaScript, because they don't do what you think they do, if you think they do anything like such blocks in C or Java.
In your code the "i" variable used twice, So second time initialized value is Incrementing in first for loop. That's why, Condition failed in first for loop and loop is terminating. Change the variable name in second or first for loop then it will be working as you expected

Javascript Euler Fibonacci for loop

I'm doing the Euler project problem 2 in which the objective is to sum the even numbers of the fibonacci sequence that have a value of less than 4 million. I've searched a bit and I've seen several solutions using a while loop but nothing simple using a for loop. I'm curious why I'm returning zero with the following code:
var array = [];
array[0] = 0;
array[1] = 1;
var total = 0;
for(var i=2;total<=4000000;i++) {
array[i] = array[i-1] + array[i-2];};
for(var x=0;x<array.length;x++){
if(array[x]%2 === 0){
total += array[x]};};
alert(total);
I'm guessing the problem is in my for loop using the total variable. I couldn't get it to work using array[i]<=4000000 either and I'm really curious behind the why here. Anyone know why this is? What can I change in the for loop condition (second statement) to get a correct total here?
First of all there is an infinite loop at first for. Your condition must be array[i-1] < 4000000. After that your second for loop will find the correct result.
Also for the problem, you don't need to store all fibonacci numbers then find sum of even numbers.
You can calculate sum when calculating fibonacci.
var first = 0;
var second = 1;
var sum = 0;
for(var current=first+second; current < 4000000; current = first+second){
if(current%2 === 0){
sum+=current;
}
first = second;
second = current;
}
I fixed it for you.
var i, data = [ 0, 1 ], total = 0;
for (i = 2; i <= 4000000; i++)
{
data[i] = data[i - 1] + data[i - 2];
if (data[i] % 2 === 0)
{
total += data[i];
}
}
alert(total);
I'm not sure what you termination condition should be like, you say have a value of less than 4 million, but this is ambiguous. Maybe it should be total <= 4000000 or data[i] <= 4000000. Your phrasing is not precise enough.
Sorry but for me your code going in a dead loop. first "for" use total as check but it's never incremented. If you want This is a solution for fibonacci sequence based on dinamic programming with memoization tecnic.
var f1 = 1;
var f2 = 1;
for(var i = 2; i < 40000; i++){
console.info(i, f1, f2);
var temp = f1 + f2;
f1 = f2;
f2 = temp;
}
alert(f2);

Categories