Home > Mobile >  Why does the foreach statement with the function expression work when it is not called?
Why does the foreach statement with the function expression work when it is not called?

Time:04-13

I don't know why 'forEach statement' works even though i didn't call.

<script>

    const data = [1, 2, 3]

    const makeTree = data.forEach((el) => {
        console.log("hi")
    })
    
</script>

As you can see, I never call makeTree function. But when I run the code, I can see three hi in my console. Someone tell me why does this happen.

CodePudding user response:

As you can see, I never call makeTree function

makeTree isn't a function.

You are assigning it the return value of immediately calling data.forEach().

If you want it to be a function then you need to explicitly write it as a function using either a function declaration, function expression, or arrow function.

function makeTree() {
    data.forEach((el) => {
        console.log("hi")
    });
}

CodePudding user response:

Its becouse it is a callback function similar to this:

function foreackExplained(calback){
  
  calback('hollo')
}
foreackExplained( (val)=> console.log(`${val} world`) )

CodePudding user response:

makeTree as variable receive a value from right expressions, but right expressions is function call

Maybe you can read this https://javascript.info/function-expressions

CodePudding user response:

forEach is an array function so if you are even write like this

array.forEach((el) => {console.log("hay")})

it's going to execute

in your case you are assigning a value to maketree but there's no need if you only want to print you can do it directly

    data.forEach((el) => {
    console.log("hi")
})

like this

if you want to restrict your forEach you can write it in some kind of if condition then it will be only executed when the condition was right

if(false){
data.foreach((el) => {
console.log("hellow");
}
}

or you can write a separate function for that and call that function when you need

conclusion: forEach itself a function(Array function) so when you wright it's going to execute

Have a good day......

  • Related