Skip to content

I m getting confuse why I am getting the second Result first..?

function first() {
  console.log("first");
}

function second() {
  console.log("second");
}

first(second());

Now the issue is when I am calling (first function) this is giving me the (second) first, I just wanted to know what is exactly happening here how this is working..? and how the second function’s value is passing inside first function..? (because there is no parameter inside first function)

Answer

Let’s debug your code step by step.

First, the two functions are defined. Nothing wrong with that.

Then, you call the first function, first()

Javascript reads the line and looks at what’s inside the parentheses so that it can pass the value into the function.

So now, it sees you called the second function, second(). Again, it looks at the parameters being passed. It sees nothing, so it passed nothing. The function you defined also accepts nothing, so it works! It prints out "Second" first. But you made the function return nothing. So, it’s a null function. It returns null.

Right now, your code is first(null) because second() is null. In Javascript, myFunction(null) is mostly the same as myFunction(), so Javascript passes nothing into the function, and your first() functions also accepts nothing, and this works, printing out "First" second.

Javascript does go left to right, but usually, it executes commands in the deepest lowest nest of brackets so that it can pass the returning results to the next level of parentheses.

.

I suggest watching more Javascript videos online and learning them on w3schools or https://developer.mozilla.org/ as they have great examples and studies.