Learning Javascript Functions Scope - javascript

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".

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);

var
The function Greet sets the default value of Greetings as greet.
var greet="Hello"; is a global variable thus the value of greet is always "Hello" unless overrridden during function call.
In your function Greet_Friend you call the function Greet without supplying any parameters, thus the function Greet takes the global variable with the value of Hello.
To get the value of "Hi", you would need to pass the local variable greet to the function Greet as follows
function Greet_Friend()
{
var greet="Hi";
Greet(greet);
}
Then call Greet_Friend as follows:
Greet_Friend()

No Global Variables
//greet takes a string as a parameter - you can call it anything, but no equals sign
function greet(str) {
console.log(str)
}
//greet_friend initializes the variable and sends it to greet
function greet_friend() {
var myGreeting = 'Hi';
greet(myGreeting);
}
function greet_friend(); // "hi"

Related

What is the difference between displayName(); and return displayName;?

I am an aspiring front-end developer. I was reading an MDN article about closure in JavaScript. The MDN article used the following two code examples to explain the basic concept. Though I understood the basic concept, I have the following doubt.
What is the difference between displayName(); and return displayName ?
function init() {
var name = 'Mozilla'; // name is a local variable created by init
function displayName() { // displayName() is the inner function, a closure
alert(name); // use variable declared in the parent function
}
displayName();
}
init();
**
function makeFunc() {
var name = 'Mozilla';
function displayName() {
alert(name);
}
return displayName;
}
var myFunc = makeFunc();
myFunc();
In the first case it is executing the function , while in second case makeFunc is returning another function.Check the console.log. That is the reason there is a () after myFunc() which will execute the function returned from makeFunc
function init() {
var name = 'Mozilla';
function displayName() {
alert(name);
}
displayName();
}
init();
function makeFunc() {
var name = 'Mozilla';
function displayName() {
alert(name);
}
// this is returning a function
console.log(displayName)
return displayName;
}
var myFunc = makeFunc();
// since it is returning a function it is getting executed ony after adding () with it
myFunc();
What's the difference between displayName() and return displayName?
The difference is that the first is invoking the function displayName while the second is returning it. To see an example of what that means:
const log = () => console.log('I was invoked!')
const getLog = () => {
return log
}
const doLog = () => {
log()
}
We have some function that, when invoked, prints to the console. We also have two other functions, one that returns log and one that invokes it. When we call getLog(), we don't see anything printed to the console. When we call doLog(), we do.
Another point is that getLog returns the value of log. So we can do this as well:
const logByDifferentName = getLog()
which wouldn't cause log to be invoked but assign it to another value.

Does the callback function create a new scope in javascript

function hello() {
var result = [];
var str = 'I am here';
function inner() {
var result = [];
for (var i=0;i<10;i++) {
result.push(i);
}
return result;
}
}
in the code above when I called the function hello(), the return value was an empty [], also it did not console.log the str from the inner function. However, in the below code set I have used a call back function:
function forEach(cb) {
for(var i =0;i<10;i++) {
cb(i);
}
}
function hello() {
var result = [];
var str = 'I am here';
forEach(function(num) {
console.log(str);
result.push(num);
});
return result;
}
the question is why both functions reacted, and gave a different output? Note; in both codes there was an inner function which supposed to create a new scope that can access the outer scope ? Does anyone have a good explanation for this issue ?
Thanks
In the first code block, inner is a new function that is declared inside of hello. It does not execute because you do not call it. It does create a new child scope inside of hello when it is called. But, since hello() doesn't actually return anything and doesn't call inner(), you get undefined when you call hello(). You could fix that by changing to this (you can run this snippet to see the return value):
function hello() {
var str = 'I am here';
// declare inner
function inner() {
var result = [];
for (var i = 0; i < 10; i++) {
result.push(i);
}
return result;
}
// now call inner() and return its result
return inner();
}
console.log(hello());
Functions declared inside other functions do create a new scope. Every function declaration and corresponding call in Javascript creates a new scope. If the function is inside another function, then the code inside that inner function has access to both its local scope and to the parent scope and this can nest as deep as your nested function declarations go.
the question is why both functions reacted, and gave a different
output? Note; in both codes there was an inner function which supposed
to create a new scope that can access the outer scope ? Does anyone
have a good explanation for this issue ? Thanks
In the first example, you never called the inner function so it never executed.
In the second example, you pass an inline, anonymous function reference as a function argument to your forEach() function. When that forEach() function executes, it calls your callback function with the line of code cb(i) so that's how your callback function is getting called in the second example. forEach() calls it for you.
Also, in the second example, the locally declared callback function is accessing the parent scope and modifying the result array (which is perfectly allowable). In your first code example, you are declared a new result variable in the inner function scope and then returning that. You are not accessing the parent result variable. When you declare a local variable with the same name as a variable in the parent scope, the local variable overrides the parent variable (essentially hiding the parent variable) and any references to that variable in the local scope only access the local variable.
You could have written the first code example to use a parent scoped result variable like this:
function hello() {
var result = [];
var str = 'I am here';
// declare inner
function inner() {
for (var i = 0; i < 10; i++) {
result.push(i);
}
return result;
}
// now call inner() and return result
inner();
return result;
}
console.log(hello());
You have confused function declaration and calling.
Declaring a function can be done in multiple ways:
function myNewFunction() {}
Now this function exists in the current scope, but will not execute unless called.
You can call the function like this. Now your function will get executed.
myNewFunction();
Functions and their scopes can be compared to variables. Functions defined inside another function can only be accessed from inside the parent function. Let me give you an example.
function myMegaFunction() {
console.log("in mega");
function mySmallFunction() {
console.log("in small");
}
}
myMegaFunction();
This will only print - 'in mega'. If you call mySmallFunction() inside of myMegaFunction then both lines will get printed.
Now let's take a more complex scenario like this:
function myMegaFunction() {
console.log("in mega");
var str = "car";
var result = function mySmallFunction() {
console.log("in a small", str);
}
return result;
}
var resultingFunction = myMegaFunction();
resultingFunction();
This will first print the following:
in mega
in a small car
So essentially, this is functions being passed around like variables. They can be executed later on too.

