Simple javascript if statement with charAt is not working - javascript

Its simple, if a user enters a number that does not beggin with 6 or 9, he gets error:
console.log($(this).val().charAt(0));
if($(this).val().charAt(0) != 6 || $(this).val().charAt(0) != 9){
x=false;
}else {
x=true;
}
Console.log correctly displays the first character.. that means the value exists..
But no matter if I type 6 or 7 or 9, i will always get false... Why?

Whatever the value of somevar,
somevar!=6 OR somevar!=9
is always true.
The best solution here would probably be a regular expression:
var x = /^[69]/.test($(this).val());

You need to invert the logic conditions as both states cannot possibly be true at the same time, so x is always set to false. Try this:
var chr = $(this).val().charAt(0);
if (chr == '6' || chr == '9') {
x = true;
} else {
x = false;
}
From there you can now see that you don't even need the if condition as you can set x directly, like this:
var chr = $(this).val().charAt(0);
var x = chr == '6' || chr == '9';

Related

Extended Ternary expression

I know you can do ternary expressions in Javascript for an if - else statement, but how about an else- else if- else statement? I thought that surely this would be supported but I haven't been able to find any info about it and wasn't able to get it to work just hacking around.
In contrast to Robby Cornelissen's answer - there is no problems with readability if you format it properly (and not writing PHP, since it messed up the operator by making it left-associative in contrast to all other languages that have that construct):
var y =
x == 0 ? "zero" :
x == 1 ? "one" :
"other";
EDIT
What I was looking for is a shorter version of "if expression 1 is true, return expression 1. Else if expression 2 is true, return expression 2. Else return expression 3". Is there no clean way to do this?
There is: expression1 || expression2 || expression3. (It would have been nice if you had put this into your question in the first place.) This is commonly used for default values:
var defaults = null;
function hello(name) {
var displayName = name || (defaults && defaults.name) || "Anonymous";
console.log("Hello, " + displayName + ".");
}
hello("George");
// => Hello, George.
hello();
// => Hello, Anonymous.
defaults = {};
hello();
// => Hello, Anonymous.
defaults.name = "You"
hello();
// => Hello, You.
However, it is important to be aware of the conditions for truthiness. For example, if you expect "" or 0 to be a valid value that does not need to be replaced by a default, the code will fail; this trick only works when the set of possible non-default values is exactly the set of truthy values, no more and no less. E.g.
function increment(val, by) {
return val + (by || 1); // BUG
}
increment(10, 4);
// => 14
increment(10, 1);
// => 11
increment(10);
// => 11
increment(10, 0);
// => 11 <-- should be 10
In this case you need to be explicit:
function increment(val, by) {
return val + (typeof(by) === "undefined" ? 1 : by);
}
I wouldn't recommend it because of readability, but you could just nest ternary operators:
var y = (x == 0 ? "zero" : (x == 1 ? "one" : "other"));
This would be the equivalent of:
var y;
if (x == 0) {
y = "zero";
} else if (x == 1) {
y = "one";
} else {
y = "other";
}
You can extend a ternary condition if you're good. It gets to be messy though.
var number = 5;
var power = 2;
var ans = Math.pow(number,power);
var suggest = ( ans == 5 ? 5 : ans == 10 ? 10 : ans == 15 ? 15 : ans == 25 ? "works" : null);
console.log(suggest);
I may have added to many because I'm on my phone haha but try it in your developer panel.

JavaScript if else statement ignored

