0

Hello i am a beginner in JAVASCRIPT and i want to learn more about functions with parameters; i have problem in the second case the console write that sayhello it is not a function ( how can i fix this letter code please)

var gender = prompt('are you mr or ms')
if (gender === 'mr') {
  function sayhello(name, gender) {
    return ('hello' + gender + name + ' how are you today')
  }
  console.log(sayhello(' mike', " mr "))
} else {
  console.log(sayhello(' emmy', " ms "))
}
Not A Bot
  • 2,474
  • 2
  • 16
  • 33
amina NBA
  • 23
  • 5
  • 1
    declare `sayhello` outside the scope of the prompt. As far ar you can – ffflabs Mar 30 '21 at 12:01
  • 2
    You declared the `sayhello` function inside the `if` statement, so on the `else` statement you will not have acces to the scope of the `sayhello` function. – Pablo Silió Mar 30 '21 at 12:02
  • In the old days this used to work (albeit very illogical). [But that is no longer the case](https://stackoverflow.com/questions/10069204/function-declarations-inside-if-else-statements). – Ivar Mar 30 '21 at 12:22

2 Answers2

2

Define your function sayhello outside if-else

When you define your function sayhello inside the if statement, you are limiting the scope of your function sayhello.

This means that, if any other part of your program wants to access the sayhello function, it won't be able to access it due to the limited accessibility of your function.

var gender = prompt('are you mr or ms')
if (gender === 'mr') {
  console.log(sayhello(' mike', " mr "))
} else {
  console.log(sayhello(' emmy', " ms "))
}

function sayhello(name, gender) {
    return ('hello' + gender + name + ' how are you today')
}
Not A Bot
  • 2,474
  • 2
  • 16
  • 33
0

Your function is in the if statement. I mean only if gender is equal to 'mr' you define a function. Take your function up one level outside if and it will work.