How to understand Javascript in deep with var scope & closure? [duplicate] - javascript

This question already has answers here:
Javascript function scoping and hoisting
(18 answers)
Closed 6 years ago.
I just can't understand why the the a1 = function ?
and where is my value 1 that was passed to the fn(),
whether it was overrwrited by var a ?
the problem look like caused by the same names( var & function) !
function fn(a) {
console.log("a1 = " + a);
var a = 2;
function a() { }
console.log("a2 = " + a);
}
fn(1);
// a1 = function a() { }
// a2 = 2
function fnx(ax) {
console.log("a1 = " + ax);
var ax = 2;
function b() { }
console.log("a2 = " + ax);
}
fnx(1);
// a1 = 1
// a2 = 2
/* it equal to the final version */
function fn(a) {
var a;
a = function() { }
// function hoisting > variable hoisting
console.log("a1 = " + a);
a = 2;
console.log("a2 = " + a);
}
fn(1);
// a1 = function a() { }
// a2 = 2

I just can't understand why the the a1 = function ?
Function declarations are:
Hoisted to the top of the function they appear in
Declare a local variable (with the same name as the function) in the scope of the function they appear in (this isn't relevant because argument definitions do that too)
Assign themselves as the value of that variable
and where is my value 1 that was passed to the fn(),
Overwritten by the function declaration
whether it was overrwrited by var a ?
The var is ignored because there is already a local variable named a.
The assignment overwrites the function between the two console.log statements.
Your code is effectively the same as:
function fn(a) {
a = function a() { };
console.log("a1 = " + a);
a = 2;
console.log("a2 = " + a);
}
fn(1);

Related

Why don't you define every variables in the global scope

I am learning javascript and today i'm learning about the scope chain.
So apparently you can access the variable of the global scope even inside 3rd or 4th function scope.
I don't really get why wouldn't you declare all of your variables in the global scope to be able to access them everywhere and every function that you create ?
so why not :
var a = 'Hello!';
var b = 'Hey!';
var c = 'Hola!';
function first (){
//some function you want to do
second();
function second () {
console.log(a + b + c);
}
}
Instead of :
var a = 'Hello!';
function first (){
//some function you want to do
var b = 'Hey!';
second();
function second () {
var c = 'Hola!';
console.log(a + b + c);
}
}

Is there a way to add 1 to a variable using "+="? [duplicate]

This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
Closed 3 years ago.
I am trying to add a value to a variable using the += function. This is the code I am using:
function getAnswer() {
var num1 = Number(document.getElementById('numone').value);
var num2 = Number(document.getElementById('numtwo').value);
var oper = document.getElementById('oper').value;
var numberOfEquation = 0;
numberOfEquation += 1;
if (oper == '+') {
var p = document.createElement('p');
var txt = document.createTextNode(num1+num2 + ' - Equation ' + numberOfEquation);
p.appendChild(txt);
document.body.appendChild(p);
} else if (oper == '-') {
var p2 = document.createElement('p');
var txt2 = document.createTextNode(num1-num2 + ' - Equation ' + numberOfEquation);
p2.appendChild(txt2);
document.body.appendChild(p2);
}
console.log('You did an equation!');
}
I don't know what went wrong.
It appears to be a misunderstanding of how local variables work.
Local variable:
function x() {
var y = 0;
++y;
return y;
}
x(); // => 1
x(); // => 1
x(); // => 1
This returns 1 each time since var y explicitly declares a local variable. It will only exist during the execution of that function. As soon as the function terminates that variable ceases to exist. When the function starts up again it makes a brand new one.
Here's a different approach with a persistent variable:
var y = 0;
function x() {
++y;
return y;
}
x(); // => 1
x(); // => 2
x(); // => 3
This is because y exists outside the scope of the function. It lives as long as your program does.

Javascript - how to get variable value from another function in different function [duplicate]

This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
Closed 5 years ago.
I'm trying to get variable d value from function b in function e, but the result not value from function b. The result just from variable outside the function b.
var d = "maybe";
var a = 1;
function b() {
if (a == 1) {
var d = "yes";
} else {
var d = "no";
}
}
b();
function e() {
console.log(d); //output maybe
}
e();
How do I get the result to be the value from function b, or equal to "yes"?
You only have to use the var keyword when you define the variable. If you want to change the variable afterwords, don't use var. If you do you'll actually be making a new variable inside the function. So the code you want is:
var d = "maybe";
var a = 1;
function b() {
if (a == 1) {
d = "yes";
} else {
d = "no";
}
}
b();
function e() {
console.log(d); // now it outputs yes
}
e();

How do I replace variables with values inside a stringified function (Javascript)?

Consider the following :
var a = 5;
var b = function ()
{
console.log (a + 5);
};
var c = b.toString();
after the above has been executed, c will be equal to :
"function ()
{
console.log (a + 5);
}"
How can I have c be equal to :
"function ()
{
console.log (5 + 5);
}"
instead?
I tried the following :
var a = 5;
var b = function ()
{
console.log ('<%a%>' + 5);
};
var c = b.toString().replace('<%a%>', a);
But the above obviously makes c equal to :
"function ()
{
console.log ('5' + 5);
}"
Is there some other way of achieving this (javascript + RegEx) without using libraries like underscore (with the known template function) ?
Basically I'm trying to come up with a neat function that will convert a function into a string while at the same time replacing all variables (that have a hardcoded value) present in that function with their respective values, without the use of any variables.
Thanks
You can fix your snippet by changing the first argument of .replace:
var a = 5;
var b = function ()
{
console.log ('<%a%>' + 5);
};
var c = b.toString().replace("'<%a%>'", a);
For more generic solution you may need smarter parser with syntactical analysis.

How do I call this function in JavaScript?

I am trying to call this function in Javascript but it wont work.
eval("function f() { return x + 1;}")
I called it by typing function f(12);
If you MUST you eval.. you should give x to the function as a parameter. So it should be :
eval("function f(x) { return x + 1;}")
But you could just write it as:
function f(x) {
return x + 1;
}
eval() in javascript
The eval() function evaluates or executes an argument.
If the argument is an expression, eval() evaluates the expression. If the argument is one or more JavaScript statements, eval() executes the statements.
var x = 10;
var y = 20;
var a = eval("x*y") ;
var b = eval("2+2") ;
var c = eval("x+17")";
var res = a + b + c;
Output:
200
4
27
Create your function like this:
function f(x) {
return x + 1;
}

Categories

Resources