-3

** Placing My actual JS snippet" I have a small JS function in one JS file as below

   function interest(customerRef) {
   try { 
      var customerInterest = "";         
      var baseUrl="https://test/"
      var url = baseUrl+customerRef           
      var username = "username";
      var password = "password";

      var request = new XMLHttpRequest();
      request.open("GET", url);
      request.setRequestHeader("Authorization", "Basic " + btoa(username+":"+password))
      request.send()
      request.onload=()=>
      {               
           if(request.status==200)
           {                    
                var guestJson = JSON.parse(request.response);                
                var sessions = guestJson.sessions || [];               
                var interest = sessions.filter(session => session.events)
                     .flatMap(session => session.events)
                     .filter(event => event.type === "SEARCH")
                     .map(event => event.arbitraryData.interest)[0];     
                customerInterest = interest;   
                alert("---"+customerInterest);
           } 
           else
           {
                console.log(`error ${request.status} ${request.statusText}`)
           }
      }  
      alert(customerInterest);
      return customerInterest;
 }
 catch (error) {
      console.error(error);
 }     
 }

I am calling the above function in my HTML file as below

  customerRef = "6a789727"          
  var interest1 = "";
  interest1 = interest(customerRef);
  console.log(interest1);

I am not getting any value in "console.log(interest1)" or "alert(customerInterest);" before the return. But i am getting the expected value in "alert("---"+customerInterest);"

Jey
  • 2,137
  • 4
  • 22
  • 40

1 Answers1

1

No, you'll get an error, not just undefined.

Running

var test = "";
test = test()
console.log(test)

will yield an

Uncaught TypeError: test is not a function

at line 2, since you just defined test to be a string ("") instead of a function you could call.

Instead, try something like:

function greet() {
 return "Hi";
}
var test = "";
test = greet();
console.log(test);

If you evaluate this in the console, this will print out

Hi
undefined

; the latter undefined comes from the return value of console.log();

AKX
  • 152,115
  • 15
  • 115
  • 172
  • Thanks AKX. I have updated my actual snippet where i am facing the issue. Can you help me what i am doing wrong? – Jey Sep 06 '22 at 21:05
  • @user1428019 Why on _earth_ did you not post your actual code to begin with? – AKX Sep 07 '22 at 05:06