This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Let's use `eval` to calculate the maths expression:
Usemos `eval` para calcular la expresión matemática:
```js demo run
let expr = prompt("Type an arithmetic expression?", '2*3+2');
let expr = prompt("Escribe una expresión matemática:", '2*3+2');
alert( eval(expr) );
```
The user can input any text or code though.
Aunque el usuario puede ingresar cualquier texto o código.
To make things safe, and limit it to arithmetics only, we can check the `expr` using a [regular expression](info:regular-expressions), so that it only may contain digits and operators.
Para hacer las cosas seguras, y limitarlo a aritmética solamente, podemos verificar `expr` usando una [expresión regular](info:regular-expressions) que solo pueda contener dígitos y operadores.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
The built-in `eval` function allows to execute a string of code.
La función incorporada `eval` permite ejecutar una cadena de código.
The syntax is:
La sintaxis es:
```js
let result = eval(code);
```
For example:
Por ejemplo:
```js run
let code = 'alert("Hello")';
eval(code); // Hello
```
A string of code may be long, contain line breaks, function declarations, variables and so on.
Una cadena de código puede ser larga, contener cortes de línea, declaración de funciones, variables y así.
The result of `eval` is the result of the last statement.
El resultado de `eval` es el resultado de la última sentencia.
For example:
Por ejemplo:
```js run
let value = eval('1+1');
alert(value); // 2
Expand All
@@ -30,7 +30,7 @@ let value = eval('let i = 0; ++i');
alert(value); // 1
```
The eval'ed code is executed in the current lexical environment, so it can see outer variables:
El código evaluado es ejecutado en el entorno léxico presente, entonces podemos ver sus variables externas:
```js run no-beautify
let a = 1;
Expand All
@@ -46,69 +46,69 @@ function f() {
f();
```
It can change outer variables as well:
También puede modificar variables externas:
```js untrusted refresh run
let x = 5;
eval("x = 10");
alert(x); // 10, value modified
alert(x); // 10, valor modificado
```
In strict mode, `eval` has its own lexical environment. So functions and variables, declared inside eval, are not visible outside:
En modo estricto, `eval` tiene su propio entorno léxico. Entonces funciones y variables declaradas dentro de eval no son visibles fuera:
```js untrusted refresh run
// reminder: 'use strict' is enabled in runnable examples by default
// recordatorio: 'use strict' está habilitado en los ejemplos ejecutables por defecto
eval("let x = 5; function f() {}");
alert(typeof x); // undefined (no such variable)
// function f is also not visible
alert(typeof x); // undefined (no existe tal variable)
// la función f tampoco es visible
```
Without `use strict`, `eval` doesn't have its own lexical environment, so we would see `x` and `f` outside.
Sin `use strict`, `eval` no tiene su propio entorno léxico, entonces podemos ver `x` y `f` afuera.
## Using "eval"
## Usando "eval"
In modern programming `eval` is used very sparingly. It's often said that "eval is evil".
En programación moderna `eval` es usado muy ocasionalmente. Se suele decir que "eval is evil" - juego de palabras en inglés que significa en español: "eval es malvado".
The reason is simple: long, long time ago JavaScript was a much weaker language, many things could only be done with `eval`. But that time passed a decade ago.
La razón es simple: largo, largo tiempo atrás JavaScript era un lenguaje mucho más débil, muchas cosas podían ser concretadas solamente con `eval`. Pero aquel tiempo pasó hace una década.
Right now, there's almost no reason to use `eval`. If someone is using it, there's a good chance they can replace it with a modern language construct or a [JavaScript Module](info:modules).
Ahora casi no hay razones para usar `eval`. Si alguien lo está usando, hay buena chance de que pueda ser reemplazado con una construcción moderna del lenguaje o un [Módulo JavaScript](info:modules).
Please note that its ability to access outer variables has side-effects.
Por favor ten en cuenta que su habilidad para acceder a variables externas tiene efectos colaterales.
Code minifiers (tools used before JS gets to production, to compress it) rename local variables into shorter ones (like `a`, `b` etc) to make the code smaller. That's usually safe, but not if `eval` is used, as local variables may be accessed from eval'ed code string. So minifiers don't do that renaming for all variables potentially visible from `eval`. That negatively affects code compression ratio.
Los Code minifiers (minimizadores de código, herramientas usadas antes de poner JS en producción para comprimirlo) renombran las variables locales acortándolas (como `a`, `b` etc) para achicar el código. Usualmente esto es seguro, pero no si `eval` es usado porque las variables locales puden ser accedidas desde la cadena de código evaluada. Por ello los minimizadores no hacen tal renombado en todas las variables potencialmente visibles por `eval`. Esto afecta negativamente en el índice de compresión.
Using outer local variables inside `eval` is also considered a bad programming practice, as it makes maintaining the code more difficult.
El uso de variables locales dentro de `eval` es también considerado una mala práctica de programación, porque hace el mantenimiento de código más difícil.
There are two ways how to be totally safe from such problems.
Hay dos maneras de estar asegurado frente a tales problemas.
**If eval'ed code doesn't use outer variables, please call `eval` as `window.eval(...)`:**
**Si el código evaluado no usa variables externas, por favor llama `eval` como `window.eval(...)`:**
This way the code is executed in the global scope:
De esta manera el código es ejecutado en el entorno global:
```js untrusted refresh run
let x = 1;
{
let x = 5;
window.eval('alert(x)'); // 1 (global variable)
window.eval('alert(x)'); // 1 (variable global)
}
```
**If eval'ed code needs local variables, change `eval` to `new Function` and pass them as arguments:**
**Si el código evaluado necesita variables locales, cambia `eval` por `new Function` y pásalas como argumentos:**
```js run
let f = new Function('a', 'alert(a)');
f(5); // 5
```
The `new Function` construct is explained in the chapter <info:new-function>. It creates a function from a string, also in the global scope. So it can't see local variables. But it's so much clearer to pass them explicitly as arguments, like in the example above.
La contrucción `new Function` es explicada en el capítulo <info:new-function>. Esta crea una función desde una cadena, también en el entorno global, y así no puede ver las variables locales. Pero es mucho más claro pasarlas explícitamente como argumentos como en el ejemplo de arriba.
## Summary
## Resumen
A call to `eval(code)` runs the string of code and returns the result of the last statement.
- Rarely used in modern JavaScript, as there's usually no need.
- Can access outer local variables. That's considered bad practice.
- Instead, to `eval` the code in the global scope, use `window.eval(code)`.
- Or, if your code needs some data from the outer scope, use `new Function` and pass it as arguments.
Un llamado a `eval(code)` ejecuta la cadena de código y devuelve el resultado de la última sentencia.
- Es raramente usado en JavaScript moderno, y usualmente no es necesario.
- Puede acceder a variables locales externas. Esto es considerado una mala práctica.
- En su lugar, para evaluar el código en el entorno global, usa `window.eval(code)`.
- O, si tu código necesita algunos datos de el entorno externo, usa `new Function` y pásalos como argumentos.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Eval: run a code string #303
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Uh oh!
There was an error while loading. Please reload this page.
Eval: run a code string #303
Filter by extension
Viewed files
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
There are no files selected for viewing