Why does "Hello" run 3 times in the first program and why is 1 printed as the output for the second program? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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));

8th Jul 2019, 5:31 AM
eMBee
eMBee - avatar
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.
8th Jul 2019, 6:21 AM
Qasem
+ 6
in the second program, your function reduces the argument passed by one to the base case and returns 1.
8th Jul 2019, 5:44 AM
Boboev Ahmadjon Safaralievich
Boboev Ahmadjon Safaralievich - avatar
+ 5
Oh, great, I get you Qasem, also thanks for the effort Airree, I really appreciate
8th Jul 2019, 6:32 AM
eMBee
eMBee - avatar
+ 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
8th Jul 2019, 5:36 AM
Airree
Airree - avatar
+ 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
8th Jul 2019, 5:52 AM
Airree
Airree - avatar
+ 2
Airree, I'm afraid to say I don't understand any of your explanation 🤦‍♂️
8th Jul 2019, 5:49 AM
eMBee
eMBee - avatar
+ 2
I already explained you twice, I can't really help you after that
8th Jul 2019, 6:02 AM
Airree
Airree - avatar
+ 1
Airree I got the explanation for the second program but for first, I still do not understand what is going on
8th Jul 2019, 6:00 AM
eMBee
eMBee - avatar
0
pintu kumar
19th Jul 2019, 4:54 PM
Pintu Kumar
Pintu Kumar - avatar
0
pintu kumar
19th Jul 2019, 4:54 PM
Pintu Kumar
Pintu Kumar - avatar