How do I replace variables with values inside a stringified function (Javascript)? - 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.

Related

why is this a not defined when it clearly is?

I'm a total newbie, trying to survive my JS assignments. Any help is welcome.
When I run the following code, I get an error message saying "a is not defined." But a is defined.
function name(a, n) {
let a = b;
let b = x;
let c = n;
let b = c;
return c + a;
}
console.log(name(a, n));
a is only defined inside the function.
You are trying to read a (and n) outside the function and pass the resulting values to the function.
The problem is the way you call the function name instead of this console.log(name(a, n)); use this: console.log(name(5, 10));
As #Quentin said, when you pass the variables a and b to the function console log, it has to be defined outside of your function, but you can pass just the values and don't need to define the a and b variable outside the function.
So many problems here...
function name(a, n) {
let a = b; // a is already declared in function's declaration
let b = x; // x has never been declared
let c = n;
let b = c; // b is already declared in Line 3, additionally this line will make b = n
return n + a;
// this would finally become return b + b
// because Line 4: c = n
// and Line 5: b = c
// and Line 2: a = b
}
document.write(name(a,n)); // a and n should contain any value

Converting Strings to Template Literals in ES6

Suppose I have a string like "${a + b}", say read from JSON, that I'd like interpreted as an ES6 template literal. I thought something like this might work:
var x = {"add": "${a + b}"};
var a = 10, b = 20;
alert(`${x.add}`);
But this alerts as ${a + b}, so it just does one level of substitution.
Tried being clever by interpreting it again:
var a = 10, b = 20;
var x = {"add": "${a + b}"};
var i = `${x.add}`;
alert(`${i}`);
This still alerts as ${a + b}.
Tried being even more clever:
var a = 10, b = 20;
var x = {"add": "${a} + ${b}"};
var i = `${x.add}`;
alert(`${i}`);
This alerts as ${a} + ${b}.
Starting with a string, e.g. "${a + b}", is there any way to have this evaluated to completion as if it were a template literal? Ideally without eval!
Yes, they aren't recursive.
If your starting point is a string containing those placeholders, as far as I know there is no template compiler function. There's eval, of course; [insert all the usual caveats about using eval — only with content you trust, not if you can avoid it, etc., etc. — here].
So for instance:
"use strict";
var x = {"add": "${a + b}"};
var a = 10, b = 20;
console.log(eval("`" + x.add + "`"));

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

Variables equality

I'm unsure why example 1 don't give the same result as example 2.
Example 1:
var a = [1,6,2,4];
var b = [];
function minT(data){
var d = [];
d = data;
d.sort(function(a, b){return a-b});
return d;
};
b = minT(a)
console.log("b =" + b);
console.log("a =" + a);
Results:
b =1,2,4,6
a =1,2,4,6
Example2:
var a = [1,6,2,4];
var b = [];
function minT(data){
var d = [];
d = data.slice(0,10);
d.sort(function(a, b){return a-b});
return d;
};
b = minT(a)
console.log("b =" + b);
console.log("a =" + a);
Results:
b = 1,2,4,6
a = 1,6,2,4
Why does example 1 affect array a?
How can I write a function minT that does not affect array a. (without a slice inside the function)?
The reason why your first attempt sorts your a array also is because d = data; just copies the object reference, so both variables are pointing to the same location in memory.
When you do d = data.slice(0,10);, you're assigning the result of the slice operation to the d variable, which is a different object in memory than the data variable is pointing to.
Check out this book excerpt on the differences between value vs reference.
In example 1:
You have written d=data. It means that d is pointing to the element data. You have not just copied the values.
Example 2:
You have written d=data.slice(0,10). It actually copies the element of data rather than copying the address of data.
Now, to write the function minT without affecting data, and without using function data.slice(), you just need to replace the line data.slice() with your own simple code to copy element of one array to another.
Here's what I've done :
function minT(data){
var d = [];
for(var i=0;i<data.length;i++)
d[i]=data[i];
d.sort(function(a, b){return a-b});
return d;
};

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