Javascript: scope of variable - javascript

For a function, does it get the variable scope during the declaration, or before the run time?
I tried the first part of code below and it doesn't work. The second part works. Can somebody shed some insight on the difference?
//// does not work
function a() {
console.log(v1);
}
function b() {
let v1 = 1;
a();
}
b();
//// does work
function a() {
console.log(v1);
}
function b() {
a();
}
let v1 = 1;
b();

OK, Let's Look at this:
//// does not work
function a() {
console.log(v1);
}
function b() {
let v1 = 1;
a();
}
b();
In the above snippet of code, you have 2 functions (a() and b()) and invoke the method b() from your "main" function (which is unnamed but there). In a(), you try to directly access a local-scope variable from b() - which you can't.
//// does work
function a() {
console.log(v1);
}
function b() {
a();
}
let v1 = 1;
b();
So in this snippet of code, you also have a() and b() - as well as a variable v1. Since this is declared in the public space (before invoking b() - which then invokes a()), it is also available within the methods that you invoke.

The let keyword gives a variable block-level scope, meaning the v1 variable in b() is only usable inside b(). a() does not know what v1 is.
//// does not work
function a() {
console.log(v1);
}
function b() {
let v1 = 1;
a();
}
b();
In this example, v1 is being set in the global scope, so all your functions will recognize it.
//// does work
function a() {
console.log(v1);
}
function b() {
a();
}
let v1 = 1;
b();

Related

Why function expression is called when there are function declaration and function expression with same name?

Here I have two function declarations with same name.
function a() {
console.log('a1')
}
function a() {
console.log('a2')
}
a();
It make senses that a() prints a2.
And here are a function declarations and a function expression.
b = function() {
console.log('b1')
}
function b() {
console.log('b2')
}
b();
But here b() prints b1, what is the reason?
function b() will hoist the definition to the top of the containing scope. As a result, it is declared first. Following that, b is then assigned to with your b = function assignment, and when you call b() it then logs 'b1'.
I think this is the cause of hoisting. because hoisting moves all declarations to the top of the current scope (to the top of the current script or the current function).
and here the function assign to **b for hoisting.**

Javascript function scope and parameter

Here is the code:
function b() {
console.log(x);
};
function a() {
var x= 1;
b();
}
a();
//the output is : x is not defined!
Can anybody help explain why it will ouput undefined? I thought it would output 1. Why function b() can't get the variable x?
You're confusing closures with actual invoking of a function. If you had function b inside function a, then you can access x like so.
function a() {
var x= 1;
function b() {
console.log(x); // print out 1
};
b();
}
You must pass x variable as parameter:
function b(x) {
console.log(x);
};
function a() {
var x= 1;
b(x);
}
a();
If a var is define inside a function, the var can only be use within the function. If a var is define outside the function, then it can be use anywhere. Your var x =1 is defined inside function a(), so it can only be use inside function a(). To solve your code, you can simply move var x= 1 outside function a(). Here's the code:
function b() {
console.log(x);
}
var x= 1;
function a() {
b();
}
Or, I could suggest you use this instead. It's much shorter:
var x= 1
function b() {
console.log(x);
}

How to call nested function in javascript?

I have two function like this..
function a() {
function b() {
alert('reached');
}
}
how i call function b() from outside of function a()..
In general, you can't. The point of defining a function inside another function is to scope it to that function.
The only way for b to be accessible outside of a is if (when you call a) you do something inside a to make it available outside of a.
This is usually done to create a closure, so that b could access variables from a while not making those variables public. The normal way to do this is to return b.
function a() {
var c = 0;
function b() {
alert(c++);
}
return b;
}
var d = a();
d();
d();
d();
var e = a();
e();
e();
e();
You can rearange your code to this
function a() {
this.b = function() {
alert('reached');
}
}
now instantiate it and run:
c = new a();
c.b();
You will need to return the inner function call.
function a() {
function b() {
alert('reached');
}
return b();
}
And then you can call this function simply by calling function a like this:
a();
The output will be the required alert.

Working with hoisting in Javascript

How will the code look after hoisting is done by js?
jsFiddle shows it prints 1, but how is that true?
var a = 1;
function b() {
a = 10;
return;
function a() {}
}
b();
alert(a);
This is what I have come up with:
var a; //hoisted var declaration
function b() { //hoisted function declaration
function a() {} //hoisted function declaration
a = 10;
return;
}
a=1;
b();
alert(a);
This is expected behaviour.
var a = 1;
function b() {
a = 10;
return;
function a() {}
}
b();
alert(a);
This all has to do with the scope and when a function is defined. Declaring a function with the codeword function first
function a(){};
will add the function to the scope at parse time. I.E It is defined before the first line in b(). What is happeing is that you define a to be a loal variable inside b. This will make the global variable a unreachable from within b. a will be defined and manipulated locally within the scope of b and leave the global a untouched.
Equivalient code will be
var a = 1;
function b() {
var a = function() {}
a = 10;
return;
}
b();
alert(a);
After some experimentation, i've reached to the conclusion that having the same Global variable and local function name is confusing the JS Engine..
So what you are doing by a = 10 is changing that function declaration or something.. it's not affecting the global variable a. But, changing the name of global variable and keeping it different from the inner local function will give the expected results:
var c; //hoisted var declaration
function b() { //hoisted function declaration
function a() {alert('in');} //hoisted function declaration
c = 10;
return;
}
c=1;
alert(c); //1
b();
alert(c); //10
See the DEMO here
var a = 1;
function b() {
a = 10;
return;
function a() {}
}
b();
alert(a);
There is nothing confusing here. Moving all declaration to the top, your code is the same as:
var a; //global a
var b = function(){
var a = function(){}; //local a
a = 10; //still referring to local a
return;
};
a = 1; //referring to global a
b();
alert(a); //referring to global a
Both a aren't the same. I believe it is quite obvious.
The first code example given appears to be identical to one on Ben Cherry's adequately good site. This goes into more detail on the way scoping works in JavaScript (primarily - it's function-level, not block-level), and ends with the following statement, attributed directly to the ECMAScript Standard:
If the variable statement occurs inside a FunctionDeclaration, the variables
are defined with function-local scope in that function, as described
in section 10.1.3. Otherwise, they are defined with global scope (that
is, they are created as members of the global object, as described in
section 10.1.3) using property attributes.
...
A Block does not
define a new execution scope. Only Program and FunctionDeclaration
produce a new scope.
This hopefully explains why the code you include works the way it does - there is no "way the code looks after hoisting", there's just a simple (and, common) misunderstanding about how scope works in JavaScript.

Access array from another function in javascript

Please, if is it possible to define array in one function and access this, from another function in javascript?
I think better should be:
var x =[];
function a() { x = ['a','b']; };
a();
function b() { alert(x[0]); }
b(); //alerts 'a'
Using var to declare the variable at the scope needed
Yes:
function a() { x = ['a','b']; };
a();
function b() { alert(x[0]); }
b(); //alerts 'a'

Categories