do I need eval? [duplicate] - javascript

This question already has answers here:
Why does eval() exist?
(6 answers)
Closed 9 years ago.
I've searched the web for what eval does and here is what I have found:
The eval() method evaluates JavaScript code represented as a string.
And I've read this question, which says that it is evil.
But I really don't understand what does it do, i.e I don't see when to use eval.
I mean:
var x= 3;
var y =5;
var z = eval("x+y");
// is the same as:
var z = x+y;
so as I see it's just adding characters to my code. Can somebody give me an example of why eval was created in the first place?

It allows execute dynamicly generated code, not just "x+y".

Eval allows you to evaluate a string as javascript code. This means you can do things like evaluate a string to call a function:
function add(x,y){
return (x+y);
}
stringToEval = 'add(5,6)';
eval(stringToEval);
This code would run the function by evaluating the string as a function call.
So I would say you do not need to use eval here. Just add the two variables.

Related

Why do people write js like this? [duplicate]

This question already has answers here:
Why does any JavaScript code want to "cut the binding"?
(1 answer)
JavaScript syntax (0, fn)(args)
(2 answers)
Closed 2 years ago.
var type = (0, _reactIs.isMemo)(nodeOrComponent) ? nodeOrComponent.type.type : nodeOrComponent.type;
(0, _reactIs.isMemo) really confuse me. What's the meaning of this?
ps: I know (0, _reactIs.isMemo) this expression's value is _reactIs.isMemo
The comma operator there ensures that what's inside the parentheses is evaluated as an expression without a calling context.
To take a shorter example, if the code was:
var type = obj.fn(someArg);
then fn would be called with a calling context of obj. But the original untranspiled code, whatever it is, does not have such a calling context, so in order to be faithful to the original code, the calling context has to be removed, which can be done with the comma operator:
var type = (0, obj.fn)(someArg);
Another way of doing the same thing would be:
var fn = obj.fn;
var type = fn(someArg);
(but that takes more characters, so minifiers prefer the comma operator version)
This is a silly-looking minification trick that's often seen with imported modules. Usually, you'd only be looking at the source code, which won't have this sillyness.

If statement from string statement [duplicate]

This question already has answers here:
What's the main benefit of using eval() in JavaScript?
(15 answers)
Closed 4 years ago.
I would like to ask if it's possible to write an if-statement using a string and convert it somehow into a real statement?
I wish I could use "c==c" like if(c==c).
Is that possible?
var c=1;
var aa= "c==c";
if(aa) {
console.log("abc")
}
Yes, use Javascript's eval function https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval
Eval let's you run any string as valid Javascript code. However eval has a few downsides like performance and security since this can lead to vulnerabilities in your code if you let users eval any string they want.

Dynamically call function in javascript [duplicate]

This question already has answers here:
Calling function inside object using bracket notation
(2 answers)
Closed 6 years ago.
I rather have a seemingly trivial issue, but am not able to figure out an efficient approach.
I have a list of about 50 functions to be called such as :
globalClient.funcA(...)
globalClient.funcB(...)
globalClient.funcC(...)
My code should ideally dynamically create the name of the function (funcA / funcB/ funcC and then proceed to actually call that function. My approach below does not work (please note that these aren't exactly the actual names of the functions. I'm only giving these arbitrary names for simplicity of understanding):
var functionName = 'func'.concat('A');
globalClient.functionName
The second line is where it errors out. Now JS thinks that functionName itself is the name of the function. What I want it to do is resolve functionName to funcA and then call globalClient.funcA(...) instead.
I've thought about implementing a switch / case for this but I'm sure there is a far simpler appraoch. Any ideas?
You could use the bracket notation as property accessor.
globalClient[functionName]()
You can use the [ ] operator for accessing the properties.
var globalClient = {
funcA: function(){
console.log('funcA is called');
}
}
var functionName = 'func'.concat('A');
globalClient[functionName]();

String evaluation function in JavaScript [duplicate]

This question already has answers here:
How to convert string equation to number in javascript?
(5 answers)
Closed 8 years ago.
Is there any built-in function in JavaScript like eval built-in function in Python?
notice: eval function take an equation as string and returns result. for example assume variable x is 2, then eval("2x+5") returns 9.
Yes, there is eval function in JavaScript too.
Besides, the statement should be valid for evaluation, i.e. eval("2*x+5").
You should also note, that using eval in JavaScript is not recommended. You can read about at MDN.
REF: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/eval
Yes, it's called eval, oddly enough.
http://www.w3schools.com/jsref/jsref_eval.asp
Edit: the mozilla link from VisioN (https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/eval) is better, since it explains why you shouldn't use it.
You can use eval() however you will need to convert any "human" math operators to ones understood by javascript.
var sum = "4x5";
eval(sum.replace("x", "*"));
Update didn't read the part about x being a variable! that does make it slightly more complicated depending on how complex the equations are.

Why is the JavaScript RegExp.test() method behaving as a toggle? [duplicate]

This question already has answers here:
Why does a RegExp with global flag give wrong results?
(7 answers)
Closed 6 years ago.
Can anyone explain why the alert() in the following JavaScript code is firing? It appears to be a bug in the RegExp.test() method which reverses its previous decision each time you run the method. I'm using IE7.
I've found a replacement that appears solid, using the string.search(regex) method instead. But, I'm curious whether anyone knows something about this.
var styleHasWidthRegex = /\bwidth\s*\:/ig;
var styleText = "WIDTH: 350px";
var result1 = styleHasWidthRegex.test(styleText);
var result2 = !styleHasWidthRegex.test(styleText);
if (result1 == result2) {
alert("This should never happen!");
}
Your regex has the global (g) flag set. Every time it is executed, it'll update an internal index (the lastIndex property) specifying where it left off, and begin searching at that point the next time through.
Of course, you don't really want that - you want it to start at the beginning every time. So ditch the g flag.
See also: Inconsistent javascript logic behavior
In this scenario, you should be needing a global tag anyways, since in css declarations a property should only be declared once.

Categories

Resources