Home > Back-end >  Call a function in another funtion
Call a function in another funtion

Time:09-07

I want to get the first name of a customer and use that in other functions.

I have an address:

John Doe Streetname 1 1234AA Village

function firstName(){
        let address = "John Doe\nStreetname 1\n 1234AA Village";
        let firstname = adres.split(' ')[0]; 
    }

function customerText(){
   firstName();
   let text = "Dear " firstname ", how is life?";
   alert(text);
}

So that the result would be: Dear John, how is life?

But unfortunately, it doesn't. Don't know how this should work?

CodePudding user response:

return the firstname and use it in the second function

function firstName(){
  let address = "John Doe\nStreetname 1\n 1234AA Village";
  let firstname = address.split(' ')[0]; 
  return firstname;
}

function customerText(){
   let text = "Dear " firstName() ", how is life?";
   alert(text);
}

// call your function
customerText();

OR pass firstname as parameter to the second function

function firstName(){
  let address = "John Doe\nStreetname 1\n 1234AA Village";
  let firstname = address.split(' ')[0]; 
  customerText(firstname);
}

function customerText(nameParameter){
   let text = "Dear " nameParameter ", how is life?";
   alert(text);
}

// call your function
firstName();

CodePudding user response:

Here is the modified code: I hope this will help you.

  function firstName() {
            let address = "John Doe\nStreetname 1\n 1234AA Village";
            let firstname = address.split(' ')[0];
            customerText(firstname)
        }


        function customerText(fname) {
            let text = "Dear "   fname   ", how is life?";
            alert(text);
        }
        firstName()

CodePudding user response:

You can get the return value of the fName() in customerText() function and put it right into the text.

    function fName(){
      return 'Robert'
    }
    function customerText(){
      return `Hi, ${fName()}, how are you :) ?`
    }

    console.log(customerText())

  • Related