Arham Chopra Arham Chopra - 6 months ago 9
Node.js Question

Learning Javascript Functions Scope

var greet="Hello";

function Greet(Greetings=greet) {
console.log(Greetings);
}

function Greet_Friend() {
var greet="Hi";
Greet();
}

Greet_Friend();


I am having some problems in understanding the scopes in javascript?
On Running this code i get "Hello" as output but i need "Hi".

Answer

I know your logic, you want to use Greet() to log a variable that in other function, right?

var greet="Hello";

function Greet(Greetings=greet) {
  console.log(Greetings);
}

function Greet_Friend()  {
  var greet="Hi";
  // you forgot to pass the local variable to the log function
  Greet(greet);
}

Greet_Friend();

In reality, we don't invoke Greet() directly in the Greet_Friend,we do this

var greet="Hello";

function Greet(Greetings=greet) {
  console.log(Greetings);
}

function Friend()  {
  var greet="Hi";
  return greet;
}

Greet(Friend());

Or use callback:

var greet="Hello";

function Greet(Greetings=greet) {
  console.log(Greetings);
}

function Greet_Friend(callback)  {
  var greet="Hi";
  callback(greet);
}

Greet_Friend(Greet);