JavaScript Recursion exercise: Unexpected token else - javascript

I have read about this error on other threads that mostly ask the user to remove semicolons. This seems to have no effect on my code.
function isEven(number){
if (number > 1)
return isEven(number-2);
else if (number == 1)
return false;
else if (number == 0)
return true;
else if (number < 0)
number *= -1
return isEven(number);
else
return "Error";
}
It seems that this line [number *= -1] is causing the error as if I remove it the code runs with no error except for negative numbers where the stack runs out of memory. What I'm trying to do is to make all numbers positive.
Anyone that would like to help me out?
Solution
function isEven(number){
if (number < 0){
number *= -1
return isEven(number);}
else if (number > 1){
return isEven(number-2);}
else if (number == 1){
return false;}
else if (number == 0){
return true;}
else
return "Error";
}

Short answer: Wrap your codes with {}
if (){
..
..
}else {
..
..
}
Long answer :
else if (number < 0)
number *= -1
return isEven(number);
You are not using {} hence the very next line of the condition only considered as a statement belong to the else if and the later will be treated as general statements.
Since you have 2 lines of code in else if, the link broken there and your else became an orphan. That is the reason you seeing the error. Please wrap up your conditions in {}
function isEven(number){
if (number > 1){
return isEven(number-2);
}
else if (number == 1){
return false;
}
else if (number == 0){
return true;
}
else if (number < 0){
number *= -1
return isEven(number);
}
else{
return "Error";
}
}
Note: Not only to avoid this specific error but to avoid many other weird things always try to use {}. That makes everyones life easy.

Problem is without curly brackets {}
Better you could add {}(curly brackets) on each if and else statement
function isEven(number) {
if (number > 1) {
return isEven(number - 2);
} else if (number == 1) {
return false;
} else if (number == 0) {
return true;
} else if (number < 0) {
number *= -1
return isEven(number);
} else {
return "Error";
}
}
console.log(isEven(-2))

The problem is that you are trying to execute 2 lines of code in the 3rd else if without wrapping it up in curly braces.
By default only single line gets executed when you don't wrap up the block in curly braces.
function isEven(number){
if (number > 1){
return isEven(number-2);
}
else if (number == 1){
return false;
}
else if (number == 0){
return true;
}
else if (number < 0){
number *= -1;
return isEven(number);
}
else{
return "Error";
}
}

Related

If Else Statement Disaster [duplicate]

