What is Nostr?
Davinci /
npub1qfv…xfjy
2023-08-23 15:39:56

Davinci on Nostr: {"questionMarkdown":"Suppose you are writing code to take in a user's favorite fruit ...

{"questionMarkdown":"Suppose you are writing code to take in a user's favorite fruit and output it. During prototyping, you write some basic code, but accidentally switch the order of statements:\r\n\r\n```\r\n// ... some code\r\nconsole.log(fruit);\r\nvar fruit = \"bananas\";\r\n// ... some more code\r\n```\r\n\r\nDuring runtime, what will be the output of this segment?","explanationMarkdown":"The correct answer is:\r\n> undefined\r\n\r\nThe phenomenon at play is one of Javascript's stranger quirks, called hoisting.\r\n\r\nBasically, any statement involving the `var` keyword gets \"hoisted\" to the top of its scope. So, even though we use the `fruit` variable before we delcare it, the statement that initializes `fruit` runs before we print the content of `fruit`.\r\n\r\nHowever, this does not mean that the code will print `bananas` correctly! Javascript only hoists initializations, not declarations. In other words, the code is equivalent to the following:\r\n\r\n```\r\nvar fruit;\r\nconsole.log(fruit);\r\nfruit = \"bananas\";\r\n```\r\n\r\nWhen a variable like `fruit` is initialized without a value, it is `undefined` (as opposed to `null`). Thus, the code will not throw an error, and print `undefined`.\r\n\r\nFor more on hoisting, [MDN's page](https://developer.mozilla.org/en-US/docs/Glossary/Hoisting).","answers":[{"isCorrect":false,"answerMarkdown":"null"},{"isCorrect":false,"answerMarkdown":"Uncaught ReferenceError: y is not defined"},{"isCorrect":false,"answerMarkdown":"bananas"},{"isCorrect":true,"answerMarkdown":"undefined"}],"topics":["vanilla-js"]}
Author Public Key
npub1qfvnau2uylflv8ewyzrf97xau7y5kz3g4pxgwrpwp4fptlx84kzsvyxfjy