Hello everyone. I was playing a bit with functions when I noticed a behavior I don’t understand:
function random(arg){
//return arg divided by two
return arg/2
}
function moreRandom(arg){
//silly function log argument
console.log(arg)
}
function test(c, toDo, arg){
//c = counter, toDo = function, arg=argument => call a function a given number of times
for(let i = 0; i < c; i++){
toDo(arg)
}
}
test(3, moreRandom, 'hello') // hello hello hello
test(3, random, 8) //undefined
Why the first call trough test works and does what it was told to, while the second (which should return a number) doesn’t?
Another test:
function simple_number(){
return 10
}
function test(a, b){
return a * 10 + b
}
//this one works
test(simple_number(), 10) //110
//this one doesn't
let count = 2
let counter;
while(count > 0){
counter += simple_number()
count--
}
counter //=> NaN
Can someone help me out? Please provide some material to be studies as to elucidate the matter. Thank you!
I’m not sure on the first one, but in the second case, you didn’t initialize the counter variable with a number. If you define it with “let counter = 0”, it will return a number.
EDIT found a solution for #1
The first test is using a function that instructs the console to log what is written for each loop. In the second test, when it goes through the loop 3 times, it evaluates toDo(arg) as 4 each time. However, the test function does not actually return any value, so it has nothing to bring back to test(3, random, 8).
Your test function is not returning anything.
You got 3 'hellos’s in your first example because you were using console.log().
Any function without a return will by default return undefined.
I almost didn’t sleep last night, I finally wake up and start writing a function that doesn’t return anything (the loop is unnecessary anyway since return will automatically exit the function (@anon10002461 I didn’t want to print a value, I just used console.log to test the function ) and then I try to add 1 to undefined (thanks @darren-stoll . Good morning from guys, and thanks all for the replies. (For mods: can I keep the thread open for the day, in case I’ll need to ask other things? I’m kinda trying to review things today, hopefully better than how I started :D)
let count = 0
function silly(){
count++
}
function repeat(n, toDo, arg){
while(n > 0){
toDo(arg)
n--
}
}
repeat(3, silly, count) //=> count = 3
How’d I write that does the same thing but accepts an argument and performs the same task with it? (I know these questions are quite silly, but I’d like to better understand, trough them, how functions work)…
Has that something to do with the fact that the counter is an object (and we access it trough reference) while the global variable is a primitive type (and we access it trough value)?