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?!

1
  • msg is part of the showmsg function scope which is not part of the inner function or global scope and therefore is undefined. Commented Sep 12, 2015 at 8:31

3 Answers 3

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

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

 showmsg();
Sign up to request clarification or add additional context in comments.

Comments

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

4 Comments

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 I think if AJAX call is being used, refer this question.
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
This is exactly what I am working on now and I have problem with data which I am getting from Ajax
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();

1 Comment

The best practice is to avoid global variables.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.