How do I call this function in JavaScript? - 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;
}

Related

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

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

What happens if a JavaScript variable is re-initialized?

I'm new to javascript and I'm not sure if there is anything called re-initialization in javascript, so please excuse if there is no such concept.
What happens if a javascript variable is re-initialized?
Ex:
function foo()
{
var x = 10;
.... //do something
.... //do something
.... //do something
var x = 20;
console.log("x: " + x);
}
What would be the value of x here?
x will be 20. var is "hoisted" (more below), which means that the variable gets declared as of the beginning of the function, before any step-by-step code is run. Any initializer on a var statement is actually just an assignment statement.
So your code:
function foo() {
var x = 10;
//do something
var x = 20;
console.log("x: " + x);
}
is treated as though it were like this:
function foo() {
var x;
x = 10;
//do something
x = 20;
console.log("x: " + x);
}
When you call a function, the JavaScript engine does several things before it starts executing the step-by-step code in the question. one of the things it does is look through the code and process any var statements. (Although it's called the var statement, var is more of a declaration.)
It's quite fun, your code could also be written this way:
function foo() {
x = 10;
//do something
x = 20;
console.log("x: " + x);
return;
var x;
}
It would still be valid, and it would do exactly the same thing.
More (on my blog): Poor, misunderstood var
ES6 will introduce let, which behaves differently (amongst other things, it is scoped to the block it's in, whereas var is scoped to the function as a whole even if declared within a block); details on MDN.
The var keyword essentially just determines the scope of the variable and is handled before any of the code is actually executed (look up "hoisting"). Using var twice for the variable is redundant, but doesn't really do anything in particular. In the end you're just assigning 10 to x and later you assign 20 to x; nothing more, nothing less.
You can always run simple test to check that. var means it's this variable is in current scope. So in your example x will be equal to 20
var x = 10;
var x = 20;
var y = 10;
function Test() {
var x = 30;
y = 20;
alert('X in function: ' + x);
alert('Y is global, so it\'s ' + y);
}
Test();
alert('X outside of function: ' + x + ', also Y = ' + y);

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.

What do I have to do with the variable count in order to pass this tutorial about JavaScript function scopes?

The tutorial says:
Define a function named callFunc that takes one argument, a function
f. It should return an array containing the values f(0), f(0), f(1),
f(1). You can only call f twice.
This is what the tutorial gives:
var count = 0;
var f = function (x) {
count += 1;
return x + 2;
};
var callFunc = function (f) {
};
I have no idea how to use count to pass this tutorial.
Any suggestions?
You don't need to use count. Just call f() twice and put the return values into an array:
var callFunc = function (f) {
var f0 = f(0);
var f1 = f(1);
return [f0, f0, f1, f1];
};

Returning multiple values in javascript?

Is there a way to use a sort of the C#-like out or ref parameter modifiers with Javascript to do something like this:
function myManyReturnFunction(number1, number2, out x, out y) {
x = number1 * number2;
y = number1 / number2;
return true;
}
var height1, height2 = 0;
var check = myManyReturnFunction(1,1, out height1, out hight2);
I would like to change the variable's reference as well. So yes, passing an argument by reference.
function myManyReturnFunction(number1, number2) {
return {
x: number1 * number2,
y: number1 / number2
}
}
And you don't need x and y parameters, simply call:
var result = myManyReturnFunction(6, 9);
var x = result.x;
var y = result.y;
You can create an "object"...
function getObj(){
var objOut = new Object();
objOut.name = "Smith";
objOut.State = "Arkansas";
return objOut;
}
If you define the 'out' variables in the global scope outside if your function they can be reassigned inside the function with something like this:
var height1 = 0, height2 = 0;
function myManyReturnFunction(number1, number2) {
height1 = number1 * number2;
height2 = number1 / number2;
return true;
}
var check = myManyReturnFunction(1,1);
You can also create an object, which you can then pass to your function, which can be modified within the function like so:
var myValues = {}
function setValues(num1, num2, vals) {
vals.x = num1 * num2;
vals.y = num1 / num2;
return True;
}
setValues(1, 1, myValues);
There are several ways to return multiple values in JavaScript. You've always been able to return multiple values in an array:
function f() {
return [1, 2];
}
And access them like this:
var ret = f();
document.write(ret[0]); // first return value
But the syntax is much nicer in JavaScript 1.7 with the addition of destructuring assignment (if you're lucky enough to be targeting an environment guaranteed to support it (e.g. a Firefox extension)):
var a, b;
[a, b] = f();
document.write("a is " + a + " b is " + b + "<br>\n");
Another option is to return an object literal containing your values:
function f() {
return { one: 1, two: 2 };
}
Which can then be accessed by name:
var ret = f();
document.write(ret.one + ", " + ret.two);
And of course you could do something really horrible like modify global scope or even set properties on the function itself:
function f() {
f.one = 1;
f.two = 2;
}
f();
document.write(f.one + ", " + f.two);
More reading (and the source of some of these examples):
https://developer.mozilla.org/en/New_in_JavaScript_1.7#Destructuring_assignment_(Merge_into_own_page.2fsection)
You can return non-primitive types:
function blah() {
return { name: 'john', age: 23 };
};
var x = blah();

Categories

Resources