So I am suppose to create a function that reverses a values boolean parameter. [Here][1] is what I came up with:
I really just want to understand what is my flaw in thinking. How can I fix my approach?
Please have a look to your code:
function not(x) {
if (1 == true) {
return "true";
} else if (0 == false) {
return "false";
}
}
Whats right:
function not(x) {
}
Whats goes wrong:
if (1 == true) {
// ^ ^^ ^^^^
// | | boolean
// | equal (not type safe)
// number
You compare constant values. In this case a number 1 with a boolean true. The comparison operator is equality == and this "converts the operands if they are not of the same type". That means that one is equal true and the next part is evaluated and
return "true";
ever, because there are no variables involved. The rest of the else part is never reached, as well as the next comparison, which is never reached.
As well as 'true' is always returned, it is not the type you want, because you need a boolean and return a string.
What should change:
if (x == true) {
// ^
// the parameter of the function
return true;
// ^
// boolean
} else {
// ^
// no other if
return false;
// ^
// boolean
}
or a short version of all with the logical NOT operator !:
function not(x) {
return !x;
}
I assume you want to write the function for learning purpose, because you do not need to write it in practice. Javascript already has ! (not) operator.
For your function and implementation would be:
function not(x) {
if(x === true) return false;
else return true;
}
But as I said you can just use ! operator.
Related
I am attempting to solve a generic Palindrome problem recursively. However, it seems that my algorithm is only evaluating the first recursive call, not the second, which should check all characters in the string. There is apparently a logic error in my algorithm, but I can't spot it. Can anyone advise? See the code below.
function isPalindrome(totalChars: number, lastIdx: number, str: string): boolean | undefined {
console.log(`lastIdx: ${lastIdx}; char: ${str[lastIdx]}`);
// const curIdx = lastIdx;
let highIdx = lastIdx;
const lowIdx = totalChars-1 - highIdx;
// Base Case:
if(totalChars === 0) return true;
if (lowIdx === highIdx) return true;
if (lowIdx > highIdx) {
console.log(`Endpoint reached; STR: ${str}; LOW: ${str[lowIdx]}; high: ${str[highIdx]}`);
return;
}
if(str[lowIdx] === str[highIdx]) {
console.log(`Loop through idx; STR: ${str}; LOW: ${str[lowIdx]}; high: ${str[highIdx]}`);
return true;
}
else if(str[lowIdx] !== str[highIdx]) return false;
// Recursive Case:
return isPalindrome(totalChars, highIdx, str) && isPalindrome(totalChars, highIdx-1, str);
}
// console.log("a is Palindrome: " + isPalindrome("a".length, "a".length-1, "a"));
// console.log("motor is Palindrome: " + isPalindrome("motor".length, "motor".length-1,"motor"));
console.log("rotor is Palindrome: " + isPalindrome("rotor".length, "rotor".length-1,"rotor"));
There are a few problems:
your if...else will always result in a return, and so the statement with the recursive call will never be executed.
Note that the condition after else if will always be true when it gets evaluated, since it is the negation of the condition that is evaluated in the earlier if statement.
More importantly, when that earlier if condition is true, you don't want to return, as it has not been verified yet that the remaining (inner) characters match. This still has to be verified via the recursive call, so this is not a place to perform a return. Just remove that if block, and only return when the characters differ.
So replace this:
if(str[lowIdx] === str[highIdx])
{
return true;
}
else if(str[lowIdx] !== str[highIdx]) return false;
With just:
if(str[lowIdx] !== str[highIdx]) return false;
The first recursive call passes the same arguments as the current execution of the function got -- this will lead to infinite recursion. A recursive call must always make the problem smaller. In this case, there is actually no need to make two recursive calls, and you should remove that first one.
So replace this:
return isPalindrome(totalChars, highIdx, str) && isPalindrome(totalChars, highIdx-1, str);
with:
return isPalindrome(totalChars, highIdx-1, str);
The base case has a condition where return is executed without boolean return value. The function should always return a boolean value. In this case it should be true, because it means that all character-pairs were compared, and there is no single-middle character remaining (the size of the string is even). So you can combine this case with the previous base case. In fact, that base case condition will also work when totalChars is zero, so you can omit that first if.
So change this:
if (totalChars === 0) return true;
if (lowIdx === highIdx) return true;
if (lowIdx > highIdx) {
return;
}
with:
if (lowIdx >= highIdx) return true;
I am pretty new at this stuff, and I am solving a series of questions, but I've got lost in this one.
I have to verify if a number can be divided by other, and the answer must be true or false.
I got his
function solucao(numero, x) {
solucao(numero % x);
if (solucao === 0) {
resultado = true;
}else{
resultado = false;
}
}
But I'm getting runtime error and can't see whats is missing.
So you want to check if a number numero is divisible by x. The modulo operator can help. Try this:
function solucao(numero, x){
if (numero % x == 0){
return true
}
else {
return false
}
}
function solucao(numero, x) {
let resultado;
if (numero % x === 0) {
resultado = true;
}else{
resultado = false;
}
return resultado;
}
I think you get confused at some point. You are calling the function, inside of itself. You should do like this, and also, declare the result variable.
I am sure this will help:
function checkIfDivided(){
// in this section the variables come from an html document
var number=parseInt(document.getElementById("number").value);
var divisor=parseInt(document.getElementById("divisor").value);
if(number%divisor==0)
return true;
else return false;
}
or
function checkIfDivided(number,divisor){
//in the function the variable are given as parameters
if(number%divisor==0)
return true;
else return false;
}
Looks like two things to me:
You haven't declared your 'resultado' variable ( this can be as simple as just typing 'let resultado;' without the single quotes
You haven't returned your 'resultado' variable after the if/else statement
Right now, your function is using an undeclared variable and not returning anything, so that is why you are getting an error. Fix the two above steps and you should be good! :)
You clearly understand that the modulus operator is the way to go. Using it we discover that 12 is divisible by 3 because 12 % 3 return zero. Zero is considered a "falsy" value while any other number is considered "truthy".
Given this then if 12 % 3 returns a "falsey" value (zero) we can't use the result directly. But what if we can "flip" false to true? We can, using the not operator (!).
Using the ! operator on the result of a math problem requires the use of parentheses around the math problem itself.
So the problem in code becomes (12 % 3) and to 'flip' it with the ! operator it becomes
!(12 % 3).
This is proven below with:
console.log(!(12 % 3)) --> logs true
console.log(!(12 % 5)) --> logs false
The function implementation of that is simple and also proven:
console.log(isDivisible(12,3)); --> logs true
console.log(isDivisible(12,5)); --> logs false
console.log(!(12 % 3))
console.log(!(12 % 5))
function isDivisible(number, x){
return !(number % x);
}
console.log(isDivisible(12,3));
console.log(isDivisible(12,5));
There is one other way to do so and i think its much cleaner.
console.log(Number.isInteger(10/2)) //true
console.log(Number.isInteger(4/2)) // false
//a must be greater than b
function check(a,b) {
console.log(Number.isInteger(a/b))
return Number.isInteger(a/b)
}
check(10,5)//true
check(8,3)//false
I have a function that checks whether a value is found in array. I want to return a true or false. Current code works but throws and js-standerd/es-lint error "Unnecessary use of boolean literals in conditional expression"
I've searched through a ton of these error messages here but can't seem to wrap my head around it. To me this says 'If the value is found return true otherwise false'
let found = value.find(val => {
return val === item
})
return found ? true : false
I tried this
return value.find(val => {
return val === item
}) || false
Which works but doesn't return a Boolean if found, it returns item.
I know i can make this work in multiple ways but i'm just trying to figure out whether my code is bad or incorrect or whether es-lint is flagging it sort of incorrectly.
The linter is complaining about this:
return found ? true : false
Which should be read as "If found is truthy return true otherwise return false". This structure is referred to as a 'ternary' operator and has been in use since the early days of C, if not before. The ? operator evaluates the condition on the left and returns the first argument if the condition evaluates to true, otherwise it returns the second argument, where the arguments are separated by a colon.
The problem with your code is that returning the condition itself is the equivalent of returning the boolean literals true or false. Therefore, the check and the literals are unnecessary and can be removed. Though, because this is javascript you might want to double negate the condition before returning it, to force it to be a boolean. So, the result looks like this:
return !!found
This is easier to read and there is less chance of it being implemented wrong or misunderstood in the future.
Of course, this could be taken further:
return !!value.find(val => val === item)
In this way, you don't need to even introduce the symbol found into the code at all. Also, this would be better with some(), but I think your question is more about the ternary operator than how to search a list.
My issue was an unnecessary 'else if'.
This produced an error:
// val: "A" | "B" | "C"
const val = "B";
if (val === "A") {
// do something
} else if (val === "B" || val === "C") {
// do something else
}
Removing the 'else' fixed the error:
// val: "A" | "B" | "C"
const val = "B";
if (val === "A") {
// do something
}
if (val === "B" || val === "C") {
// do something else
}
I suppose the reasoning is readability.
return value.some(val => { return val === item; });
I attempted to solve the recursion exercise of the online book eloquentjavascript 2nd edition:
Here is what the question states:
We’ve seen that % (the remainder operator) can be used to test whether
a number is even or odd by using % 2 to check if it’s divisible by
two. Here’s another way to define whether a (positive, whole) number
is even or odd:
Zero is even.
One is odd.
For any other number N, its evenness is the same as N - 2.
Define a recursive function isEven corresponding to this description.
The function should accept a number parameter and return a boolean.
Test it out on 50 and 75. See how it behaves on -1. Why? Can you think
of a way to fix this?
Here is what I have attempted and it works:
function isEven(number) {
if (number == 0) {
return true;
} else {
return (-number % 2 == 0) ? true : false;
}
return isEven(number - 2);
}
console.log(isEven(-1));
But, it seems to be a wrong answer because as I understood the author wants me to use - 2 method. I am wondering if this is indeed the correct answer or if it is wrong could someone point me in the right direction.
I think the reason you are getting confused is because you're not understanding how recursion works. The reason it is n-2 is, it is taking the number and subtracting 2 until it is either a zero or one. Therefore giving us a true or false.
Hope that helps. Read over how the process of recursion works.
The alternative solution that doesn't use the modulos operator % or any other built in functions in JavaScript is provided below. This solution instead relies on using another recursion to change negative value of the number.
function isEven(number) {
if (number < 0) {
return isEven(-number);
} else if (number == 1) {
return false;
} else if (number == 0) {
return true;
} else {
return isEven(number - 2);
}
}
console.log(isEven(50)); // true
console.log(isEven(75)); // false
console.log(isEven(-1)); // false
We call isEven(number -2) to go back to the top of the function with the number that was inputed intially but 2 less than before and it will keep doing that until the number is 1 or 0 and then it will be able to return the boolean true or false (even or odd).
I think the problem is to create an isEven function without using a mod/%/remainder operation
function isEven(number) {
if (number < 0) {
number = Math.abs(number);
}
if (number===0) {
return true;
}
if (number===1) {
return false;
}
else {
number = number - 2;
return isEven(number);
}
}
I guess it is important to add to this
it doesn't handle strings
it doesn't handle floats
don't put this into a production application
function isEven(n) {
n = Math.abs(n);
if (n==0)
return true;
else if (n==1)
return false;
else
return isEven(n-2);
}
console.log(isEven(-50)); // → true
console.log(isEven(75)); // → false
console.log(isEven(-75)); // → false
console.log(isEven(-1)); // → false
var isEven = function(n) {
// Get the absolute value of the number
// so we don't have to bother with negatives
n = Math.abs(n);
// We know that if we subtract 2 from our number
// until it is equal to zero, our number was even
// If our number isn't zero, this statement will be skipped
if(n === 0) return true;
// We know that if we subtract 2 from our number
// and it reaches a value of 1, it isn't even
// If our number isn't 1, this statement will be skipped
if(n === 1) return false;
// We subtract 2 from our original number and pass it
// back in to this function to check it over and over again
// until one of the conditions is met and the function can
// return a result
return isEven(n - 2);
}
// We test our function here
console.log(isEven(-21));
This is the leanest method I could come up with. Notice we call our isEven function from within itself and pass in the value of n - 2. This will constantly subtract 2 from our number and check to see if it is equal to 0 or 1 until we get a proper result and return the corresponding boolean.
I hope this clears things up a little.
How about the below code? Seems to work for me.
/*if > 1 keep looking, otherwise return reverse boolean value.
If negative value, inverse, to answer the last part of the question...
Also needed to use parseInt as the text value I used,
was considered a string value!
This being a recursive function which really isn't necessary,
means that in javascript we will get a
stack size exceeded error when the number becomes too large.*/
function isEven(x) {
return (x>1)?isEven(x-2):(x>=0)?!x:isEven(-x);
}
The book wants the following console.log outputs for such values
console.log(isEven(50));
// → true
console.log(isEven(75));
// → false
console.log(isEven(-2));
// → ??
The hint says "When given a negative number, the function will recurse again and again, passing itself an ever more negative number, thus getting further and further away from returning a result. It will eventually run out of stack space and abort." So I'm not sure if what I got represents that but my code and console.log outputs is shown below:
let isEven = function(num) {
if (num ===0) {
return true
} else if (num===1){
return false
} else {
return isEven(num-2)
}
}
console.log(isEven(50));
// → true
console.log(isEven(75));
// → false
console.log(isEven(-2));
// → RangeError: Maximum call stack size exceeded (line 3 in function isEven)```
The question requires that you don't' not to use the modulus operator (%).
// Your code here.
var isEven = function(a){
if (a == 0){ //case 1 : zero is even
return true;
}
else if(a == 1){ //case 2: one is odd
return false;
}
else {
return isEven(Math.abs(a-2)); //solves case 3 (negative numbers)
}
}
console.log(isEven(50));
// → true
console.log(isEven(75));
// → false
console.log(isEven(-1));
// → ?? ....false
This is the "correct" answer from the website. I say "correct" in quotes because I don't understand the 2nd 'else if' statement's return isEven(-n). Why did the author include the option to turn n into a positive number?
function isEven(n) {
if (n == 0)
return true;
else if (n == 1)
return false;
else if (n < 0)
return isEven(-n);
else
return isEven(n - 2);
}
Anyways, thought I'd share since I didn't see anybody post THIS answer.
//define recursive function isEven takes a positive whole number
//returns true if even
function isEven(x) {
//define innner function to loop over value
function find(current) {
//check if value == 0, return true
if (current == 0) {
return true
//check if value == 1 return false
} else if (current == 1) {
return false
//loop over value, subtracting 2 each time until either 0 or 1
//which returns the approriate true/false value based on evenness
} else {
console.log(current)
return find(current -2)
}
}
return find(x)
}
If the number is 1 or -1 so ODD, the function returns false,
If the number is 0 so EVEN, it returns true,
If then number nor 1,-1 nor 0 we have to first check if the number is positive or negative,
If the number is negative and less than -1 we call the function again but increase the number by 2 until we get -1 or 0;
If the number is positive and greater than 1 we call the function again but decrease the number by 2 until we get 1 or 0;
So for example, the number is 5 ->it`s positive and greater than 1 so call the function over and over again and decrease the number by 2 until the result will be 0 or 1:
5->3->1 //->false
function isEven(num) {
if (num == 1 || num == -1) {
return false;
} else if (num == 0) {
return true;
} else {
if (num < -1) {
return isEven(num + 2);
} else {
return isEven(num - 2);
}
}
}
Test result:
console.log(`-35 is even: ${isEven(-35)}`); //-> false
console.log(`-1 is even: ${isEven(-1)}`); //-> false
console.log(`0 is even: ${isEven(0)}`); //-> true
console.log(`32 is even: ${isEven(32)}`); //-> true
I see quite a few examples above using math functions and modulo operator. But I guess the author expects a simple recursive function to make the reader understand the functioning of the same and how if not properly defined it can lead to repetitive function calls and eventually lead to overflow of stack. I believe this code below can help you understand:
function isEven(n){
if(n==0){
return true;
} else if(n==1){
return false;
} else {
return isEven(n-2);
}
}
console.log(isEven(50));
console.log(isEven(75));
console.log(isEven(-1));
function isEven(num){
if(num %2 == 0) {
return true;
} else {
return false;
}
}
console.log(isEven(50));
// → true
console.log(isEven(75));
// → false
console.log(isEven(-1));
// → ??
function isEven(number) {
while(number>= -1)
{
return isEven(number-2) == 0 && number>-1 ? true : false;
}
}
console.log(isEven(-1));
I hope this helps:
const evenOrOdd = (N) => {
if (Math.abs(N) === 0) {
return console.log('Even');
} else if (Math.abs(N) === 1) {
return console.log('Odd');
}
evenOrOdd(Math.abs(N) - 2);
};
Google Chrome Console code results:
It utilizes all three given arguments on the problem. It can handle negative integers. It does not use the modulo operator. Lastly, I wasn't able to see any code snippet similar to what I provided thus I am enticed to share what I can.
false
0
null
undefined
empty string
I use them,but I am still unaware of the marginal difference each prospect in the above list have.
I mostly use 0,false.But I have come across many scripts that uses undefined ,empty string.
I want to know the exact differnce between them.
I know its a silly question,but would be great If i get a small conscise answer.
It's called "truthy and falsy values" if you want to know how to refer to it.
Here is a link to explain the answer to your question: http://www.sitepoint.com/javascript-truthy-falsy/
(Keep in mind when reading the link at the beginning that !!(value) forces the value to be either true or false)
The type is the difference.
false is a boolean, 0 is a number, null is an object, undefined is undefined, and '' is a string.
You pick the type based on what it is being used as. For example:
// There is nothing wrong with this block of code
var num_cats = 7;
if(num_cats){
// num_cats is truthy
}
// This block works but it could be made more clear
var has_cat = num_cats;
if(has_cat){
// This would work, but it doesn't make sense. As a developer I would
// expect that has_cat should be either true or false, not 7.
// One way to convert the number to a boolean would be:
has_cat = !!num_cats
}
The two most confusing falsey values are probably null and undefined.
null basically means that the variable exists, but it's value is unknown.
undefined means that the variable doesn't exist (although a variable can be explicity set to undefined like var x = undefined; and then the variable x exists but it is explicitly not being defined which means that you can treat it as though it doesn't exist.
The list you have are 5 of the 6 "falsy" values in javascript. If you add "NaN" to that, you would have all the falsy values in javascript. So the complete "falsy" list is
1)0
2)""
3)false
4)undefined
5)null and
6)NaN
When used in a "if" statement, these all behave the same way so
if(0)
if("")
if(false)
if(undefined)
if(null) and
if(NaN) would behave the same
You asked for a short concise answer but I think the best way is just showing how it works with some basic test. Apologies for the long answer
//Checking if all the "falsy" values evaluate the same way in a "if" statement
console.log("Checking if(0)");
if(0) {
console.log(" if(0) Will not be reached");
}
console.log('Checking if("")');
if("") {
console.log(' if("") Will not be reached');
}
console.log("Checking if(undefined)");
if(undefined) {
console.log("if(undefined) Will not be reached");
}
console.log("Checking if(null)");
if(null) {
console.log("if(null) Will not be reached");
}
console.log("Checking if(Nan)");
if(NaN) {
console.log("if(NaN) Will not be reached");
}
console.log("Checking if(false)");
if(false) {
console.log("if(false) Will not be reached");
}
//Checking if all the falsy values are equal(==) to each other in a if statement
if(0 == "") {
console.log('if(0 == "") is true');
}
if(0 == false) {
console.log("if(0 == false) is true");
}
if("" == false) {
console.log('if("" == false) is true');
}
if(0 == undefined) {
console.log("if(0 == undefined) Will not be reached");
}
if("" == null) {
console.log('if("" == null) Will not be reached');
}
if(undefined == null) {
console.log("if(undefined == null) is true");
}
if(NaN == "") {
console.log('if(NaN == "") Will not be reached');
}
//Checking for strictly equality between false and falsy values
if(undefined === false) {
console.log("Will not be reached");
}
if(null === false) {
console.log("Will not be reached");
}
if(undefined ===false) {
console.log("Will not be reached");
}
if(0 === false) {
console.log("Will not be reached");
}
if("" === false) {
console.log("Will not be reached");
}
if(NaN === false) {
console.log("Will not be reached");
}
What this means that though these "falsy" values might be used in a "if" statement interchangeably, they all are not equal(==) to each other(particular the set of 0,"" and false with the other three). If a stricter equals(====) is used, none of these would be equal to false, hence perhaps the classification "falsy" instead of false.
Only two of the values you've mentioned are what I would call designated "special values".
null - In most cases this is equivalent to not applicable.
undefined - The implicit version of null
An example for both:
function findByTitle(arr, title)
{
for (var i = 0; i < arr.length; ++i) {
if (arr[i].title === title) {
return arr[i];
}
}
return null;
}
The return value of null indicates that the record could not be found, otherwise it's an object.
function increment(x, by)
{
return x + (by || 1); // by may be undefined
}
increment(4); // 5
In this case, the by argument is not passed, so JavaScript passes it as undefined implicitly. I wouldn't recommend assigning this to a variable though; rather, I would use null.
The other values you have mentioned are not particularly special; they can be used as a starting value, such as building a string value or calculating a sum, but they're not special in their own right.
"" is a string
false is a boolean
0 and NaN are numbers