What does "count=(count && count.length || 0);" do? - javascript

Below is a simple snippet:
pass="Hello";
count=pass.match(/[A-Z]/g);
count=(count && count.length || 0);
alert(count); //1
I just didn't get how the third line works, count=(count && count.length || 0);. What is the logic behind? Thanks!

It's short for:
if (count) {
count = count.length;
} else {
count = 0;
}

It is basically equivalent to
count = (count)? count.length : 0;
or more explicitly
if (count)
count = count.length;
else
count = 0;

If you want it written in English, it means
If count is truthy, get count.length and then if count.length is falsy, get 0. If count was falsy, get 0. Set count equal to what we got.
You can think of being truthy like this (and falsy being the inverse)
function isTruthy(x) {
if (x) return true;
return false;
}

So basically, a=(a && b || c); is short for
if (a)
a=b
else
a=c
I agreed as I have tested with a in which a in {-1,0,null,1}. What made me confused at first was I thought logical operation would always return true/false or 1/0 value. But now I learnt something new. Thanks all!

Related

Check if number is divisible by another number in JS

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

Javascript exercise that looks fine to me but its not working

The exercise is about identifying if all elements in an array are the same and return true if they are or false if they aren't. Below is the code & my logic behind writing the code.
function isUniform(array){
for(var i = array.length - 1; i>=0; i--){
if(array[i] !== array[i-1]){
return false;
}
}
return true;
}
Basically I want to start from the end of the array with the last element and check if its equal with the second-to-last element.If they're equal, the loop will subtract 1 from the "i" variable and the "if statement" will run again. The loop will stop when i reaches -1 and thats the point where every array element was checked and the loop should end, returning true. What am I doing / thinking wrong?
Thanks!
When i becomes 0, you are comparing arr[0] with arr[-1] which is wrong. Your checking condition should be i > 0.
The very last time it run, i is 0, so you're comparing array[0] with array[-1] which is incorrect. Your Boolean condition should be i > 0 so you avoid this issue:
function isUniform(array){
for(var i = array.length - 1; i > 0; i--){
if(array[i] !== array[i-1]){
return false;
}
}
return true;
}
You can use every method for a simplified solution.
const allEqual = arr => arr.every(x => arr[0] == x));
You could create a method that checks the array for your input using ArrayUtils.
public boolean contains(final int[] array, final int key) {
return ArrayUtils.contains(array, key);
}
Traveling so can't debug, but the last iteration of i will be 0 in your code and stop.

How to use ternary operator for a return in JS?