Assign a function with custom parameters without calling the funcion

I've a function A which accepts at run-time another function B as parameter and calls it. The problem is the function B needs some parameters, but I don't know how to pass the function B, with parameters, to the the function A.
Example:
function callerFunction(c)
{
alert("The caller is calling the function!");
c(c.arguments);
};
var a = "hello";
function thisOne(d)
{
d = "I changed my way";
alert(d);
};
callerFunction( /* I NEED TO PASS THE 'thisOne' with the parameter/variable 'a' here, and then call it inside 'callerFunction' */);
Just pass a closure:
callerFunction(function() { thisOne(a); });
And call it as c(), not c(c.arguments).
Note that this anonymous function will reference the a variable, not the value a had at that moment. So if callerFunction() was to store this function object and call it later, if you changed the value in a between passing the anonymous function and the time it is called, the value of a from the perspective of the anonymous function would have changed:
var a = 1;
var fn = function() { console.log(a); };
fn(); // Logs 1
a = 2;
fn(); // Logs 2

Use of () in javascript for a function

Sorry if its being a noob question, but I still can't understand the difference of its usage so I am unable to search on google with right keywords to search for.
I am following this tutorial on Closures.
Now my query is for this code -
function makeFunc() {
var name = "Mozilla";
function displayName() {
alert(name);
}
return displayName;
}
var myFunc = makeFunc();
myFunc();
Why displayName being a function is referenced as a property in the code ? Do being a closure function it needs to be returned as a property as I tried this code -
function makeFunc() {
var name = "Mozilla";
function displayName() {
alert(name);
}
return displayName();
}
var myFunc = makeFunc();
myFunc();
Output - An alert but an error TypeError: myFunc is not a function.
Let me know when to use what or what basic concept I am missing here.
"return displayName;" is returning the function displayName.
The result is then being set to myFunc.
function makeFunc() {
var name = "Mozilla";
function displayName() {
alert(name);
}
return displayName;
}
var myFunc = makeFunc();
myFunc();
It is easier to understand if you think of:
function displayName(){}
as an alternative to:
displayName = function(){}
makeFunc = function () {
var name = "Mozilla";
displayName = function () {
alert(name);
}
return displayName;
}
var myFunc = makeFunc();
myFunc();
In first case, you're returning a function reference which you can use later. In the second case, you are returning the result of the function which is undefined since you're not returning anything. So the error comes up as myFunc is not a reference to a function and hence cannot be called.
Other than the above, I don't know what you're meaning to say when you say "property".
return displayName()
this code returning not the function, but result of calling this function.
var myFunc = makeFunc();
myFunc();
the same.in myFunc not the function, but it's result.
try to do this:
return displayName;
...
var myFunc = makeFunc(); //makeFunc() will return displayName() function
myFunc();
Before understanding closures, which is a concept extended from the Javascript function scope.
Closures: allows certain variables to get accessed within the scope being created.The inner function can get accessed to the outer function as well as its variables.But the outer function cannot access variables within the inner function.
So in your closure example, the reason why output alerts "Mozilla" is because your inner function-displayName alerts the name variable declared in the outer function (displayName can get access to any variables in the makeFunc function). So when your makeFunc function invokes the inner function-displayName, you will get a TypeError with undefined. Same result will output when you simply call the makeFunc(), you get undefined.

passing an anonymous function to another function in Javascript

I understand you can pass a function as an argument to another function like so
var fn = function(){alert('Hello')}
function outer(a,fn){
fn();
}
How can you pass an anonymous function to another function and have it invoked within the function after taking a parameter from the outer function?
function outer(function(x){alert(x);})
{
var xVar = "foo";
//..would liked to pass xVar to the anaonymous function
//passed as a param to the function so that "foo" is displayed as message...
}
Please note changing the signature of outer would be the last choice.
You're confusing function invocation (calling a function) with function declaration (defining a function). Here's how do what you ask:
// declare the outer function
function outer(func)
{
var xVar = 'foo';
func(xVar)
}
// now invoke it
outer(function (x)
{
alert(x);
});

Categories