0

I have a script like this

function innerfunc(){
    console.log(msg);
}

function showmsg(){
var msg= "This is somthing"
 innerfunc();
}
showmsg();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

As you can see I am calling a function innerfunc() after declaring the msg but I am getting the

Uncaught ReferenceError: msg is not defined

error! As you can see I never call the method before declaring and assigning the msg so why this is happening?!

Suffii
  • 5,694
  • 15
  • 55
  • 92
  • msg is part of the showmsg function scope which is not part of the inner function or global scope and therefore is undefined. – Shikloshi Sep 12 '15 at 08:31

3 Answers3

1
 function innerfunc(msg) {
   console.log(msg);
 }

 function showmsg() {
   var msg = "This is somthing";
   innerfunc(msg);
 }

 showmsg();
BenG
  • 14,826
  • 5
  • 45
  • 60
Kaushik Maheta
  • 1,741
  • 1
  • 18
  • 27
0

There are different ways of achieving what you want.

  1. You can try to return values from function.

function innerfunc(msg){
  alert(msg);
}

function showmsg(){
  var msg= "This is somthing"
  innerfunc(msg);
}
showmsg();
  1. Set javascript global variable.

var msg;
function innerfunc(msg){
  alert(msg);
}

function showmsg(){
  msg = "This is somthing"
  innerfunc(msg);
}
showmsg();
rrk
  • 15,677
  • 4
  • 29
  • 45
  • Thanks Rejith R Krishnan but I can not use the global variable since I am getting some data from Ajax call. I mean I am not sure if it is doable there too? – Suffii Sep 12 '15 at 08:34
  • @Suffii I think if AJAX call is being used, refer this [question](http://stackoverflow.com/questions/5316697/jquery-return-data-after-ajax-call-success). – rrk Sep 12 '15 at 08:37
  • let me explain you a little bit more, I am getting some JSON data through `.done(function(data)` and I am running some functions based on these `data` now I want to create functions out side of the ajax call and just call them there – Suffii Sep 12 '15 at 08:38
  • This is exactly what I am working on now and I have problem with `data` which I am getting from Ajax – Suffii Sep 12 '15 at 08:52
0

If you want that, you should use @Rejith R Krishnan solution, or use global variables.

var MSG = "";

function innerfunc(){
    console.log(MSG);
}

function showmsg(){
MSG  = "This is somthing"
 innerfunc();
}
showmsg();
Víctor
  • 3,029
  • 3
  • 28
  • 43