I have a function to check sums in an array :
function checkSum(array, sum) {
// array = [1,4,6,11] sum = 10
var answers = [];
var map = new Map();
for (var x = 0; x < array.length; x++) {
if (map.has(array[x])) {
answers.push([sum - array[x], array[x]])
} else {
map.set(sum - array[x])
}
}
answers.length != 0 ? console.log(answers) : console.log("nada")
}
I originally had the last line just return answers; but let's say I don't want to return an empty array -- instead, I'd rather just log a statement.
why doesn't a return in a ternary conditional work such as this:
answers.length != 0 ? return answers : console.log("nada")
You need to use return answers.length != 0 ? answers : console.log("nada"). The reason it fails is because ternary conditions do not support return in their conditions. Infact, the ternary operator evaluates to an expression and expressions do not contain a return statement.
function checkSum(array, sum) {
// array = [1,4,6,11] sum = 10
var answers = [];
var map = new Map();
for (var x = 0; x < array.length; x++) {
if (map.has(array[x])) {
answers.push([sum - array[x], array[x]])
} else {
map.set(sum - array[x])
}
}
return answers.length != 0 ? answers : console.log("nada")
}
console.log(checkSum([1, 4, 6, 11], 10));
The ternary (conditional) operator expects the "expr1" part (where return answers is) to be an expression - that is, something that can be evaluated to a value, which can be used in other expressions. But a return statement is a statement, one which cannot possibly be interpreted as value, or as an expression; hence, a syntax error is thrown.
Instead of
answers.length != 0 ? console.log(answers) : console.log("nada")
either use a standard if statement:
if (answers.length !== 0) return answers;
console.log('nada');
or, if you just want to log, put the conditional operator inside the console.log instead:
console.log(
answers.length === 0
? 'nada'
: answers
)
I used ternary operators like this a lot in the past. It's fun, and keeps it to one line.
It can certainly be done, as Ankit shows, by putting the return statement out front
return answers.length != 0 ? answers : console.log('nada')
But I would recommend you use a classic if statement for this. Particularly since you're testing whether to return a value or just log one.
if (answers.length != 0) {
return answers;
};
console.log('nada')
I would go even further and recommend that you return the same value type no matter what. This will go a long way for using your function, well - functionally. In this case, that would involve still returning the array (even if it's empty) and logging the nada as well if empty.
if (answers.length == 0) {
console.log('nada');
};
return answers;

Function returns zero, but why does it not fail when method spelled wrong?

In the for loop: counter < (x.lenght) is spelled wrong, but the function returns zero. When corrected to x.length the function returns the correct number of Bs, 3. 1) Why is zero being returned? 2) Why does javascript not catch this error? 3) For the future, anything I can do to make sure these types of errors are caught?
function countBs(x){
var lCounter = 0;
for (var counter = 0; counter < (x.lenght); counter++){
if((x.charAt(counter)) == "B"){
lCounter++;
}
}
return lCounter;
}
console.log(countBs("BCBDB"));
Accessing x.lenght is returning undefined causing the for loop to terminate immediately. Therefore the initial value of lCounter is returned.
You can check for the existence of a property in an object by using the in keyword like so:
if ( 'lenght' in x ) {
...
x.lenght is returning undefined. Comparison operators perform automatic type juggling, so undefined is converted to a number to perform the comparison, and it converts to NaN. Any comparison with NaN returns false, so the loop ends.
Javascript doesn't catch this error because it uses loose typing, automatically converting types as needed in most cases.
There's no easy way to ensure that typos like this are caught. A good IDE might be able to detect it if you provide good type comments.
JavaScript does all kind of crazy coversions, instead of throwing an error: https://www.w3schools.com/js/js_type_conversion.asp
'undefined' in particular becomes NaN when necessary (very last line of the very last table), which results in 'false' when compared to a number (regardless of <, >, <=, >=, == or !=, they all fail, NaN does not even equal to itself).
If you want to catch or log an error to make sure your variable property is defined. Please see code below:
function countBs(x){
var lCounter = 0;
if(typeof x.lenght == 'undefined')
{
console.log('Undefined poperty lenght on variable x');
return 'Error catch';
}
for (var counter = 0; counter < (x.lenght); counter++){
if((x.charAt(counter)) == "B"){
lCounter++;
}
}
return lCounter;
}
console.log(countBs("BCBDB"));
To catch this particular error, set lCounter to -1 instead of 0.
That will ensure that the loop will run at least once if the for condition is correct.
You can return (or throw) an error if the loop isn't entered.
Otherwise, return lCounter + 1 to account for the initialization of -1.
function countBs(x) {
var lCounter = -1;
for (var counter = 0; counter < (x.lenght); counter++) {
if((x.charAt(counter)) == "B") {
lCounter++;
}
}
if(lCounter == -1) {
return 'Error';
} else {
return lCounter + 1;
}
}

javascript order of execution

var c = false;
if(c=[] && c.length==0)alert('hi');
hi is not alerted because c is still false when it executes the second operand of &&, can someone explain how the boolean operands in if condition are executed and in what order?
I believe this is just a precedence issue - && is binding tighter than =. Your code is equivalent to:
if (c = ([] && c.length == 0))
{
alert('hi');
}
So it's assigning c the value false rather than the empty array.
Try this instead:
if ((c = []) && c.length == 0)
{
alert('hi');
}
EDIT: To address Tryptich's comment - I did try this before posting :) As CMS said, an empty array is considered true. Try this:
if (c = [])
{
alert('empty array is true');
}
or even just this:
if ([])
{
alert('empty array is true');
}
I checked the spec before posting - I was somewhat surprised that an empty array is considered true, but it is...

Categories