JavaScript Beginner Syntax Errors - javascript

I wrote this program out in plain code but I don't know Javascript well enough to get all the syntax right. I am a beginning programming please help me with corrections to my code. It is currently not running at all. We are still going over loops and it's really giving me trouble. This is for a college class. (I know this isn't formatted properly that's why i'm asking for help)
function main() {
alert("Welcome to the program");
var fatGrams = getFatGrams(fatGrams);
var calories = getCalories(fatGrams,calories);
var percentage = caloriesPercentage(fatGrams,calories);
displayPercentage(percentage);
}
function getFatGrams(fatGrams) {
fatGrams = prompt("Enter the number of fat grams in your food item");
while(fatGrams < 0){
alert("Error, the fat grams cannot be less than 0.");
fatGrams = prompt("Enter the new number of fat grams.");
}
return fatGrams;
}
function getCalories(fatGrams,calories) {
calories = prompt("Enter the number of calories in your food item.");
while (calories < 9 || calories > (fatGrams * 9)){
alert("Error, the calories cannot be less than 9 or exceed the fat grams * 9");
calories = prompt("Enter the new number of calories");
}
return calories;
}
function caloriesPercentage(fatGrams,calories){
percentage = (fatGrams * 9) / calories;
alert("The amount of calories that come from fat is, " + percentage);
return percentage;
}
function displayPercentage(percentage){
if(percentage < 0.3){
alert("The food is low in fat.");
}
else{
alert("The food is not too low in fat.");
}
}
main();
alert("End of program");

Errors in your code :
The function keyword is not needed to call a function. Remove the keyword function before calling a function and simply call the function as getFatGrams(fatGrams);
You are not passing parameters to function caloriesPercentage. Change it to caloriesPercentage(fatGrams,calories);
The expression for a while loop should be enclosed in paranthesis as while(fatGrams < 0).
The OR should be written as ||.
Use + to concatenate 2 string (Or a string and a variable)
"The amount of calories that come from fat is, " + percentage
The expression for an while should also be enclosed in paranthesis as if(percentage < 0.3) and no then is needed. The curly brackets of if should be closed before else.
if(percentage < 0.3){
alert("The food is low in fat.");
}
else {
alert("The food is not too low in fat.");
}
assign value from prompt to variable as
fatGrams = prompt("Enter the new number of fat grams.");
Your final code should look like this :
function main() {
alert("Welcome to the program");
var fatGrams;
var calories;
var percentage;
getFatGrams(fatGrams);
getCalories(fatGrams,calories);
caloriesPercentage(fatGrams,calories);
displayPercentage(percentage);
}
function getFatGrams(fatGrams) {
fatGrams = prompt("Enter the number of fat grams in your food item");
while(fatGrams < 0){
alert("Error, the fat grams cannot be less than 0.");
fatGrams = prompt("Enter the new number of fat grams.");
}
return fatGrams;
}
function getCalories(fatGrams,calories) {
calories = prompt("Enter the number of calories in your food item.");
while (calories < 9 || calories > (fatGrams * 9)){
alert("Error, the calories cannot be less than 9 or exceed the fat grams * 9");
calories = prompt("Enter the new number of calories");
}
return calories;
}
function caloriesPercentage(fatGrams,calories){
percentage = (fatGrams * 9) / calories;
alert("The amount of calories that come from fat is, " + percentage);
return percentage;
}
function displayPercentage(percentage){
if(percentage < 0.3){
alert("The food is low in fat.");
}
else{
alert("The food is not too low in fat.");
}
}
main();
alert("End of program");

welcome to the wonderful world of programming!
It looks like you are getting the basics down, let me explain some of the issues you are having with JavaScript. I'm going to use some big words (as will many other experienced developers so get used to them!).
Function Declaration vs Function Invocation
The very first issue I see with your main() function is a confusion about when to use the function keyword in JavaScript. You only need to use function when you are declaring a function, or in other words when you want to "create a new function." When you declare something, you are creating it, and in JavaScript the function keyword is how you declare (aka create) a Function. Here is an example of creating a "named function" in javascript.
function addTwo( number ) {
return number + 2;
}
That right there is a "named function" declaration. On a side note, you can also create functions as "expressions" (which would be called a "function expression"). That would look like this
var addThree = function( number ) {
return number + 3;
};
Note that in both cases we are creating a function with the function keyword.
When you want to use a function, you "invoke" it. This is also referred to as "calling" a function. To call (aka invoke) a function you simply write the function name with parenthesis behind it, passing in any arguments. Function invocation works the same for both named functions and function expressions. So we could invoke the two functions above like so
var four = addTwo( 2 );
var five = addThree( 2 );
Simply put, only use the function keyword to make functions. To call or use a function just put ( argument, otherArg ) at the end of the function name.
Branching Statements
The next thing I see is that you're missing some parenthesis! JavaScript has a C style syntax so that means you need to put parenthesis around expressions for if, else if, and switch statements. Those keywords I listed are what we call Branching Statements. They allow you to conditionally execute code based on some true or false value, as opposed to Looping Statements that allow you to repeat code based on a true or false value. The structure for an if .. else branching statement in JavaScript is as follows.
if ( number % 2 === 0 ) {
number *= 2;
} else if ( number % 3 === 0 ) {
number *= 3;
} else {
number += 5;
}
For both if and else if you need to provide an "expression" to branch around. An else statement is always executed if none of the if or else if expressions evaluated to true. The else clause is not required so if you don't have any code in your else block you can just remove it! It is perfectly fine to have a single if statement like this in your code
if ( needsCleanup ) {
doCleanup();
}
Of course it would be ok to have an else if clause and no else clause, the else is always optional. But remember the else clause never has an expression so you should never write () after a simple else.
Looping Statements
Looping is a big concept that takes a while to master so don't get frustrated or discouraged! In JavaScript we have for, while and do while loops. Just like if statements looping statements need an expression, but in this case they need it to know when to stop looping. I'm not going to cover do while loops because they are rarely used and can be confusing when just starting out. Simply put, looping statements say: "keep executing this code block until the expression is false." I find it easiest to illustrate this with a for loop. For loops are a great way to run a code block a specific number of times. Let's look at an example that adds all the numbers from 1 to 10 with a for loop.
var sum = 0;
for ( var i = 1 ; i <= 10 ; i++ ) {
sum += i;
}
// sum will be 55
// i will be 11
A for loop has three expression separated by ;. The first is for initialization and is only executed before the loop starts (the var i = 1 part). The second is the condition that is checked before each iteration. The last is an increment operation that is executed at the end of every loop execution. If we were to re-write this for loop as a while look it would look like this...
var sum = 0;
var i = 1;
while ( i <= 10 ) {
sum += i;
i++;
}
So you can see the var i = 1 happens before the loop starts. The i <= 10 happens before each time the loop runs its body (the part in the {}). And the i++ happens at the end of the loop before it checks i <= 10 to see if it should keep looping.
String Concatenation
String concatenation is the process of putting two strings together. In JavaScript the + operator does double duty as addition 1 + 1 and string concatenation 'hello' + ' world'. So when you want to put two strings together you simply add them! If the strings are in variables then you can just "add" them together...
var salutation = 'Hello';
var name = 'Kylie';
var greeting = salutation + ', ' + name;
// greeting will be "Hello, Kylie"
I hope that clears some things up, if you have any questions please let me know!

Because this IS for a class I am NOT going to give you the answers but instead point out the issues.
Calling a function in Javascript and return a value:
var myvalue = myFunction();
You have function... in your main and need to fix that.
Some functions just return values and thus calling them needs no parameter (like above) others need parameters for the inputs which you have done.
Prompt returns a value and you need to capture that value:
var myinputvalue = prompt("enter value");
Reference: https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt
Conditionls need to be wrapped in parenthesis when using while, if etc.
while (mything < 0){ Reference; https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while
" OR " in a conditional is represented by || and an AND by &&
NOTE: You can use some on-line tools to work out some of the issues for example paste your code into http://jshint.com/ and it will tell you many of the syntax issues.

Related

A task in JavaScript

I need to create a sequence of numbers using while or for that consists of the sum of the symbols of the number.
For example, I have a sequence from 1 to 10. In console (if I've already written a code) will go just 1, 2,3,4,5,6,7,8,9,1. If I take it from 30 to 40 in the console would be 3,4,5,6,7,8,9,10,11,12,13.
I need to create a code that displays a sum that goes from 1 to 100. I don't know how to do it but in console I need to see:
1
2
3
4
5
5
6
7
8
9
1
2
3
4
etc.
I've got some code but I got only NaN. I don't know why. Could you explain this to me?
for (let i = '1'; i <= 99; i++) {
let a = Number(i[0]);
let b = Number(i[1])
let b1 = Boolean(b)
if (b1 == false) {
console.log ('b false', a)
}
else {
console.log ('b true', a + b)
}
}
I hope you get what I was speaking about.
Although I like the accepted answer however from question I gather you were asking something else, that is;
30 become 3+0=3
31 become 3+1=4
37 becomes 3+7=10
Why are we checking for boolean is beyond the scope of the question
Here is simple snnipet does exactly what you ask for
for (let i = 30; i <= 40; i++) {
let x=i.toString();
console.log( 'numbers from ' +i + ' are added together to become '+ (Number(x[0])+Number((x[1])||0)))
}
what er are doing is exactly what Maskin stated begin with for loop then in each increment convert it to string so we can split it, this takes care of NAN issue.
you don't need to call to string just do it once as in let x then simply call the split as x[0] and so on.
within second number we have created a self computation (x[1])||0) that is if there is second value if not then zero. following would work like charm
for (let i = 1; i <= 10; i++) {
let x=i.toString();
console.log( 'numbers from ' +i + ' are added together to become '+ (Number(x[0])+Number((x[1])||0)))
}
Did you observe what happens to ten
here is my real question and solution what if you Don't know the length of the digits in number or for what ever reason you are to go about staring from 100 on wards. We need some form of AI into the code
for (let i = 110; i <= 120; i++) {
let x= Array.from(String(i), Number);
console.log(
x.reduce(function(a, b){ return a + b;})
);
};
You simply make an array with Array.from function then use simple Array.reduce function to run custom functions that adds up all the values as sum, finally run that in console.
Nice, simple and AI
You got NaN because of "i[0]". You need to add toString() call.
for (let i = '1'; i <= 99; i++) {
let a = Number(i.toString()[0]);
let b = Number(i.toString()[1])
let b1 = Boolean(b)
if (b1 == false) {
console.log('b false', a)
} else {
console.log('b true', a + b)
}
}
So the way a for loop works is that you declare a variable to loop, then state the loop condition and then you ask what happens at the end of the loop, normally you increment (which means take the variable and add one to it).
When you say let i = '1', what you're actually doing, is creating a new string, which when you ask for i[0], it gives you the first character in the string.
You should look up the modulo operator. You want to add the number of units, which you can get by dividing by 10 and then casting to an int, to the number in the tens, which you get with the modulo.
As an aside, when you ask a question on StackOverflow, you should ask in a way that means people who have similar questions to you can find their answers.

Javascript if else conditionals not returning the desired output [duplicate]

This question already has answers here:
if statement always return true even for simple integer values
(3 answers)
Closed 2 years ago.
I've been teaching myself how to code in new languages and might be asking a couple of silly questions here for a while.
Trying to put this to work but, when the output pops out and the grade I've typed into is higher than 50, it was supposed to show the word "PASS". Instead, I'm still getting "FAIL" - the amount doesn't matter.
I am pretty sure it has to do with the conditionals, but I've been stuck on this for a long time now.
Here is my code:
var input = Number(prompt("Enter a grade between 0 and 100.")); //enter grade
if (input > 100 || input < 0) {
alert("Grade not valid. Enter a grade between 0 and 100."); //validate grade
} else {
if (input < 50); //result FAIL
{
result = "Fail";
alert("FAIL");
}
/*
if (input > 50); //result PASS - This part doesn't work
{
result = "Pass";
alert("PASS");
}
*/
total = total + input;
entrys = entrys + 1; //show inputed grades
document.write("<br>" + "Grade " + entrys + " = " + input + " = " + input / 100 + "%" + " " + result); // Every inputed result is considered "Fail"
}
The semicolon after the if (input < 50) turns the if statement into a one line if with an empty expression, followed by a code block that always runs. You can fix your issue by getting rid of the semicolon.
if (input < 50); //result FAIL
// ^ this is bad
As others have already pointed out, you need to remove the ; from the line if you want the rest of the statements to execute. The reason why is because, traditionally, in compiler languages the semicolon(;) is used to mark the end of the line. In javascript, they are also used for that purpose, but they are optional in javascript.
So if your code spans multiple lines, avoid using it unnecessarily. Definitely don't use it after a for or while loop(unless for certain use cases where you want that), or after an if-else statement, because execution will get stopped at that line and the next line will be executed like it is an unrelated code and not part of the loop/statement. Hope this makes sense

Multiplying Integers on a For Loop

Beginning JavaScript learner here...
I'm working through Adrian Neumann's Simple Programming Problems and my question is about number 6 in the elementary exercises.
Write a program that asks the user for a number n and gives him the possibility to choose between computing the sum and computing the product of 1,…,n.
// var myArray = []; // for testing
var mySum = 0;
var userNum = prompt("What is your number? ");
var userChoice = prompt("Would you like to add up (+) or multiply (*) all the numbers from 1 to your number? Please enter (+) or (*): ");
if (userChoice == "+") {
for (var i = userNum; i > 0; i--) {
mySum += +i;
}
console.log("Your answer is " + mySum);
} else if (userChoice == "*") {
for (var i = userNum; i > 0; i--) {
mySum *= +i;
// myArray.push(i); // for testing
}
console.log("Your answer is " + mySum);
// console.log(myArray); // for testing
}
When entering values for multiplication, the answer is always 0. Obviously, I thought 0 was being included in the iteration, so I setup an empty array myArray, and pushed all the numbers to the array using myArray.push(i);... 0 was never included as a value in the array.
Other than some obvious form-validation considerations, can anyone tell me what I'm missing? Why is my answer always 0?
Note: The sum section of the code seems to work brilliantly.
Please note I'm a beginniner to JavaScript, so if you'd like to comment, let me know WHY you changed the code the way you do, rather than simply spitting back code to me. That's a big help, thanks.
Well, you initialize mySum to 0 so in every iteration of the loop you'll multiplying i by zero and save the result (again, zero) back into mySum. For multiplication you'd have to start at one.
You didn't set mySum to 1 before multiplication. 0*i = 0.

Why is everything NOT prime?

I'm trying to write this program to find prime numbers. I have the basics of it down, except that no matter what number I put in, it returns as NOT prime. I've been messing with this for way too long and cannot figure out what it is. Is it in my "if" statement or my isPrime function? Please help, and thank you!
var number = 0;
function main()
{
number = parseInt(prompt("Please Enter a Number to Determine Whether or Not it is Prime:", "Enter a Number"));
while(isNaN(number) === true)
{ alert("You Entered an Invalid Number. Please Reenter");
number = parseInt(prompt("Please Enter a Number to Determine Whether or Not it is Prime:", "Enter a Number"));
}
isPrime(number);
if(prime = false)
{ alert("The number " + number + " is a Prime Number!"); }
else
{ alert("The number " + number + " is NOT a Prime Number!"); }
}
/*------------------------------------------------------*/
function isPrime(number)
{
if(number < 2)
{return false;}
var prime = false;
for(var i = 2; i <= Math.sqrt(number); i++)
{ if(number % i == 0)
{prime = true;}
}
return prime;
}
if (prime = false)
You just assigned prime to false.
You don't want to do that.
By contrast, you do want to assign it to the result of your function.
Replace:
if(prime = false)
not only because you're using assignment instead of comparison, but because prime is not defined (it's not going to return/create a global variable prime from that function call).
Replace it with:
if (!isPrime(number)) {
Now this doesn't use a variable to store the result of the isPrime call, but uses the call directly. If you need this result in more than one place, then it would be a good idea to assign it to a variable:
var prime = isPrime(number);
and then do the rest of your code:
if (prime == false)...
isPrime(number);
leaves no variable assigned. Therefore prime is never assigned in your test and unassigned variables are treated as false as far as boolean expressions are concerned.
It should be
var prime = isPrime(number);
You're also doing an assignment where you meant to do a comparison.
if(prime = false)
should be
if(prime === false)
Tip: If you're doing these kinds of tests, it's usually a good idea to put the thing that can't be changed by assignment on the left (function call, constant, etc). That way if you accidentally put = instead of == or === the script will fail with an error.
if(false === prime)
If you accidentally type
if (false = prime)
you'll get
ReferenceError: invalid assignment left-hand side
which is obvious and easy to debug.
As this is a simple boolean switch, a simple "is not true" check is fine.
if (!prime)
Actually their are only 2 small logic failure.
You define "prime" inside your function isPrime() - hence you cannot use it outside your function.
You try to do if(prime = false) which assigns the value false to "prime" whick does nothing for your if except breaking it.
You need to define the variable outside hence use your prime = isPrime()
Also you do not need to check against "false" which by any means does not really make sense their. "true == false" ? just skip that ans ask for if(prime) which is true or false.
Alternativly you can call your funtion directily in the if condition like:
if(isPrime(number)){....
it then automaticly checks the return value.

How do I fix this syntax error?

The code is:
function roundAmount(theDecimal) {
var s = "" + Math.round(theDecimal * 100) / 100
var i = s.indexOf('.')
if (i < 0) {
return s + ".00"
}
var t = s.substring(0, i + 1) + s.substring(i + 1, i + 3)
if (i + 2 == s.length)
t += "0"
return t
}
The line with the error:
if (i < 0) return s + ".00"
The error is:
error: expected (;)
does anyone know how to fix this?
About your script:
The problem in the script above is that last if statement which does some operations followed by a return. You need a semi-colon after the operation.
In the future, as good practice, make sure to put a semi-colon after every valid statement. That way this won't bother you.
Think of each line as a thought, and curly braces as ways to "group" and "relate" thoughts together.
The below is a full thought that says "give me a variable "i" and give it the value 1 + 2;
var i = 1 + 2;
The below is a full thought about a condition that says "If i is 3 then add 1 to i". The thought "add 1 to i" is its own thought, so it needs a semicolon. Since the curlybraces for the IF statement are special in that they don't need a semi-colon after their "full thought" as long as you put a "block" (which is what curlybraces really make) after it, to enclose the thought.
This means the following is valid:
if( i == 3 ) {
i = i + 1;
}
The following is not valid because the semi-colon after the if ends the "thought" before the if knows what to do if i equals 3:
if( i == 3 ) ; {
i = i + 1;
}
For a basic JavaScript tutorial, check out W3Schools.
"There must be a better way?"
Any time you find yourself doing a lot of string operations on decmials, it's a good idea to ask yourself "is there a better way to do this?".
It looks like you're writing a function to round a number to the nearest hundredths while displaying two decimal points. There's a much easier way to do this. You can just round to the nearest hundredths and have javascript output the fixed point number.
Example:
function roundAmount( theDecimal ) {
//first round to the nearest hundredth
//then return the value with two decimal places as a string
return theDecimal.toFixed( 2 );
}
if (i < 0) return s + ".00";
Note the ; at the end of the statement. Personally, I prefer surrounding almost all my ifs in {} such as
if (i < 0)
{
return s + ".00";
}
Which helps in debugging and stepping though code.
It's expecting a semicolon, so add a semicolon.
if (i < 0)
return s + ".00";
Add a semicolon at the end of the line! Like this:
if (i < 0) return s + ".00";
I don't see anything particularly wrong with the code you posted in the earlier comments, but may I suggest always adding a semi-colon to the end of your statements. Though they are not required, it usually makes it easier to debug problems such as these.

Categories

Resources