Javascript Helper Functions 7/11 - console.log outside of curly brace

Hello all.
I’ve been flowing through the codecademy course for the past couple of months. Initially HTML, then CSS and now Javascript. I’ve referenced back to these a number of times and they’ve helped fill in the knowledge gaps - thank you to all that have contributed.
However, Javascript is proving a little trickier and I have a query (and I guarantee I’ll have further queries!).

I’m currently having a little trouble understanding (or verbalising it to myself) the following:

https://www.codecademy.com/courses/introduction-to-javascript/lessons/functions/exercises/return-ii?action=resume_content_item

Working through the four check points I managed to get them all successfully ‘ticked’ but with an issue. This code shows up an error message (even though, as mentioned above, I pass the task:

function monitorCount(rows, columns) {
  return rows * columns;
}
function costOfMonitors(rows, columns) {
  return monitorCount(rows, columns) * 200;
  const totalCost = costOfMonitors(5, 4);
}
  console.log(totalCost(5, 4));

Which shows this error message:


/home/ccuser/workspace/helper-function/main.js:8
console.log(totalCost(5, 4));
            ^

ReferenceError: totalCost is not defined
    at Object.<anonymous> (/home/ccuser/workspace/helper-function/main.js:8:13)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.runMain (module.js:605:10)
    at run (bootstrap_node.js:427:7)
    at startup (bootstrap_node.js:151:9)
    at bootstrap_node.js:542:3

If I place the console.log within the curly brace as so:

function monitorCount(rows, columns) {
  return rows * columns;
}
function costOfMonitors(rows, columns) {
  return monitorCount(rows, columns) * 200;
  const totalCost = costOfMonitors(5, 4);
console.log(totalCost(5, 4));
}

I obviously need to read up more but an obvious pointer as to why it’s wrong to place the console.log outside of the curly brace would be hugely helpful (it’s a bit of a blockage in my learning).

Kind regards.

You say that almost as if that curly brace is some random obstacle in your code file that needs to be dodged but doesn’t have any meaning.

Maybe it’s not so much about which side of a curly brace something is, but rather about whether something should or should not be inside a particular function. Maybe it should be deleted if you don’t know when it should be executed?

If you were a bit more deliberate about what you were writing, I don’t think you’d be able to form the question.
Here’s my function. It’s supposed to do these three things. Done.

What does a function look like? Where does its code begin, where does it end? The code of a function should go in somewhere between there, yes? So what should go into the function, what should the function do? There should be those things, and only those things.


I suppose what I’m saying is that you shouldn’t be reasoning about syntax. You should be reasoning about what you’re modelling, the concept.

And then if you don’t know what a function looks like by the time you need to write a function, well, you’d have to look it up, there’s no way around that. But by the time you’re at this stage you should already have made a decision about what the function is doing.

2 Likes

As a general rule, I find the Mozilla docs to be incredibly helpful with most things. They do a really good job of explaining stuff.

Your problem is one of “scope”.

Here’s an example:

const monitor_cost = 180;
var number_of_monitors = 3;

function totalMonitorCost(unit_cost, unit_qty) {
    const shipping_cost = 10;
    let total_cost = (unit_cost * unit_qty) + shipping_cost;
    return total_cost;
}

Here, both my const monitor_cost and var number_of_monitors declarations are at the “top level” - that is, they aren’t declared within a { code block } (which could be a function, an if-else… anything with curly braces). This makes them global in scope - they can be accessed from anywhere in the code.

When you declare a const or use let to declare a variable, both of these are what’s called block-scoped. That is, they’re only available inside of the code block where they’re declared.

If we revisit my example:

const monitor_cost = 180;
var number_of_monitors = 3;

console.log(monitor_cost); // 180
console.log(number_of_monitors); // 3

function totalMonitorCost(unit_cost, unit_qty) {
    const shipping_cost = 10;
    console.log(shipping_cost); // 10
    console.log(monitor_cost); // 180
    let total_cost = (unit_cost * unit_qty) + shipping_cost;
    return total_cost;
}

console.log(monitor_cost); // 180
console.log(shipping_cost); // undefined - shipping_cost only exists within the "totalMonitorCost" function!

If we go back to your code, specifically your declaration of the costOfMonitors function:

function costOfMonitors(rows, columns) {
  return monitorCount(rows, columns) * 200;
  const totalCost = costOfMonitors(5, 4); // declared WITHIN the function, so only exists inside the { }
}
  console.log(totalCost(5, 4)); // I don't exist yet in this scope!

As @ionatan said:

You’re asking the question

why it’s wrong to place the console.log outside of the curly brace

Are you sure that’s all that’s wrong?

Edit: Can tell I haven’t had my coffee this morning…

Didn’t immediately notice that your erroneous line is actually a function call. I’m leaving the stuff about variable scoping, as it may still prove helpful to you in the longer run, but - definitely as ionatan pointed out - you might want to revisit that function. :slight_smile:

2 Likes

Thanks very much. As it happens, I’m just reading up on scope and closures via this site (https://css-tricks.com/javascript-scope-closures/). I’ve come across those Mozilla docs so I’ll continue looking art them.
I’ve also ordered a book on Javascript ( JavaScript and JQuery: Interactive Front-End Web Development by Jon Duckett) just so I can digest via a different medium than online.

Bit of a steep learning curve (I don’t have any real programming background) and I’ll be asking questions oftentimes that I potentially have the answer to in front of me - so apologies for that.

I think where this task threw up a curveball is that usually the task will not let you move on if there’s the slightest of syntax errors then you won’t ‘pass’ the task (green/blue tick) but placing the console.log outside of the bracket throws up the error message but allows the task as completed (also noted the use of under score instead of camel casing above, which I presume is another way of writing. I’m quite fastidious so I’m hoping that is to my favour with coding.

All that code I posted above printed no ouput to the cosole (should be 20) but at the same time everything was ‘checked’ with the tick as passed.
However, I’ve refreshed both the task and the browser and started again using the following code:

function monitorCount(rows, columns){
return rows * columns
};
const numOfMonitors = monitorCount(5, 4);
console.log(numOfMonitors);

And this time I get the console printing ‘20’ and all the tasks passed. I think I had a late night with it all and the task in the browser was acting rather strange.

So - restarting has cleared the task and my mind somewhat.
At thw very least I’ve started a conversation/said hello on here as I’m sure I’ll be having further ‘headaches’ in the future.
I’ll continue looking through the Mozilla docs, CSS-tricks, the book and any other help I can grab. I’m starting a full on night school course in all this next month but want to get my ‘homework’ in early.

Kind regards.

I’m personally of the opinion that there are no stupid questions. Sure, sometimes people will ask a fairly trivial question - but a lot of the time, merely thinking about how to frame the question causes the “penny to drop” and you can answer it yourself. Otherwise, if you’re asking questions you’re trying to learn - which is infinitely better than not asking and ignoring the problem.

One thing I’ll say is that, as brilliant as the exercise environment is on Codecademy you’ll find that every now and again it will do something weird that makes you ask “wth is going on?!”. Sometimes it’ll give you a pass with code that’s slightly off, sometimes it won’t let you progress with a perfectly correct solution… Part of it is I think down to how they verify the tasks behind the scenes (the verifier can be an absolute stickler for “type this EXACTLY!!”), but usually these little blips can be easily fixed.

I don’t know if there’s a definite style guide for JavaScript. As a rule, I don’t particularly think it matters (nor do I personally care) whether you write variables like variable_name or variableName or vArIaBlEnAmE… well, maybe I do care if you do the last one 'cause it’s ridiculous. “How” you ought to name variables, functions etc can be subject to intense debate - but ultimately, the important thing is consistency. If you’re writing code just for you, use whatever naming convention you want but stick to it. If you’re working with a team on a larger project, use whatever is dictated by the project and stick to that.

It’s why the forums are here, so we can help where we can. :+1:

:slight_smile:

1 Like

Thanks very much thepitycoder -that’s a wonderfully informative answer/response.

I’m not particularly averse to a challenge and all this (being almost completely new to programming in this sense) is definitely dipping my toes in very cold water.
As mentioned above I’m a bit of a stickler for detail (some would say mild OCD, but knowing people with genuine OCD I’m not sure that’s fair on them) so would happily keep track of my own style guide (for writing variable)…the semi-colon on the end of ‘lines/functions’ (see, I’m not even at the stage when I can name them correctly yet!) I’m quite conscious of.

I enjoyed the HTML/CSS course as I’m quite a visual person (background more music/audio/design) and although I’m finding even rudimentary Javascript a little taxing I’m starting the appreciate the hidden beauty in it (there…I said it!!).

Anyway, thanks very much once again…I’m sure I’ll be here more than a few times…!

Kind regards.

1 Like

Hello!

I got stuck in there too. Following the instructions I wrote the same code and got the same error (with all the points checked) as you did first.

But then, by following the instructions, I noticed the expected output is the COST of the monitors (4000) not the amount of them (20).

I wrote the following code getting all the points checked and no errors:

function monitorCount(rows, columns) {
return rows * columns;
}

function costOfMonitors(rows, columns) {
return monitorCount(rows, columns) * 200;
const totalCost = costOfMonitors(rows, columns);
};

console.log(costOfMonitors(5, 4));

I hope it helps.

(UPDATE after a double check)

function monitorCount(rows, columns) {
return rows * columns;
}

function costOfMonitors(rows, columns) {
return monitorCount(rows, columns) * 200;
};

const totalCost = costOfMonitors(5, 4);

console.log(totalCost);

It was a scope problem at declaring the variable totalCost. It should be declared after the brackers then logged into the console.

I meant “brackets” not “brackers” :sweat_smile: