I am trying to call recursively another function "cityname()" with switch case#1 and I am getting
"TypeError: cityname is not a function"
the purpose is to give users option to enter the City name again and again if the user requests.
Note: I have excluded the other cases which are working fine.
import axios from "axios";
import readlineSync from "readline-sync";
cityname()
function cityname(){
const apiKey = 'xyz';
var name = readlineSync.question(`Enter City Name:n`);
return getWeatherData(name,apiKey)
})
function getWeatherData(cityname, apiKey) {
axios.get(`https://api.openweathermap.org/data/2.5/weather?q=${cityname}&appid=${apiKey}`)
.then((res)=>{
let data = res.data
var options = readlineSync.questionInt(`Select an option below for ${cityname}n
1. Change Cityn
0. Exitn`)
switch(options)
{
case 1: cityname();
case 0: console.log('Exiting the program...');
break;
default:
console.log('Invalid option. Please try again.');
break;
}
})
}
2
Answers
The issue you’re facing is due to the way you’re trying to call the cityname() function recursively inside the switch statement. In JavaScript, function declarations are hoisted, but only within their scope. In your case, the function declaration for cityname() is placed after the function call cityname() itself, resulting in the "TypeError: cityname is not a function" error.
To fix this issue, you can use function expressions instead of function declarations. Here’s the modified code:
By using a function expression (const cityname = function () { … }), the function is defined before it’s called, resolving the "TypeError" issue.
Please note that the modified code assumes you have the necessary dependencies (axios and readline-sync) properly installed and imported.
You just need to change your argument named
'cityname'
to something else, as it shadows (conflicts in your case) with the function with same namecityname()
. I have renamed the argumentcityname
tocityName
.Here is the updated code of yours