This question already has answers here:
How does (A == B == C) comparison work in JavaScript?
(6 answers)
Closed 6 years ago.
today I decided I wanted to make a simple js code that would accept a number (in meters), and decide what the appropriate metric unit to use would be. The code turned out to be a little more complicated than I had expected, but I was able to figure out most of the bugs as I found them (even if it meant rearranging all of my code). However, when it came to my if/else statement I could not figure it out. If I put in a number that is less than 1 nothing happens. If I put in a number more than 9 it logs the same thing every time. The structure itself may need some work, but if someone could help me with the if/else statement I would be very thankful. Here is the code (init is called when the body loads):
function init() {
var x = prompt("How many meters?");
convertMetricMeters(x);
function convertDown(x) {
if (0.1 >= x >= 0.99) {
console.log("deci");
}
else if (0.100 >= x >= 0.999) {
console.log("centi");
}
else if (0.1000 >= x) {
console.log("milli");
}
else {
console.log("error");
}
}
function convertUp(x) {
if (1 <= x <= 99) {
console.log("deca");
}
else if (100 <= x <= 999) {
console.log("hecto");
}
else if (1000 <= x) {
console.log("kilo");
}
else {
console.log("error");
}
}
function convertMetricMeters(x) {
if (x < 1) {
convertDown(x);
}
else if (x > 9) {
convertUp(x);
}
else {
console.log("Appropriate Metric Unit");
}
}
}
Use && as AND operator in javascript
Convert these 100 <= x <= 999 to 100 <= x && x <= 999
You could simplify the check a bit and return if a condition is true.
function convertDown(x) {
if (x < 0.01) {
console.log("milli");
return;
}
if (x < 0.1) {
console.log("centi");
return;
}
if (x < 1) {
console.log("deci");
return;
}
console.log("error");
}
Your code has 2 sort of errors. One was simple to fix, that you have to add && between two conditions in if statement.
Now coming to the other part, the less than 1 items. It needed a different logic. Well, your maths seems to be needing bit attention. 0.1 is same as 0.100 and is same as 0.1000
I have updated the code to look for the number of digits after the decimal point and then console.log accordingly.
The updated code will be:
function init() {
var x = prompt("How many meters?");
convertMetricMeters(x);
function convertDown(x) {
// checks the number of digits after decimal point
decimals = (x.split('.')[1] || []).length
if (decimals == 1 || decimals == 2) {
console.log("deci");
}
else if (decimals == 3) {
console.log("centi");
}
else if (decimals == 4) {
console.log("milli");
}
else {
console.log("error");
}
}
function convertUp(x) {
if (1 <= x && x <= 99) {
console.log("deca");
}
else if (100 <= x && x <= 999) {
console.log("hecto");
}
else if (1000 <= x) {
console.log("kilo");
}
else {
console.log("error");
}
}
function convertMetricMeters(x) {
if (x < 1) {
convertDown(x);
}
else if (x > 9) {
convertUp(x);
}
else {
console.log("Appropriate Metric Unit");
}
}
}
Working jsfiddle example: https://jsfiddle.net/w7pf3moL/
A simplified version with only 1 method convert(float x):
function init() {
var x = prompt("How many meters?");
convertMetricMeters(x);
function convert(x) {
if (x < 0.01) console.log("milli");
else if (x < 0.1) console.log("centi");
else if (x < 1) console.log("deci");
else if (x < 10) console.log("meter");
else if (x < 100) console.log("deca");
else if (x < 1000) console.log("hecto");
else console.log("kilo");
}
function convertMetricMeters(x) {
if (x > 0) {
convert(x);
} else {
console.log("Appropriate Metric Unit");
}
}
}
init();

When will If else break with all conditions javascript

When will else condition executed ?? is there any possibility of i value which will not satisfy any if , else if condition and reach else block in javascript.
random = Math.random();
i=0; //0,0.1,0.001
console.log(random);
if(random < i) {
console.log("<");
} else if(random > i) {
console.log(">");
} else if(random == i) {
console.log("=");
}else{
console.log("nothing");
}
Else will never be reached. The Result of Math.random() is between 0 and 1 (see W3Schools)

This mergesort should "of" failed, right?

I noticed something weird while reviewing this mergesort implementation on Code Review…
/************************************************************
* Mergesort implementation
***********************************************************/
function sort(array) {
var len = array.length;
var middle = Math.floor(len*0.5);
var left = array.slice(0,middle);
var right = array.slice(middle, len);
if (len == 1) {
return array;
} else {
}
return merge(sort(left), sort(right));
}
function merge(left, right) {
var a = left.length;
var b = right.length;
if (a > 0 && b > 0) {
if (left[0] > right[0]) {
return [].concat(left[0], merge(left.slice(1,a), right));
} else {
return [].concat(right[0], merge(right.slice(1,b), left));
}
} else if (a == 0) {
return right;
} else of (b == 0)
return left;
}
/************************************************************
* Demonstration
***********************************************************/
function doSort() {
var array = document.getElementById('in').value.split(/[, ]+/).map(function(e) {
return parseInt(e);
});
var sorted = sort(array);
document.getElementById('out').value = sorted;
}
function generateRandom(len) {
var array = [];
for (var i = 0; i < len; i++) {
array.push(Math.round(Math.random() * 100));
}
document.getElementById('in').value = array;
};
generateRandom(20);
<button onclick="generateRandom(20)">⬇︎ Generate random numbers ⬇︎</button>
<div><input id="in" size="80"></div>
<button onclick="doSort()">⬇︎ Sort ⬇︎</button>
<div><input id="out" size="80" disabled></div>
The last conditional branch is else of rather than else if. Normally, else of should result in a syntax error. Yet, no matter how hard I try, I can't trigger the syntax error — it always successfully returns an array sorted in descending order!
I know, else of (b == 0) could just be replaced by else, but still, I want to know: How could this code possibly work?
This works because of a combination of 2 "bad things" about Javascript: skipping braces in block statements that contain only a single statement, and semicolon insertion.
Your if statement, properly braced, should look like this:
if (a > 0 && b > 0) {
if (left[0] > right[0]) {
return [].concat(left[0], merge(left.slice(1,a), right));
} else {
return [].concat(right[0], merge(right.slice(1,b), left));
}
} else if (a == 0) {
return right;
} else of (b == 0) {
return left;
}
but, because of the missing braces and semicolon insertion, Javascript is seeing/parsing it like this:
if (a > 0 && b > 0) {
if (left[0] > right[0]) {
return [].concat(left[0], merge(left.slice(1,a), right));
} else {
return [].concat(right[0], merge(right.slice(1,b), left));
}
} else if (a == 0) {
return right;
} else {
of(b == 0);
}
return left;
If you always pass in legitimate left and right arrays then this last else branch is never reached, hence why you haven't seen an exception.
If you pass in an empty right array, it will reach the last branch and throw of is not a function:
merge([10, 20, 30], []);
Any respectable coding standard should explicitly require these 2 "features" of Javascript never be used... but that's just one opinion.
of is a keyword in ES6, used for iterating over objects..
but in this case the of is behaving as function not keyword..
The function code never goes to else of (b == 0) return left; part.. so compiler is not throw ReferenceError: of is not defined
if you will change of keyword into another word like else often(b==0).... then also code work
when you send right side empty then code will throw error ReferenceError: of is not defined, so finally this is only typo.

