Codecademy: Javascript - Code Your Own Adventure/Adding Some Story ERROR! :( - javascript

Oops, try again. Make sure your string is correct and is between quotation marks!
This is the error that I keep receiving on Part 3: "Adding Some Story" of the second course on Javascript via Codecademy.com--"Code Your Own Adventure".
Here is what I have prior to adding a single line for this section--
confirm("I am ready to get silly!");
var age = prompt("What's your age");
if( age < 13)
{
console.log=("You are allowed to play, but I take no responsibility.");
}
else
{
console.log=("GO GET CRAZY!");
}
Then, the instructions are written as--
Under all your previous code, print out the following introduction, exactly as it is written.
"You are at a Justin Bieber concert, and you hear this lyric 'Lace my shoes off, start racing.'"
Print the introduction using console.log. Remember that the introduction is a string, so make sure to keep it between quotes.
So then I add in:
console.log=("You are at a Justin Bieber concert, and you hear this lyric 'Lace my shoes off, start racing.'");
And I continue to get the same error I mentioned above:
Oops, try again. Make sure your string is correct and is between quotation marks!
This continues to happen no matter what sorts of variations of the "introduction" I try to input. Please help!
Here is a link to the course page of this lesson.

Remove the = in console.log=("...");. console.log() is a method that you can invoke by passing data (in your case, a string) as parameters within the parentheses. = is the assignment operator and it's not used when invoking functions/methods.

console.log is a function. It essentially is the function log in the class console. So if for example you made a class food and a function cook in that class, you'd call it like: food.cook()
With that explained, console.log("...") is the format you want. Exactly how you used prompt("What's your age") just without a return variable.

Related

Is there any difference between java script if/else and c++ if/else?

I was wondering that is the if/else statements in js different or the same as c++.I have worked in c++ and the if/else conditions work as automatically break is put in that if one condition is true the other doesn't work but in js, the conditions were printed again and again.even though the item is found the else part is shown in the next iteration
var A = ["cake","apple pie","cookie","chips","patties"];
var search=prompt("Welcome to ABC Bakery.What do you want to order Sir/Ma'm");
var size=A.length;
for(var i=0;i<=size;i++)
{
if(search===A[i])
{
alert(search+" is available at index "+(i+1)+" of our bakery");
check=true;
break;
}
else
{
alert("We are sorry "+search +" is not available in our bakery");
}
}
C++ and JS have very different tastes in foods, which is why you might be experiencing oddness in your if/else statements. I have found that C++ tends to stick with the staples like bread, eggs, and oysters, whereas js prefers more exotic foods like almond butter.
In your case, though, I'm not convinced that the food has anything to do with the problem you are seeing. The break keyword functions similarly in both languages. Without knowing what food you are requesting, it is not possible for me to know what you're seeing versus what you would expect, but my guess is that when you enter a food that exists in A but is not the first food (in this case cake, which you should avoid except for special occasions but I'm not a licensed nutritionist so take that with a pinch of salt), then you are seeing a number of "We are sorry..." messages followed by the "...is available..." message. That is because you are looping over the elements of A, and are triggering the else statement each time, until the if statement is finally true and your break is triggered.
Instead what you want is to check if the food is really in the store at all, and in that case get its index. Otherwise I'd recommend placing an order with your distributor because it sounds like your customers are really clamoring for it and you don't want a riot on your hands. I think we all learned that from the great Toilet Paper Fiasco of April 2020. As a foodie myself, here's what I would do instead of your loop.
var index = A.indexOf(search);
if (index > -1) {
alert(search+" is available at index "+(index+1)+" of our bakery");
check=true;
}
else {
alert("We are sorry "+search +" is not available in our bakery");
}

Why does this error- and warning-free statement not complete?

I'm making a simple JavaScript for opening a dialog with a hypothetical recruiter. When I run the script it does not complete, but neither throws any errors or warnings. At least (!) it doesn't seem like it completes, but it might be me not thinking straight about how to use Firebug.
Here's the code:
var str = prompt("How are you today?", "I'm quite alright, thank you")
if (str.search(/\+alright\i|\+good\i|\+fine\i|\+alright\i/) != -1) {
alert("I'm very glad to hear that! Me, I'm feeling freaky today!");
} else if (str.search(/\+not/&&(/\+well|\+good/)||(/\+sad|\+down|\+blue/)) != -1) {
if (confirm("I'm sorry to hear that! Perhaps you'd like to get together and talk sometime?")) {
var sadNumber = prompt("What's your phone number? (The one entered is mine, feel free to call me!)", "072-");
if (sadNumber.search(/\D/) != -1) {
alert("Sorry, I think there's something wrong with your number. Try entering it with just numbers please!");
sadNumber = prompt("What's your phone number? (The one entered is mine, feel free to call me!)", "072-");
} else {
alert("That's fine! Let's move on with our job questions, shall we?");
}
} else if (alert("Wow! I didn't expect that answer! Truly interesting"));
}
Tried methods
This is what it looks like in Firebug:
After running, this is where the statement stops for some reason. Pressing continue breaks and steps out of the statement:
Stepping through, the statement continues to run, but skips all the (I conbsider) important parts. As you can see here, the alert is being skipped, and statements continues at the else if line:
My guess it that my regexp search (either the method, pattern, or modifiers) is wrong and that's why the statement breaks. I'm still finding it odd, though, since regexp errors usually throw errors or warnings, but this script returns none.
Anyone knows why this particular script breaks? Anyone having a good methodology for debugging errors that do not throw errors or warnings?
Your regular expressions are wrong.
This one, for instance: /\+alright\i|\+good\i|\+fine\i|\+alright\i/ searches for +alrighti (literally) or +goodi or +finei or +alrighti, because \+ means a literal + and \i means a literal i.
You probably meant /alright|good|fine/i, which searches for alright, good, or fine, case-insensitve. Or perhaps /\b(?:alright|good|fine)\b/i, which does the same but is expecting word boundaries on either side of the word.
You can test out your regex at various sites, including regex101.com.

Why won't my While Loop work?

I am doing the video tutorials from The New Boston and I'm on video 20. Everything has been fine until now but I can't get this one to run. I've checked against the code in the tut and I just can't see what I'm missing. I'm sure it's right in front of my face.
Sorry this is so basic, but I'm a total newbie.
This is the video tutorial: http://www.youtube.com/watch?v=QPFW_0blw9w
This is my code:
var x = 1;
while(x<10){
document.write(x + "how do you like </br>");
x++;
}
Thanks for any help!
Your syntax is correct, as verified by running the JavaScript code (exactly as you wrote it) inside Codecademy Labs. If your while loop isn't working, I suspect it has to do with your environment or the state of the document being written, but it is not the code itself. As a fellow newbie, I try running code in two IDE's (codecademy labs being one) to test a lot of code and confirm against this sort of issue, though codecademy can't do file operations.
In addition, if you're interested in knowing why a for loop is superior to while for this situation, continue reading.
A for loop is a loop that comes in handy when you have a fixed index; When you know how many iterations you need, or know how to find out and can work that into the code.
A while loop is better at handling situations when an unknown (and unpredictable) number of iterations is required, as it will loop through until the conditions are eventually met.
Keep in mind that what makes it strong also makes it weak; for loops are harder to create infinite loops for. Because of the arguments in a for loop (IE: for (index,index<=value,value++)), most for loops self-terminate neatly, or at least it's hard to forget to put the "closing" condition in. while loops, however, don't innately ask for a closing statement and thus you must explicitly state them inside the loop.
I hope this answers your question, and more.
EDIT: Oh yeah, and </br> doesn't work inside the quotes. You can remove it, and it should still do a new line without it; But leaving </br> inside the code just has it literally print </br> in the line.
I don't see anything wrong with your code the way you wrote it, so there must be an error in some of the code that surrounds this. Alternatively, for the same outcome as this, I would suggest using a for loop as such:
for (var x = 1; x < 10; x++){
document.write(x + "how do you like </br>");
}

What does 'jQuery.each(lines, function(lineNo, line)' do?

I'm a beginner in jquery and ajax. While i was going through some example online, i came across the following piece of code and wondered what exactly it does.
lines = newLine.split('#');
jQuery.each(lines, function(lineNo, line) {
eval("linedata = " + line);
data.push(linedata);
});
I'm not a programmer, but just trying to understand its functionality. Can anyone help me?
The each function iterates over an array which is supplied as the first parameter. During each iteration the index and element are passed into a function that is performed. The function is passed as the second parameter to the each function.
Read more on the jQuery Documentation
In the example you have provided a string newLine is split into an array using # as the delimiter.
The each function then iterates over the newly created array, assigning the value of each element to a variable linedata and pushes linedata onto another array.
This could be more easily achieved with the following, since the call to eval is unnecessary:
jQuery.each(lines, function(lineNo, line) {
data.push(line);
});
I pretended, for a moment, that I was a new programmer. This is how you should go about looking into things from here on out:
1.) Ok, I don't know what this first line is doing. It's splitting something (based on the split word). Hmmm let's Google for "split javascript". This is the first thing that comes up. From here, you may be wondering what a String is, so you would search for that as well).
2.) Ok so now I know that splitting a String gives me an array (again you probably looked this up by this step) of the newLine substrings that were separated by the # character. Cool. So let's look into what jQuery.each does. I google "jQuery.each" and this is the first thing that comes up.
Awesome! Now you understand what a String is, an Array, the split function from String as well as what jQuery.each is. :D
EDIT: As you move forward, you'll realize that W3C is generally an inferior source of information. I simply linked to it since it was literally the first thing that came up when I Googled "split javascript". Overall it does the job for giving you a good overview of certain things when you're learning them for the first time.

