Group Chat Week 2 Solutions
These were actually all kind of tough! Good job if you managed to figure these out :)
- Why doesn’t this code output “Hello Adam!” to the console (right hand side of the screen)?
We’re not actually using (invoking) this function! We need to call it underneath (e.g. sayHello(adam)).
The name variable is coming from the function argument here, not from the name variable that we defined at the top.
This isn’t a problem with scope, because the name variable at the top is a global variable (accessible inside the function).
- Why does this code only output “Hi”, rather than saything the user’s name too?
This is a problem with scope. The name variable is defined with a local scope, so it doesn’t get passed outside the function (it lives in a totally different world). We get the name “Adam” back from calling the greetUser() function, but we’re not doing anything with it.
One solution could be to store the result in a variable, and then you can log that. For example:
const name = greetUser()
console.log("Hi " + name)
- Why does this code end up logging undefined to the console?
let name = "Adam"
is a declaration, not an assignment. Whenever we use let someVariable
, we’re saying, “give me a brand new box called someVariable
”.
So here, we’re making an empty box at the top called name with let name
, and then when setName()
gets executed, we’re making a new variable called name with a local scope, and then that’s it!
If we change let name = "Adam"
to name = "Adam"
, then this will work! This will assign the value of the global variable at the top, rather than creating a new one.
- Why doesn’t this code correctly calculate (((1 + 1) + 2) * 3)?
For one thing, addTwo()
is simply returning 2 no matter what, not adding two to whatever gets passed in.
We’re not using the num argument for addOne()
either. We’re using the firstNumber
global at the top, no matter what we pass in.
Fixing these two errors should make this work!