Why does console.log(z) throw NaN? - javascript

When it's able to pick up w from the outer scope, why is it not able to pick up z?
var w = 1, z = 2;
function foo( x = w + 1, y = x + 1, z = z + 1 ) {
console.log( x, y, z );
}
foo();

it's able to pick up w from the outer scope
Yes, because you don't have a variable w inside your function.
why is it not able to pick up z?
Because your parameter declares a local variable with the name z, and that shadows the global one. However, the local one is not yet initialised with a value inside the default expression, and throws a ReferenceError on accessing it. It's like the temporal dead zone for let/const,
let z = z + 1;
would throw as well. You should rename your variable to something else to make it work.

The first one works because the w in the w + 1 looks for w in the formal parameters but does not find it and the outer scope is used. Next, The x in the x +1 finds the value for x in formal parameters scope and uses it, so the assignment to y works fine.
In the last case of z + 1, it finds the z as not yet initialized in the formal parameter scope and throws an error before even trying to find it from outer scope.
Changing the variable z to something else as pointed out by #bergi, should do the trick.
var w = 1, z = 2;
function foo( x = w + 1, y = x + 1, a = z + 1 ) {
console.log( x, y, a );
}
foo();

you have
function foo( x = w + 1, y = x + 1, z = z + 1 )
during
x=w+1
x is undfined
and then w is undefined also
so it look into local execution context didnt find any value
so it goes outerscope and find w=1
so in local space w also become 1
now during
z = z + 1
the z which is at the left side of = is undefine
and then the z which is at the right side of = also undifine so it looks for
z inside local execution context and find one the z which was at the left side
of the equation so it do not need to go to outer space.
so z become undifine
however if you write this way z=this.z+1 you will get z= 3
cause this.z wont look into localscope directly go to outerscope and find z=2

Related

How can I swap two variables without using a temporary variable in Javascript

I know how to swap integers with a temporary variable, like this:
let x = 5;
let y = 7;
x = x + y;
y = x - y
x = x - y;
But how can I swap two variables of any type without using a third variable ?
I just discovered this in Javascript, although it must have been there for decades — and I see the question is asked in lots of languages and the answer in Javascript is unnervingly simple.
[x, y] = [y, x];

Quadratic function for increment speedup of countup

I'm writing a jQuery plugin for fast-counting up to a value when a page loads. Since javascript can't run as fast as I want it to for larger numbers, I want to increase the increment step so that it completes within a given timeframe, so I'd need a quadratic function that passes through origo and has it's turning point at y = target counting value and x = target duration, but I can't get a grip on the math for doing this. Since both the number and the duration can change, I need to be able to calculate it in javascript aswell.
Hopefully someone can help me with this one!
Let's formalize the statement a bit.
We seek an equation of the form
y = a*x*x + b*x + c
where x is the time axis and y is a count axis. We know that one point on the curve is (0,0) and another point is (xf, yf) where xf is the final time and yf is the target count. Further, you wish for the derivative of this equation to be zero at (xf, yf).
y' = 2*a*x + b
So I have three equations and three unknowns:
(0,0) => 0 = c
(xf, yf) => yf = a*xf*xf + b*xf + c
y' = 0 # (xf, yf) => 0 = 2*a*xf + b
You should be able to solve it from there.
// Create a quadratic function that passes through origo and has a given extremum.
// x and y are the coordinates for the extremum.
// Returns a function that takes a number and returns a number.
var quadratic = function (x, y) {
var a = - (y / (x * x));
var b = (2 * y) / x;
return function (x) {
return a * x * x + b * x;
};
};

How do I change the value of a global variable inside of a function