Please explain this usage of a colon in javascript

I'm making a library, and I often inspect the result of Closure Compiler's output to see how it's doing things (I do have unit tests, but I still like to see the compiled code for hints of how it could compress better).
So, I found this very weird piece of code, which I never seen before.
variable : {
some();
code()
}
Note: this is not an object literal! Also, there is no ? anywhere that would make it a ?: conditional.
That code is in a regular function block (an IIFE).
variable, in this case, is an undefined variable. There's no code making it true, false, or whatever, and just to make sure, I put a console.log in there and indeed, I get a ReferenceError.
Please do note that I test my code in IE8 too, so this isn't just in modern browsers. It seems to be standard, plain old javascript.
So let's experiment with it. Firing up Chrome's console, I get this:
undeclaredVariable:{console.log('does this get logged?')} // yes it does.
trueValue:{console.log('what about this?')} // same thing.
falseValue:{console.log('and this?')} // same thing.
but then...
(true):{console.log('does this work too?')} // SyntaxError: Unexpected token :
...and...
so?{console.log('is this a conditional?')}:{alert(123)} // Unexpected token .
So what does it do?
thisThing:{console.log('is used to declare a variable?')}
thisThing // ReferenceError: thisThing is not defined
Please, I'd love it if someone could explain to me what this code is meant to do, or at least what it does.
It is a label
Provides a statement with an identifier that you can refer to using a
break or continue statement.
For example, you can use a label to identify a loop, and then use the
break or continue statements to indicate whether a program should
interrupt the loop or continue its execution.
Another common place you see it is when people stick the wonderful and useless javascript: on event handlers.
This is a label (the bit ending with a colon) followed by a block (the code surrounded by the curly brackets).
Blocks usually follow control statements, like if(...) { /*block*/ }, but they can also simply stand on their own, as in your example.
Labels allow jumping up several loops at a time with a continue or break; see the linked MDN page for several examples, such as:
var itemsPassed = 0;
var i, j;
top:
for (i = 0; i < items.length; i++){
for (j = 0; j < tests.length; j++)
if (!tests[j].pass(items[i]))
continue top;
itemsPassed++;
}
Here, top: is a label that code inside the inner loop can jump to, in order to escape to the outer loop.
For the sake of anyone who doesn't know what JSON is, and sees a colon in what might actually be an object, and is trying to figure out what it is, and finds this discussion, a colon is also used in JSON. There is a practice of embedding functions in a JSON object. Which might be confusing (As it was to me) for anyone who happens to see this for the first time. (Everyone isn't born with the knowledge of JSON and JavaScript programmed into their brains.) So if you find yourself at this discussion, and you think that every time you see a colon in JavaScript, that it's a label, it might not be. It might be that it's a colon after a label, OR it might be part of JSON. In fact, a colon in JSON being shown as a string, is a lot more common than a label. JSON in the form of an object, will be displayed as [object Object], with all the content hidden. So, unless the JSON is in the form of a string, and you display an object to the console (console.log(object)) all you will see is [object Object]. It is common practice to write JavaScript code, wrapped in an object. In that case you will see the JSON in the form of code. That's when you'll ask yourself, "What is this? and what is that colon for?" Then you'll find yourself at this discussion, and be told that it's a label, when it's really part of JSON. The topic of this discussion is worded: "Please explain this usage of a colon in javascript", and then the "correct answer" is marked as having to do with a label. The correct answer is that a colon can be used in more than one way. So, if you don't know what JSON is, or think you know (like I did, but didn't really understand) read about it here:
JSON.org
That is just a label.
you can use continue [label name] (or break) in a loop to go to a label.
More explanations of what they are can be seen throughout the interwebs.
it is used for labeling an statement in jsvascript.check more detail here.
the labeled statement can be used with break and continue later.

Categories

Resources