What happens with this javascript function code

from a node js tutorial, instructor declares output but then keeps on redclaring it and then returns output. I would of thought that because output keeps getting re declared when the function returns output it will only return the result of the last line with replace. This doesnt seem to be the case, how does the code work. if the code is too out of context let me know and i will provide more code

 let replacer = (temp, replacedwith) =>{
 let output = temp.replace(/{placeholder}/g,replacedwith.id)
 output = temp.replace(/{other}/g,replacedwith.id)
 output = temp.replace(/{something else}/g,replacedwith.id)
return output

}```

Absolutely. It is easy to test.

const getOutput = () => {
  let output = '111'
  output = '222'
  output = '333'
  return output
}

console.log(getOutput())
// 333

I wouldn’t say “redeclared” - it is having its value changed. output is only declared once, with the let statement. But your assessment is basically correct. It is declared and initialized. Then its value it changed. Then it is changed again. The only change that will have any affect is the last one.

Usually that code would make little sense, why would you first declare a variable and assign a value to it, only to reassign it again and again right afterwards.

But if that’s from a tutorial, I could imagine that the instructor first showed what the result is with the first value assigned. Then changes the value a couple of times and shows how that changes the result.

here is more of the code , i put the comments in to help explain my confusion


let fs = require("fs")

let http = require("http")

let url = require("url")

let server = http.createServer((req,res)=>{

let read = fs.readFileSync(`${__dirname}/txt/test.json`,"utf-8")

let readtemp = fs.readFileSync(`${__dirname}/templates/index.html`,"utf-8")

let data  = JSON.parse(read)

let replacer = (temp, replacedwith)=>{

 let output = temp.replace(/{placeholder}/g,replacedwith.id)

 output = temp.replace(/{other}/g,replacedwith.id)

 output = temp.replace(/{something else}/g,replacedwith.id)

return output

}

    if(req.url == "/test"){

       let cardshtml = data.map(x => replacer(readtemp, x)

       // so idea is to loop over the json file (data)and for each element in json run the replacer function. the replacer function

      // takes in  html file(readtemp) and the function replaces the given placeholder with the JSON elmenent (x)

      // but how is this possible when the output variable keeps getting reinitialized, its not as if there is an if statement

       )

       console.log(cardshtml)

      

            res.writeHead(200,{

                "Content-type": "text/html", 

                "somethign" : "soemthign"

            })

            

            res.end(readtemp)

    }

  else{

      res.end("ok")

  }

})

server.listen(8000,"127.0.0.1")

It might make more since if the three lines above were written as:

let output = temp
  .replace(/{placeholder}/g,replacedwith.id)
  .replace(/{other}/g,replacedwith.id)
  .replace(/{something else}/g,replacedwith.id)

The above would apply the first replace to temp, the second replace would apply to the result of the first replace, and the third replace would apply to the result of the second replace. Finally, the result of the third replace would get assigned to output.

A longer version of the above would replace the last two lines of the code you supplied with:

 let output = temp.replace(/{placeholder}/g,replacedwith.id)
 
 output = output.replace(/{other}/g,replacedwith.id)

 output = output.replace(/{something else}/g,replacedwith.id)

Honestly, I am just guessing because I am not sure what the actual requirement is for the replacer function.

1 Like

thanks, yes that makes sense to me too but does seem to work for the instructor, i dont know why, ill double check i have not written something incorrectly

Do you have a link to the tutorial?

paid udemy unfortunately

looked at this again this morning and it seems to make more sense . I did the following

let replacer = (temp, replacedwith)=>{

 let output = temp.replace(/{placeholder}/g,replacedwith.id)

 output = output.replace(/{other}/g,replacedwith.id)

 output =  output.replace(/{something else}/g,replacedwith.id)

return output

}
function replaceAnimal (animal){
    let newAnimal = animal.replace("dog","cat")
    newAnimal = newAnimal.replace("bears","gifraffes")
    newAnimal = newAnimal.replace("elephants","lions")
    return newAnimal
}


console.log(replaceAnimal("dogandbearsandelephants"))
//catandgifraffesandlions

and i guess you can just keep using replace on newAnimal and when you return it will have replaced all the things you want to replace so the same should apply for the original code

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

Yeah, that looks a lot better. As Randy pointed out, those methods could be chained together, but that’s more of a style choice.

1 Like