1

When an alert() method is in double quotes it behaves like a string, meaning when it is printed in the console, the console screen shows the alert(). But i want, when there is an alert() in console.log(), to show an alert box. I have written the following piece of code but it does not fulfill my requirements:

var msg="alert("welcome")"
console.log(msg)

When I run the above code, the output to the console is alert("welcome") and no alert box is created. Could anyone help me figure out how to show an alert box?

Thanks

Angelos Chalaris
  • 6,611
  • 8
  • 49
  • 75
Debasish
  • 322
  • 6
  • 23

3 Answers3

3

If you want to do two things, you need code to do two things. If you want to do two things with one statement, you need to make a function that does both things for you.

function doubleAlert(msg) {
  console.log(msg);
  alert(msg);
}
Erik
  • 3,598
  • 14
  • 29
  • Thanks@Erik , but you can't understand my problem , i want a alert box which contain only **welcome** , when i call the **msg** in consol.log , means simultaneously the inner code will be execute . – Debasish Jun 15 '16 at 08:26
1

You should use the eval() function:

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 msg = "alert(\"welcome\")"; // Sample message.
console.log(msg);             // Log to the console regardless.
eval(msg);                    // Evaluate the message as an expression.
// Alternatively, regarding your comment about the message being altered, you can do one of the following:
var msg = "alert('welcome')";
console.log(msg);
eval(msg); 
// Or:
var msg = 'alert("welcome")';
console.log(msg);
eval(msg); 
// Or even:
var msg = 'alert(\'welcome\')';
console.log(msg);
eval(msg); 
Angelos Chalaris
  • 6,611
  • 8
  • 49
  • 75
  • Thanks@Angelos Chalaris , for reply but we can't change the string format means in **msg** we can't insert **\** in to the msg – Debasish Jun 15 '16 at 08:32
  • I did not insert anything in the message. In fact all I did was escape the quotations in order not to terminate the string so that it is not `"alert("` `welcome` `")"` but instead `alert("welcome")`. Alternatively, you can do `var msg='alert("welcome")'` or `var msg="alert('welcome')"` with the same result. - **EDIT:** @Debasish check the code now with more possible variations of how you can make a valid `msg` that contains quotes. – Angelos Chalaris Jun 15 '16 at 08:35
  • Thanks@Angelos Chalaris , it is working for me and solve my problem , thanks again. – Debasish Jun 15 '16 at 08:39
0

Try this

function alertAndConsole(msg){
    alert(msg);
    return msg;
}
console.log(alertAndConsole("WELCOME"))
Sabith
  • 1,628
  • 2
  • 20
  • 38