Wrapping JavaScript lessons within functions

I quite often add additional code into lessons and one of the things I most often do now is to wrap lessons within functions to add value to each lesson, to leverage the lesson to play and refactor with alternative code or patterns.

Sometimes I will take a lesson offline, into Visual Studio Code (for example), embellish it, then bring it back into the Codecademy editor to Save and Submit… but the editor may reject it. Such as with some recent code, where it says “Oops, try again. Did you declare a variable called junk?”. As you can see below, “junk” is wrapped within a function:

// You are now declaring an array.
// Arrays are an awesome data structure!
function junkieArray() {
    var cat = "cat";
    var junk = ["pig", "cow", 1, 2];
    junk.push ("dog", cat);
    console.log (junk);
};
junkieArray(); // [ 'pig', 'cow', 1, 2, 'dog', 'cat' ]

The Console outputs correctly but the Codecademy engine doesn’t recognize the “junk” variable. It would be great if the course engine could recognise all valid code. This would allow a lot more flexibility and the opportunity to ask “what if…”.

Cheers

Try making the two global variables,

Eg.

Outside of your function,

var junk = ["pig","cow",1,2]; 
var cat = "cat"; //Global Variables
function junkieArray() {
    junk.push ("dog", cat);
    console.log (junk);
};
junkieArray(); // [ 'pig', 'cow', 1, 2, 'dog', 'cat' ]

Thanks, bandit.

Putting the variables outside the function is a better work around than commenting out the function, which is what I was doing :slight_smile:

However, I was hoping Codecademy would consider enhancing the editor so that it would be able to check inside a function to see if the required code was there.

Cheers

1 Like