Home > Back-end >  Updated global variable not being passed into String
Updated global variable not being passed into String

Time:06-30

I'm getting this issue where I try to set a global variable inside a function and use a globally declared string with concatenation of the said variable.

When checked inside the method, the variable has been set correctly, but it's not detected in the concatenated String. What could be the reasoning behind this.

const axios = require('axios').default;
const express = require('express');

let environment;
let myUrl = `https://ets-tst-${environment}.mydomain.com/health`

app.get('/', function (req, res) {

    environment= 'dev'
    console.log(environment)  //prints dev
    console.log(myUrl) //prints https://ets-tst-undefined.mydomain.com/health
});

CodePudding user response:

As said in Mohamad answer you set environment after myUrl so when myUrl is evaluated environment is currently undefined.

However if you want to dynamically change myUrl you could do like so:

let environment;
let myUrl = (env) => `https://ets-tst-${env}.mydomain.com/health`

app.get('/', function (req, res) {
    environment= 'dev'

    console.log(environment)  //prints dev
    console.log(myUrl(environment)) //prints https://ets-tst-dev.mydomain.com/health
});

Here myUrl is an arrow function that takes an env string as param and returns the formatted url. Because now the formatted url string is evaluated when myUrl() arrow function is called!

You could also do:

let environment;
let myUrl = () => `https://ets-tst-${environment}.mydomain.com/health`

app.get('/', function (req, res) {
    environment= 'dev'

    console.log(environment)  //prints dev
    console.log(myUrl()) //prints https://ets-tst-dev.mydomain.com/health
}

Here you don't have to pass env param because when myUrl is called it gonna read the current value of environment which has been updated to 'dev' right above.

But I wouldn't recommand that because reading a global variable to create the string in that case could lead to unwanted behaviors if you don't keep track of the updates of environment var.
This is called a 'side-effect' and you should avoid it as described here

CodePudding user response:

you set environment after myUrl you can't set value in variable you can set before this like:

const axios = require('axios').default;
const express = require('express');

let environment = 'dev';
let myUrl = `https://ets-tst-${environment}.mydomain.com/health`

app.get('/', function (req, res) {

    console.log(environment)  //prints dev
    console.log(myUrl) //prints https://ets-tst-undefined.mydomain.com/health
});
  • Related