Is this JavaScript code wrong? - javascript

In this JavaScript lesson on Codecademy it is required to write a do/while loop, I have written this, and it passes
var getToDaChoppa = function(b){
var a = b;
do{
console.log("Dunno!");
} while (a < b);
};
getToDaChoppa(25);
But when looking closely at my code, I think that I may have done it completely wrong since a has no defined value?
Or since the variable of b is local inside the function, it does not affect the b argument which is passed a value of 25?
Many thanks in advance.

It simply does only one iteration, because when the do while loop starts, the condition is not satisfied because a and b are equals. So
var getToDaChoppa = function(b){
var a = b;
do{
console.log("Dunno!");
} while (a < b); //25 < 25, exit
};
getToDaChoppa(25);
If you want to try a do while loop try with some trick like
var getToDaChoppa = function(b){
var a = 10; //or whatever minor than b
do{
console.log("Dunno!");
a++; //when it reaches 25 or whatever value you set it breaks the loop
} while (a < b);
};
This is just an example to let you figure out how do while works

The code's fine, the logic's wrong. You are assigning a the value of b, so they'll be always equal.

You are assigning the value of b to a with the statement var a = b;
The loop will run once since you are using a do while loop.
The code is not wrong, it is designed to illustrate that the condition is evaluated after the first iteration of the loop.
http://jsfiddle.net/puleos/QXC9z/

Is this JavaScript code wrong?
depends on what problem you wanted to solve.
It looks pretty useless to me since the body of the loop will always be executed once.
while (a < b);will always return false because of var a = b; and a is not modified in the loop.

