0

I´m starting to learn javascript and this is driving me crazy. Here are to different codes that give me the same output.

In this one I don´t define any parameters inside the function

var name = "Alex"
function hellow(){
  return "Hellow " + name
}
hellow();

Here I do define the parameter name

var name = "Alex"
function hellow(name){
  return "Hellow " + name
}
hellow(name);

Can anybody explain to me why is it needed to define the parameters inside the function? It seems that if you don´t define them it still works.

Thank you

Maniraj Murugan
  • 8,868
  • 20
  • 67
  • 116
alex44_lel
  • 183
  • 1
  • 2
  • 12

2 Answers2

2

It seems that if you don´t define them it still works.

That's only if the function closes over the variable you want to use. (Your second one does.) Usually it doesn't. Here's an example where it doesn't:

function hellow(){
    return "Hellow " + theName;
}
function example() {
    var theName = "Alex"
    console.log(hellow());
}
example();

(I used theName there instead of name because there's a global variable called name on browsers — it has the name of the window in it.)

In that example, theName is declared within example, and hellow isn't declared within example, so hellow doesn't close over theName. In that case (which is the common case), for hellow to have the value from theName, you must pass it as a parameter.

When a function closes over a variable, that's called a closure. You can read more about closures here on Stack Overflow and in this old post (with slightly outdated terminology) on my anemic little blog.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

You are setting var name globally so you can reach it inside the function scope. that's why it doesn't matter if you pass it as an argument.

without a global variable you won't be able to know what's name var

function hellow(name){
  return "Hellow " + name
}
hellow("alex");
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
fedesc
  • 2,554
  • 2
  • 23
  • 39