0

I am using the fetch API. I got stuck trying to print the result of the response as I kept getting undefined. Then I copy and pasted the first example in the mozilla docs on fetch and it worked. I played around with the code and noticed that the reason I was getting undefined is because I had curly brackets around the content of the arrow function expression.

fetch(...url)
.then((response) => {response.json()})
.then((data) => {console.log(data)})
// console.log() prints undefined

fetch(...url)
.then((response) => response.json())
.then((data) => console.log(data))
// console.log() prints the expected json output

Why does adding curly brackets result in console.log() outputting undefined in the first snippet?

Valachio
  • 1,025
  • 2
  • 18
  • 40
  • with `{}` you need to write `return` like this `.then((response) => { return response.json()})`. if you don't use curly brakets then it will automatically return the value (the importnat thing is to have one line code to return (when without {}) – Laaouatni Anas Sep 21 '22 at 20:56
  • 1
    Why would adding them _not_ change the output? See e.g. https://stackoverflow.com/q/39629962/3001761, https://stackoverflow.com/q/52430105/3001761, ... – jonrsharpe Sep 21 '22 at 20:56
  • 1
    Please research your inquiry before posting in accordance with [ask]; this is a duplicate of [Arrow function without curly braces](https://stackoverflow.com/questions/39629962/arrow-function-without-curly-braces) – esqew Sep 21 '22 at 20:57
  • see here how it will be with `return` https://jsfiddle.net/g1q4f7c5/ , I hope this helped you, good coding – Laaouatni Anas Sep 21 '22 at 21:01

0 Answers0