'Node js variable is not working in outside function

Can anyone tell me how I can use var dataTitle outside of axios?

express = require('express') / 
const bodyParser = require('body-parser')
const axios = require('axios');
var randomInt = require('random-int');
const URL = 'url';
var randomNumber = randomInt(11)
axios.get(URL + randomNumber)
.then(function (response) {
var dataTitle = response.data.question;
console.log(dataTitle)
})
.catch(function (error) {
console.log(error);
});


Solution 1:[1]

It seems your question is about variables scope in JavaScript. You cannot use a variable outside of the function which is declared inside of the function. So, you have to declare it before than axios and use it in the axios as below:

express = require('express');
const bodyParser = require('body-parser');
const axios = require('axios');
var randomInt = require('random-int');
const URL = 'url';
var randomNumber = randomInt(11);

var dataTitle;

axios.get(URL + randomNumber)
.then(function (response) {
     dataTitle = response.data.question;
     console.log(dataTitle)
})
.catch(function (error) {
     console.log(error);
});

Solution 2:[2]

Adding on top of Pouya Jabbarisani's answer, Since axios.get returns a promise and has asynchronous behavior, console.log(dataTitle) outside of function will still result in undefined.

In order to get the real value, use await axios.get(...).
Also, you need to make the wrapping function async.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Pouya Jabbarisani
Solution 2 SherylHohman