I am using JavaScript and I create a global variable. I define it outside of a function and I want to change the global variable value from inside a function and use it from another function, how do I do this?
Just reference the variable inside the function; no magic, just use it's name. If it's been created globally, then you'll be updating the global variable.
You can override this behaviour by declaring it locally using var, but if you don't use var, then a variable name used in a function will be global if that variable has been declared globally.
That's why it's considered best practice to always declare your variables explicitly with var. Because if you forget it, you can start messing with globals by accident. It's an easy mistake to make. But in your case, this turn around and becomes an easy answer to your question.
var a = 10;
myFunction();
function myFunction(){
a = 20;
}
alert("Value of 'a' outside the function " + a); //outputs 20
Just use the name of that variable.
In JavaScript, variables are only local to a function, if they are the function's parameter(s) or if you declare them as local explicitely by typing the var keyword before the name of the variable.
If the name of the local value has the same name as the global value, use the window object
See this jsfiddle
x = 1;
y = 2;
z = 3;
function a(y) {
// y is local to the function, because it is a function parameter
console.log('local y: should be 10:', y); // local y through function parameter
y = 3; // will only overwrite local y, not 'global' y
console.log('local y: should be 3:', y); // local y
// global value could be accessed by referencing through window object
console.log('global y: should be 2:', window.y) // global y, different from local y ()
var x; // makes x a local variable
x = 4; // only overwrites local x
console.log('local x: should be 4:', x); // local x
z = 5; // overwrites global z, because there is no local z
console.log('local z: should be 5:', z); // local z, same as global
console.log('global z: should be 5:', window.z) // global z, same as z, because z is not local
}
console.log('global x: should be 1:', x); // global x
console.log('global y: should be 2:', y); // global y
console.log('global z: should be 3:', 3); // global z
a(10)
console.log('global x: should be 1:', x); // global x, unaltered
console.log('global y: should be 2:', y); // global y, unaltered
console.log('global z: should be 5:', z); // global z, overwritten in function a
Edit
With ES2015 there came two more keywords const and let, which also affect the scope of a variable (Language Specification)
var a = 10;
myFunction(a);
function myFunction(a){
window['a'] = 20; // or window.a
}
alert("Value of 'a' outside the function " + a); //outputs 20
With window['variableName'] or window.variableName you can modify the value of a global variable inside a function.
<script>
var x = 2; //X is global and value is 2.
function myFunction()
{
x = 7; //x is local variable and value is 7.
}
myFunction();
alert(x); //x is gobal variable and the value is 7
</script>
A simple way is to use var
var apple = null;
const some_func =()=>{
apple = 25
}
some_func()
console.log(apple)

How/when is this anonymous function invoked?

I'm new to javascript and I am looking through some Raphael demo code. I'm confused by how this is working...
if (R) {
(function (dx, dy, R, value) {
var color = "hsb(" + [(1 - R / max) * .5, 1, .75] + ")";
...
From what I can see this is declaring an anonymous function which takes 4 arguments. How is this function invoked when this function doesn't have a name??
Demo page.. http://raphaeljs.com/github/dots.html
JS file.. http://raphaeljs.com/github/dots.js
To briefly answer your question it is invoked immediately upon decleration.
You left out an important part, the end of the function definition:
})(leftgutter + X * (j + .5) - 60 - R, Y * (i + .5) - 10, R, data[o]);
What this says is }, which ends the function, then ), which ends the parenthesis that opened with (function. If what remains looks like an argument list, that's because it is.
An illustrative example:
(function(arg){ alert(arg); })("Hi!");
you didn't include enough of the code to tell. looking at the source, this method is executed immediately. ignoring the contents of the function, it looks like this
(function (dx, dy, R, value) {
// ... stuff
dot[0].onmouseover = function () {
if (bg) {
bg.show();
} else {
var clr = Raphael.rgb2hsb(color);
clr.b = .5;
dt.attr("fill", Raphael.hsb2rgb(clr).hex);
}
lbl.show();
};
// more stuff
})(leftgutter + X * (j + .5) - 60 - R, Y * (i + .5) - 10, R, data[o]);
this all happens within a loop, and the variables are referenced in an event handler method. the anonymous method creates a new scope so the values at the time the loop runs are preserved, rather than having every event handler point to the very last value the variable holds.
An anonymous function is created and called on the fly. A simplified version would be
function(a){<some method code>}(x);
In this the value x is passed as a in the function. In your example the function is later being invoked:
(function (dx, dy, R, value) {
var color = "hsb(" + [(1 - R / max) * .5, 1, .75] + ")";
...
})(leftgutter + X * (j + .5) - 60 - R, Y * (i + .5) - 10, R, data[o]);
It’s called 28 lines later:
...
})(leftgutter + X * (j + .5) - 60 - R, Y * (i + .5) - 10, R, data[o]);
so those are the four arguments.
If you don’t give a function a name, the only thing you can do with it is call it right there or pass it to someone else. This is pretty standard if you’re familiar with event listeners:
window.addEventListener("load", function(event) {
document.body.innerHTML = "hello";
}, false);
In this case, it’s used to control the scope of variables, to guarantee that their values are not reused after an iteration of the loop completes. Many libraries wrap the entire script in a function block, solely to create a new scope. (Unlike in other curly brace languages, a { } block alone does not create a new scope.)
(function() {
var foo; // guaranteed to not leak or interfere with someone else's foo
// 6000 lines ...
})();
Read about JavaScript Scope and Closures.