I have a simple if statement below:
function calculateTotal() {
if (tanksize != 1 || tanksize != 2) {
var setupPrice = basicPrice + StatPrice() + DigiStatPrice() + IRPrice() + UVPrice() + cagePrice();
var setupPrice2 = toFixed(setupPrice, 2);
} else {
var setupPrice = basicPrice;
var setupPrice2 = toFixed(setupPrice, 2);
}
//display the result at the top of page
var divobj = document.getElementById('totalPrice');
divobj.innerHTML = "£" + setupPrice2;
//display the result at the bottom of page
var divobj = document.getElementById('totalPrice2');
divobj.innerHTML = "£" + setupPrice2;
}
But when the tanksize variable is set to 1 or 2, the setupPrice variable is still calculated by adding the basicPrice + StatPrice...etc.
You need to use:
if (tanksize !== 1 && tanksize !== 2) {
with the && operator, or
if (!(tanksize ===1 || tanksize === 2)) {
In your code, you have the first block executing any time the value is not 1 or is not 2, which equates to it always executing.
If the value is 1, then tanksize != 2 is true so tanksize!=1 || tanksize!=2 is true.
If the value is 2, then tanksize != 1 is true so tanksize!=1 || tanksize!=2 is true.
In other words, tanksize!=1 || tanksize!=2 is always true, no matter what the value of tanksize is.
This statement is always true:
if(tanksize!=1 || tanksize!=2){
because, when tanksize = 1, tanksize is different of 2
and when tanksize = 2, tanksize is different of 1.
It is not a javascript error, you just need to change your logic to make the right test in the if...
Try if(tanksize!=1 && tanksize!=2){ instead of if(tanksize!=1 || tanksize!=2){
Your Logic is wrong..
As a matter of fact, OR Operator for two NOT EQUALS is always TRUE ( check boolean table for this) and the conditional statement "if" checks for TRUE or FALSE, hence your code will always return TRUE
Use something like
if(tanksize!=1 && tanksize!=2){
# Your code
}
(tanksize!=1 || tanksize!=2) always will be true by this statement. Change operator || to &&
your first condition is always true, cuz for example if some x = 1, is different of 2 and vice versa.
so this condition is kind of equal to.
if(true) {
// ...
}

A quick way to test equality of more than 2 values at once?

I was wondering if there was a quick way to test the equality of more than two values in js. Something similar to (= 6 6 6).
In the console, I tried things like...
1 == 1 == 1 == 1
true
2 == 2 == 2 == 2
false
0 == 0 == 0
false
0 == 0 == 0 == 0
true
...which was amusing, but also puzzling.
Is there a quick way of doing this in js?
Thanks.
The reason you got unexpected behavior is because we need to adjust your expectations in js a bit ;) 2 == 2 == 2 == 2 does 3 comparisons, all from left to right. The first comparison is the leftmost 2 == 2, which evaluates to true. After that we get the result of the first comparison being compared to (what is in this case) the 3rd 2. Ie, true === 2, which is false. And finally, we get false === 2, which is also false.
It might help to visualize it as such:
(((2 == 2) == 2) == 2)
I think in general a === b && b === c might be what you're looking for.
EDIT: Ah, and sorry I keep switching out the == for ===. It's just habit. And it's a habit I'd recommend. the === operator doesn't do type casting, so it evaluates the value proper, not a casted version of the value.
It's because true == 1 but true != 2
You can try:
function isEquals() {
var flag = true;
for(var i=1; i<arguments.length; i++) flag = flag && (arguments[i] == arguments[0]);
return flag;
}
isEquals(2,2,2); // true
or:
function isEquals() {
var ar = arguments;
return Array.prototype.every.call(arguments, function(a){return a==ar[0];});
}
Yes you can, but you need to use the "Logical Operators" like the && or || to check more than 1 statement like (x<1 && y>0).
You can use this as a quick easy reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators
If you have more than three values, it might be more convenient to create a function for use on an array:
function allEqual(arr) {
return arr.every(function (x, i) {
return i === 0 || x === arr[i - 1];
});
}
allEqual([1, 1, 1])
ES6:
function allEqual(...arr) {
return arr.every((x, i) => i === 0 || x === arr[i - 1]);
}
allEqual(1, 1, 1)
As an addition to #vp_arth's answer you could even add a method to the Array prototype
Array.prototype.isHomogeneous = function(){
return Array.prototype.every.call(this, function(c,i,a){ return c === a[0];})
}
So you could do
[1,2,3].isHomogeneous() = false
[1,1,1].isHomogeneous() = true

javascript keeps skipping my if statement thats inside two loops

Ok so im talking in some unput from the user, it must be 4 numbers, and the digits must not be the same. so everything is working accept the part where i check the 4 numbers against each other. i put the string into an array and then compare the array, by
checking the first one against the 2nd, 3rd, 4th,
then i check the second one against the 3rd, and 4th
then i check the third number against the 4th
My issue is the if statement will not work no matter what i try it gets bypassed everytime. I add random returns into the code to see where it goes and it always returns 12 no matter what even if the numbers i enter are 1111 it still passes.
Ive spent hours trying different stuff please help me!!
function validate(guess){
var user_guess = guess;
var valid = true;
var counter = 0;
parseFloat(user_guess);
if(user_guess.length == 4){
if((user_guess == null) || (isNaN(user_guess))){
validation_alert();
}else{
var guess_string = toString(user_guess);
var guess_array = guess_string.split('');
var guess_array2 = guess_array;
for(var i = 0; i < 3; i++){
counter = i + 1;
for(c = counter; c < 4; c++){
if(guess_array[i] == guess_array2[c]){
return 11;
valid = false;
validation_alert();
}
}
}
if(valid == true){
return 12;
}else{
return 13;
validation_alert();
}
}//if null
}else{
validation_alert();
}//if 4 end tag
}// function close
Just to prove to you that JavaScript uses function scope and not block scope (if else for ...) which means every var you declare moves automatically to the top of the current function it's running in.
Also note that when you return something you will exit the current function and not execute anything after that.
If you check against length you can be sure it's going to be a number so use === instead which checks against it's type (number, string, bool) as well.
Your 2 first if statements should be reversed I think. In anycase user_guess == null will never validate as the previous if checks on the length === 4.
Normally when you use return every block scope should return something. I haven't edited this but that's expected in strict javascript.
It seems more logical to start with valid=false and you will only set it to true when you are sure it's true. I'll leave that up to you.
function validate(guess){
var user_guess = parseFloat(guess),
guess_string,
guess_array,
guess_array2,
valid = true,
counter = 0,
i = 0,
c;
if (!user_guess || isNaN(user_guess)){
validation_alert();
} else {
if (guess.length === 4){
guess_string = user_guess.toString();
guess_array = guess_string.split('');
guess_array2 = guess_array;
for (i; i < 3; i++){
counter = i + 1;
c = counter;
for (c; c < 4; c++){
if (guess_array[i] == guess_array2[c]){
valid = false;
validation_alert();
return 11;
}
}
}
if (valid){
return 12;
} else {
validation_alert();
return 13;
}
} else {
validation_alert();
}
}
}
If you just need to check if the string has 4 unique number digits its much easier this way:
function isValid(str){
var unique={};
for(var i=0;i<str.length;i++){//for each character in the string
unique[str[i]]=true;//we add the character as a key in unique object(the =true doesnt really matter)
}
var chars=Object.keys(unique);//we get an array with the keys in the object(we get an array with the unique characters)
if(chars.length != 4) return false; //if the unique chracters are different than 4, its not valid so return false
chars.sort();//we order the array in lexicographical order
if(chars[0]>= '0' && chars[0] <='9' && chars[3]>= '0' && chars[3] <='9') return true;//if the first character and the last ones are digits, then the ones in the middle wil be digits as well because of the sort we made. If they are, return true
return false;//if they are not both digits, return false
}
console.log(isValid('1111'))//false
console.log(isValid('9230'))//true
console.log(isValid('1343'))//false
console.log(isValid('a412'))//false
console.log(isValid(''))//false

Change color depending on value

I don't why this is not working. Can somebody tell me what is the problem with this?
var x = $('#clicked_info').val();
if(x == 1) {
$('#companyname_ph').css({'color':'yellow'});
}
else if(x == 2) {
$('#companyname_ph').css({'color':'red'});
}
You need to use parseInt to convert a string to an integer.
var x = $('#clicked_info').val();
if(parseInt(x) == 1){
$('#companyname_ph').css({'color':'yellow'});
} else if(parseInt(x) == 2){
$('#companyname_ph').css({'color':'red'});
}
OR use string comparison
if(x == '1'){
val returns a string
x == 1 shoulb be x == '1'
x == 2 should be x == '2'
Or you can convert x to int using the following.
var x = $('#clicked_info').val();
x = parseInt(x);
like the other folks here have noted, you should use parseInt when you want to convert a string representation of an integer to a number type. I would add that you should provide a radix to parseInt because if you don't, you may get unexpected results if your string starts unexpectedly with "0x" :)
try doing:
var x = parseInt($('#clicked_info').val(), 10)

Categories