I think what you're after is:
var getToDaChoppa = function(b){
var a = 0;
do{
console.log("Dunno!");
a++;
} while (a < b);
};
As mentioned by other posters, if a = b the loop will only run once. This version should run the expected number of times (if that truly is what's expected).

Since the question says "Your loop should print a string of your choice to the editor one time", I think this is correct. Your code will print the string "Dunno!" exactly one time.
However the a and b variables and the do..while loop might as well not exist at all, they are only adding unnecessary complexity to the code which could be simplified to one line (the console.log() call).

Related

for loop calculation syntax within a function is not correct

what is the actual syntax for the for loop?
what I want to do is to calculate 2 number variables inside a function using a for a loop.
I am going over and over the internet and I cannot find anything that can help me specifically for this task I was given to do.
I am not looking for the answers, just for a guideline or a hint.
or just give me the syntax and I will try my best to adjust it to my needs.
just so you have a better understanding of the task, here it is.
Features
Instead of hardcoding Y (the result of the Fibonacci of X), calculate it with a for loop
The calculation should be wrapped in a function, that gets X as an argument, and returns Y
After the function, you should call the function, and assign the returned value in your HTML to present to the user
btw, i know that i did not put the innerHTML correcly, and also i did not do the syntax right, this is actually what i am asking here.
thank you!!
i have tried this:
var answer = document.getElementsByClassName("paragraph")
function calc (x){
for (let a = 2; a <= x; a++){
answer = document.textContent("this is a pr")
}
return calc
}
calc(2)
You should avoid to use classname, instead use .querySelectorAll
You don't need to specify how many answer exists if your calc() is just 2.
let answer = document.querySelectorAll(".paragraph");
function calc(x) {
for (let a = 0; a <= x; a++) {
answer[a].innerText = "this is a pr";
}
}
calc(2);
<p class="paragraph">A</p>
<p class="paragraph">B</p>
<p class="paragraph">C</p>
<p class="paragraph">D</p>
<p class="paragraph">E</p>
I don't know if this is what you're searching for but it's this is the standard for loop function to achieve these types of result.
function calc(x){
let sum = 0;
for (let a=0; a<x; a++){
sum+=a;
}
return sum;
}
console.log(calc(5));
The Syntax of the loop in your code is correct, the thing is that you cannot return your function inside itself without calling it as you have done in your code.
'return calc' is wrong. You should use 'return calc(argument-Variable or value)' as you have a parameter passed in your function, but this should only be used if you are writing a code of recursion. If not you should return a variable.
Refer to the code below for further clarifications

Difference between p++ and ++p when using that in a for loop Javascript

This could be a very naive dumb question, but what is the difference in the output of the following 2 condition:
for (var p=0; p<3; p++) {console.log(p)}
//outputs:
0
1
2
for (var p=0; p<3; ++p) {console.log(p)}
//outputs:
0
1
2
'p' result into same output regardless whether I increment the value first and then print it or vice vera. also I do understand the diff between (p++) and (++p), but in this case I'm unable to understand whether at this point in looping will it make it any difference if I were I do either of 2 or if it does make difference how would that impact my program.
Can someone please explain.
Thank
If you dont use the values, after using pre- and post-fix, there is absolutely no difference at all. (exept from performance)
Doing something like this would behave differently, as you can see:
var a = 0;
var b = 0;
var arr = [0,1,2];
console.log(arr[++b]);
console.log(arr[b++]);
console.log(arr[b]);
In this case there is no difference whatsoever as you are not using the value of the expression.
Since you're not assigning the expression to anything, there's no difference apart from a slight performance gain in the pre-incrementer (because a temporary variable is created in order to store the multiple values of p with the post-incrementer). JSBEN.CH.
Just so you know the difference between them:
let var1 = 3;
let var2 = 4;
console.log(var1++); //Outputs the value of var1, then increments it
console.log(++var2); //Increments the value of var2, then outputs it
The += syntax is actually better in this case, because it is easier to read, and it is just a compaction of p = p + 1 - literally no difference, performance-wise or otherwise. This means it's actually faster.
If you put the two plus in front or after the variable/number only makes a different for evaluating it.
Because it is only inportant that the counter is incremented after leaving the block. If this is done before or after doesnt matter. At the end of the call the number is incremented equally.
++p first it will count +1 and then return the result
p++ it will return the value and then add +1
p value will be different at the end of each turn in those 2 cases.
In your example there is no difference.
However if you use the increment ++ or decrement -- operators inside a function the positioning is significant. To quote the article
JavaScript Increment ++ and Decrement --
If the operand is after the variable console.log displays a then it is incremented
let a = 1;
console.log(a++); // 1
console.log(a); // 2
If the operand is before the variable a it is incremented then console.log displays it
let a = 1;
console.log(++a); // 2
console.log(a); // 2
Several other languages such as C and C++ have the same behaviour.
However these operators need to be used with care. See the following stackoverflow answer (albeit it refers to JavaScript, but also applies to C etc)
Why avoid increment (“++”) and decrement (“--”) operators in JavaScript?
In this case there is no difference in pre and post increment.
However in some cases like this can be significant:
here n and i are first evaluated and then incremented
var n=0
var i
for(i=0;n<5;n=i++){}
after the loop n and i look like this: n=5, i=6
here n and i are evaluated first, but i is incremented before entering the cycle
var n=0
var i
for(i=0;n<5;n=++i){}
after the loop n and i look like this: n=5, i=5

Heap's Algorithm Permutation JavaScript and Recursions' Stack?

I have an assignment to count repeated strings base on a Heap's Algorithm Permutation.The first thing I want to do is output the swapped strings, I found this code from jake's answer Can someone please help me understand recursion within this code in a loop? The output of this function are swapped strings.
function permAlone(string) {
var arr = string.split(''), // Turns the input string into a letter array.
permutations = []; // results
function swap(a, b) {
debugger; // This function will simply swap positions a and b inside the input array.
var tmp = arr[a];
arr[a] = arr[b];
arr[b] = tmp;
}
function gen(n) {
debugger;
if (n === 1) {
var x =arr.join('');
permutations.push(x);
} else {
for (var i = 0; i != n; i++) { // how does this loop executes within the call stack?
gen(n - 1);
debugger;
swap(n % 2 ? 0 : i, n - 1); // i don't understand this part. i understand the swap function, but I don't get how indexes are swapped here
}
}
}
gen(arr.length);
return permutations;
}
permAlone('xyz'); // output -> ["xyz","yxz","zxy","xzy","yzx","zyx"]
I have been experimenting it on debugger but still can't get what's happening.
I'm not sure what you mean by
understand recursion within this code in a loop
If you mean you want to see the algorithm in a loop form rather than a recursion version you can see them one by side in pseudocode in the wikipedia page here.
For your questions within the code:
how does this loop executes within the call stack?
You are right to refer to the call stack, and this is a general question regarding recursion. If you don't understand how recursion works with the stack you can refer to this really nice and simple video that demonstrates recursive calls using factorial calculation in java (start around min 4:00).
The line you look at is no different than any other line in the recursive function. We start by defining i and assigning the value 0 to it. We continue to check if it satisfies the condition of the for loop. If it does we step into the loop and execute the first line inside the loop which is the recursive call. Inside the recursive call we have a new stack frame which has no knowledge of the i variable we defined before executing the recursive call, because it is a local variable. So when we get to the loop in the new call we define a new variable i, assigning it 0 at first and incrementing it as the loop repeats in this stack frame/call instance. When this call finishes we delete the stack frame and resume to the previous stack frame (the one we started with) where i=0 still, and we continue to the next line.
All the calls have access to the arr and permutations variables since the function is defined in the same scope as the variables (inside the function permAlone) so within each call - no matter what the stack frame we are in, the changes made to those are made to the same instances. That's why every push done to permutations adds to the existing results and will be there when the function returns the variable at the end.
i don't understand this part. i understand the swap function, but I don't get how indexes are swapped here
Indexes are not swapped here. It is merely a call for the swap function with the correct indices.
swap(n % 2 ? 0 : i, n - 1);
is just
swap(a, b);
with
a = n% 2 ? 0 : i;
b = n - 1;
If the a part is what confuses you, then this is a use of the ternary operator for conditional value. That is, it's symbols used to form an expression that is evaluated differently according to the circumstances. The use is by
<<i>boolean epression</i>> ? <<i>value-if-true</i>> : <<i>value-if-false</i>>
to evaluate the above, first <boolean expression> is evaluated. If it's value it true then the whole expression is evaluated as <value-if-true>. Otherwise, the whole expression is evaluated as <value-if-false>.
In the code itself, for a, n % 2 is the boolean expression - js divides n by 2 and takes the remainder. The remainder is either 1 or 0. js implicitly converts those to true and false respectively. So if n is odd we get
a = 0
and if it's even we get
a = i
as the algorithm requires.

Setting Javascript Function Parameters inside the function parenthesis

This is so simple I forgot how to do it. I've always passed variables to a function hence it's param's were pre-set, now I need to set the param's when declaring the function, but don't remember the setup.
I'm looking for the working version of this:
function(a,b=4){return a-b;}
Where the b param' of the function is set when the function is declared.
If I remember rightly it's like setting a default for b if the function has no second argument:
function(a,b){b=b || 4; return a-b;}
EDIT
Thanks for all your help but it seems it's impossible in js without ECMAScript 6. Your answers are getting a bit off topic though... I really needed the values set in the paren's.
To keep it on topic... my initial problem is sending parameters to a setTimeout function. Ok so I have a <div> with a .gif background, when clicked it's background changes, this second animation runs for exactly 8 seconds and then the background changes again to a final .gif. so it's a 3 stage animation, simple... thing is the 8sec gap, I figured a setTimeout would work but I can't pass any param's to the 'sto' function to reference said <div>.
If you know of any timer events that can help then be my guest, this is as far as I've got. My original code is below... it fails at function(p = cha).
for(var i = 0; i < 5; i++){
var cha = document.createElement('div');
$(cha).css('background','url(img/stand.gif)');
cha.addEventListener('click',function(){
$(cha).css('background','url(img/walk.gif)');
setTimeout(function(p = cha){
$(p).css('background','url(img/walk.gif)');
},8000);
});
}
function(a,b){b=b || 4; return a-b;}
This is the typical way to default params in ES5. However I would advise changing this to check b's typs a little more strictly, because 0 will be considered a falsey value by the || operator
function(a,b){
b = typeof b === 'undefined' ? 4 : b;
return a-b;
}

Weird looking Javascript for loop

I have never seen a JavaScript loop such as this for( ; i-- ; ), used in the code:
uid: function (len) {
var str = '';
var src = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var src_len = src.length;
var i = len;
for (; i--;) {
str += src.charAt(this.ran_no(0, src_len - 1));
}
return str;
}
I understand the behavior, but I would like it if somebody could share some insights about this type of for loop.
This is a syntax of the for-loop construction:
for ([initialization]; [condition]; [final-expression])
statement
In your case for (; i--;) {:
no variables are initialized, because var i = len; inintialized earlier, so it's not needed.
condition part will be truthy until i becomes 0 then loop will terminate. i-- is executed on before each iteration, and due to -- operator it will eventually become 0, so it's falsy, and loop will stop.
since i is decremented in condition part of the loop, final-expression is not needed too. Another way to put it: since i is not used inside the loop, it does not matter whether we decrement it before each loop iteration or after each loop iteration.
That being said, it's better to avoid writing loops like above, as it's pretty confusing and hard to read. Prefer traditional for-loops notation.
From MDN - for - Optional for expressions:
All three expressions in the head of the for loop are optional.
You don't have to specify all three expressions in for loops. For example, for (;;) is a common wa of writing infinite loop.
In your case, while(i--) would have done the same, there is no good reason to write for (; i--;).
I'd also note that for(var i=len;i>=0;i--) is more robust - it protects you from the case len is negative.
This could be rewritten to
uid: function (len) {
var str = '';
var src = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var src_len = src.length;
var i = len;
while (i >= 0) {
str += src.charAt(this.ran_no(0, src_len - 1));
i = i - 1;
}
return str;
}
The for statement creates a loop that consists of three optional
expressions.
Javascript consider 0 == false that's why in the case you presented the loop will run until the i variable became zero. It will loop as many times as the src string size.
Note: i-- uses the variable value then decrements it. Take a look at the following situation:
for(;i--;) { // i = length in the condition
// i === length - 1 here. It will not overflow the array
}
for(;i--;) { // i = 1
// i === 0 here. It will be the last loop
}
for(;i--;) { // i == 0 == false
// Not executed
}
There is nothing wrong.
for(`INIT`;`TEST`;`ACTION`)
{
`WORK`;
}
The INIT (initialization) can be done outside the loop.
var i=0;
for(;i<=100;i++)
//do something
The TEST part yield a result that is either true or false. Now in this case value of i is tested. Until it becomes zero this works.
The ACTION part is generally used to change the loop variable. But you can leave it also or probably add it to the TEST section like it is done here.
Look this examples are going to clear your idea
var i=0;
for( i++; i++; i+=j); //No body
var i=0;
for(;;); //an infinite loop
var i;
for(i=-4;i;i++);//
Even sometimes WORK is placed in ACTION.
Example:
factorial of x
for(var i=1,ans=1;i<=x;ans=ans*(i++));
Which can be written this way also-
var ans=1;
for(var i=1;i<=x;i++)
ans=ans*i;
NOTE: You can write whichever way you want. It doesn't matter as long as you have written the code properly. Get used to this kind of form you will see them a lot.
Though, it is better to write sometimes in compact form , but remember you should keep the readability.
That's just for loop. Before the first semicolon the variable used in the loop is usually declared. But in this case the variable, the variable used in the loop is declared earlier:
var i = len;
^^^
for (; i--;) {...
So there is no need to redeclare.
After the first semicolon, there is a condition for the loop to run (i.e. i<6, i>3, etc). If condition returns false, or 0, the loop is exited. In this case, the loop will be broken out when i is 0. It happens eventually, because -- after i decrements it, and therefore there is no need for the expression, which is the place after the second semicolon is reserved for.
The first parameter of the for loop has already been defined, so the initial comma is there to delimit it's place in the parameter list.

Categories