Efficient algorithm for equation

I want to ask about efficient algorithm.
Example i have equation :
x = y + z;
if the value of variable y = 1, variable z = 2 so variable x is 3
But how to get value of y automatically if variable x = 3 and variable z = 2 with that equation? without create new equation y = x - z
I hope can get sample code using C# or javascript.
Another example, if the equation is
a = (((x + y - z)/2)*10)^4
The equation is from program, user submit value of 3 varibles.
User submit variable (x, y, z) or (y, z, a) or (z, a, x) or (a, x, y)
if user input value for var x, y and z, program can displaying value of a with that equation. Without create a = ...
if user input value for var y, z and a, program can displaying value of x with that equation. Without create x = ...
if user input value for var z, a and x, program can displaying value of y with that equation. Without create y = ...
if user input value for var a, x and y, program can displaying value of z with that equation. Without create z = ...
What you are looking for is an 'equation solver'. This is non-trivial and there is quite a bit of research on this and some well-known large mathematical software do this.
For more details, please google 'Algorithms for Computer Algebra'.
You have to resolve the equations with respect to the unknown variable:
x = y + z;
is equivalent to
y = x - z;
and
z = x - y;
For the second equation it is more difficult. If a < 0 there will be no solution. Otherwise you can first take the 4th root:
a = (((x + y - z)/2)*10)^4 <=> sqrt(sqrt(a)) = +/- (x + y + z) * 5
Then resolve it with respect to x, y or z. Note that you will get two solutions in general.
There are programs and libraries that can do these calculations automatically: Check for "symbolic math" or "computer algebra systems".
i sense a deep research of math on that problem you present, you can serach on google about equation algorithm solve that a link of wikipedia
Yes in case you have a simple workflow of some basic algorithm to find a variable
let us suppose this environment;
since there are always going to be three variables, you can valid that only one of the three is null and then select the equation of the variable you want to find if non are null then you send a message that no value are null
The original equation is x=y+z-a
x=5; y=7; z=2; a=null;
If (!x.hasValue ()){
x= y + z - a;
}
....
Else if (!a.hasValue ()){
a = -(x + y + a);
}Else{Console.Write("Don't give value to all variable");}
This isn't how it works. In programming languages you don't really have equations but rather assignments. You can assign a right-side value to the variable on the left side.
So the only way to obtain y, when having x and z is by running
y = x - z
EDIT: you may want to create something like
myFunction(double? x=null, double? y=null, double? z=null, double? a=null)
And then inside you check which variable is null (so not used), and perform your calculations accordingly. You would run it like this
var something = myFunction(x: 1, y: 2, a: 3)
If you don't want to write a new line of code and get the result of 'y' when 'x' is diferent to zero within the same equation, try this ...
// equation : x = y + z
var x=3,y=0,z=2;
x = ((x!=0) ? (x-z) : y ) + z;
console.log("Result : "+ x);
// or saving the value in 'y'
x = ((x!=0) ? y = (x-z) : y ) + z;
console.log("Result 2 : "+ x);
Answering the first question:
Y = X - Z
is the only possible solution. There aren't other ways to calculate Y.
This because computers can't solve equations (or better, they can be programmed to solve them, but only using 'Y = X - Z') , they can change the value of a variable. In this case we set the Y value to (X - Z) value.
Answering the second question:
You can solve that equation doing
X = fourth square of (...)
or you can use libraries that do all this work by themselves, like 'computer algebra system' (Also cited by #FrankPuffer)
Definitely: you can solve the equations doing inverse operation, like 'Y = X - Z', or by using libraries that simplify writing code.

Categories