Lowest price ever! Learn Generative AI for 48% less!
Get my discount+ 8
Why does "Hello" run 3 times in the first program and why is 1 printed as the output for the second program?
//first program Function.prototype.call = function(count) { var i = 0; while(i++ < count) { this() } console.log("hello"); } function test() { console.log("hello"); } test(); test.call(1); //second program function func(n) { if(n<=1) { return 1; } else { return func(n-1); } } alert(func(4));
10 Answers
+ 6
test () calls the function and we have first hello on the console.
Now we call test function handle with 1 as argument: (test.call (1)) and:
While loop is run "count" times and in each run it calls "this" (here is test function). Because "count" is 1, while loop calls test function once. So until now we have 2 hellos. After while loop we directly log hello to consol and we get third hello.
+ 6
in the second program, your function reduces the argument passed by one to the base case and returns 1.
+ 4
First program:
First time it runs normally, it is the function. Second time it's called in the while loop, just once. Third time, it's called at the end of the call method, it has nothing to do with the test function.
Second program:
I think you confused this function with a factorial function. But the last line would be:
return n * func(n - 1);
This function is kind of pointless, it just goes down to one if you input an integer and returns it
+ 4
First one:
1. function is called
2. Once called in the loop
3. printed hello at the end of the call methid
Second:
It just goes down to one.
return func(4 - 1) -> func(3 - 1) -> func(2 - 1) -> func(1) -> 1
+ 2
Airree, I'm afraid to say I don't understand any of your explanation 🤦♂️
+ 2
I already explained you twice, I can't really help you after that
+ 1
Airree I got the explanation for the second program but for first, I still do not understand what is going on
0
pintu kumar
0
pintu kumar