Javascript - Find if number is positive or negative

I see other solutions to my question but none that help me.
I want to create a function to find if a number is positive/negative. The function should take an integer argument and return true if the integer is positive and false if it is negative.
Also, prompt the user again and again if anything other than a number is entered
Here's the code so far
When I enter a number, it keeps alerting me it is true or false but won't let me enter another.
How do I control my loop so I can ask until -1 is entered? It is not giving me a chance to enter -1
function isPositive(num) {
var result;
if (num >= 0) {
result = true;
} else if (num < 0) {
result = false;
}
return result;
}
var num;
num = parseInt(prompt("Enter a number"));
while (num != -1) {
alert(isPositive(num));
if (isNaN(num)) {
alert("No number entered. Try again");
num = parseInt(prompt("Enter a number"));
isPositive(num);
while (num != -1) {
alert(isPositive(num));
}
}
}
There's a few things wrong with your code, so here's a rewrite with comments:
function isPositive(num) {
// if something is true return true; else return false is redundant.
return num >= 0;
}
// when you want to keep doing something until a condition is met,
// particularly with user input, consider a while(true) loop:
var num;
while (true) {
num = prompt("Enter a number");
// check for null here
if (num === null) {
alert("No number entered. Try again.");
continue; // return to the start of the loop
}
num = parseInt(num, 10); // second argument is NOT optional
if (isNaN(num)) {
alert("Invalid number entered. Try again.");
continue;
}
// once we have a valid result...
break;
}
// the loop will continue forever until the `break` is reached. Once here...
alert(isPositive(num));
Math.sign(number)
which returns either a 1, -1 or 0
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
The number 0 is neither positive, nor negative! :P
function isPositive(num)
{
if(num < 0)
return false;
else
return true;
}
Or a simple way,
function isPositive(num)
{
return (num > 0);
}
You are testing if it isn't -1. Try this:
if(num < 0){
...IS NEGATIVE...
}else{
...IS POSITIVE...
}
This checks if it is less than or greater than 0.

'if'-'else' in JavaScript

I have a simple if - else construct that operates with data grid filterind. Like this:
if (_r1 <= _r3 && _r3 <= _r2) {
return true;
}
else {
return false;
}
where _r1, _r2, _r3 and numbers. It has both true and false. Is it possible to rewrite this construction that it will has only for example true branch and will go to the else branch by default?
P.S. (if ... ? ... : ...) is not what I want.
Use:
return _r1 <= _r3 && _r3 <= _r2;
if (_r1 <= _r3 && _r3 <= _r2) {
return true;
}
return false;

Categories

Resources