I learnt about tenary operator recently from the JavaScript section of freecodecamp.org.
Now I'm trying to use it.
var answer =prompt("Enter your answer here ");
return answer.toString().toLowerCase()===pool[i]["Answer"].toString().toLowerCase() ? scores++ : scores=scores
What I want, if true, is to increment var scores and also console.log("Correct answer") and if false, reassign the previous value of scores and console.log("Wrong answer")
Is there a way to achieve this with the tenary operator? Or should I just use the conventional if-else statements.
Do an if {} else {} if you want to do more than an assignment, such as a console.log():
var answer = prompt("Enter your answer here ");
if(answer.toLowerCase() === pool[i]["Answer"].toLowerCase() {
scores++;
console.log("Correct answer");
} else {
scores = previousScores;
console.log("Wrong answer");
}
Notes:
no need for .toString() because the prompt returns a string.
I am not sure what you mean by "if false, reassign the previous value of scores", so I added a previousScores variable to represent that.
UPDATE 1: Technically it is possible to use a tenary operator with multiple statements, but it becomes unreadable as #Phil pointed out: return condition ? (console.log("true"), "true value") : (console.log("false"), "false value")
Related
I have a pdf with two input text boxes. 1.) Item Code and 2.) Item
I am trying to populate "Item" based on "item code" but the nested statements are giving me data for the first else if condition below for all cases. For example, I should get "20% 100 ML" for code 5009113 and "25% 50ML" for code 5009111, and so on. Instead, I am getting "20% 100ML" for any and all values in item code. Please help me with this :)
var v = this.getField("Item Code").valueAsString;
var RXC = Number(v);
if (v=="") event.value = "";
else if (RXC=5009113) event.value = "20% 100ML";
else if (RXC=5009111) event.value = "25% 50ML";
else if (RXC=5009112) event.value = "25% 100ML";
else if (RXC=5009099) event.value = "5% 250ML";
else if (RXC=5009110) event.value = "5% 500ML";
The conditions in your else if statements contain expressions such as the following:
RXC=5009113
This is an assignment expression: you are assigning the value 5009113 to the variable RXC. This is considered to be a "truthy" statement and therefore it evaluates to true and therefore no more else if statements are considered.
Instead of this you should use the comparison operator ===. Also take a look at this question regarding the difference between == and === - and why it is better to use === here.
I personally prefer to use white space characters to separate out the parts of an expression:
else if (RXC === 5009113)
It makes it easier (for me) to see what is going on - and easier to spot where I may have used = instead of ===.
But I would recommend re-working the entire section of code to use "if/else" with braces, as follows:
if (v === "") {
event.value = "";
} else if (RXC === 5009113) {
event.value = "20% 100ML";
} else if (RXC === 5009111) {
event.value = "25% 50ML";
} ...
And probably even better would be to use a switch statement, as mentioned in the comments. This is going to be less cluttered than several if/else statements: easier to read, debug, and maintain.
I'm wondering
1. why the console is throwing out a specific result
2. how to get the console to throw out the result I want based on the code
I've tried both removing the else condition and adding it, but I'm stuck because I don't know what the code is thinking.
isMarried = false;
if (isMarried = false) {
isMarried = 'Nope, not at all! ';
}
console.log(firstName + ' is a ' + age + ' year old ' + job + '. Is he married? ' +isMarried );
//This outputs false for isMarried instead of "Nope, not at all!"
If I add an else like so:
if (isMarried = false) {
isMarried = 'Nope, not at all! ';
} else {
isMarried = 'Oh yeah';
}
//The same code outputs "Oh yeah." I'm a bit confused why it's happening like this. Any thoughts?
Basically, I expected the computer to see isMarried as a false boolean, and if this is the case, I wanted to set the variable to the string seen above. Otherwise, if I changed it to true, for example, the it would be a different string.
You don't use assignment operators (=) inside conditionals. Inside conditionals, you need to use comparison operators (==, !=, >=, <, etc.)
You are assigning a value to your isMarried(false) inside the IF statement .. you need to use compare operators like ==
a == b // this operator will return a `Boolean` value (`true` Or `false`)
a = b // this operator will return the value of `b` (right value)
So :
isMarried = false // this will return the right value (false) which means the IF statement
// won't work and the else code will be auto executed
Try this, Give me green tick if this code satisfied ya..
var isMarried = false;
if(isMarried==false){
isMarried = "Not at all";
}else{
isMarried = "Oh yeah";
}
console.log(isMarried)
Can someone please explain this strange behavior in Javascript? When I do comparisons using the match() method I don't get the expected result.
var mat_1 = "wpawn";
var mat_2 = "wRook";
//compare both; do they have the same first letter?
alert(mat_1.match(/^\w/) + " seems equal to " + mat_2.match(/^\w/));
if (mat_1.match(/^\w/) === mat_2.match(/^\w/)) {
alert("They are really equal")
}
//another approach
if (mat_1[0] === mat_2[0]) {
alert("Yes! Equals")
}
match produces an array. You should really use an array comparison function, but for the sake of simple demonstration, try this - the first match value is selected and compared. All 3 alerts are triggered:
var mat_1 = "wpawn";
var mat_2 = "wRook";
//compare both; do they have the same first letter?
alert(mat_1.match(/^\w/)+" seems equal to "+mat_2.match(/^\w/));
if(mat_1.match(/^\w/)[0] === mat_2.match(/^\w/)[0]){alert("They are really equal")}
//another approach
if(mat_1[0] === mat_2[0]){alert("Yes! Equals")}
Match returns an array of matches:
String.prototype.match(pattern: Regex): Array<string>
Your first evaluation will always fail as you are comparing two arrays.
This is the correct way for what you are trying to achieve.
'myWord'.match(/^\w/)[0] == 'mIsTeRy'.match(/^\w/)[0]
Although if you wanna truly use the regex to check the first letter, I wouldn't recommend it. Too much overhead for something too trivial (just my two cents).
Have fun coding! :)
in the following lines of code you are checking the variables mat_1 and mat_2 for whether both the words starts with 'w', btw match() returns an array
if (mat_1.match(/^\w/) === mat_2.match(/^\w/)) {
alert("They are really equal")
}
you can try something like
if (["w"] === ["w"]) {
console.log("seems equal");
} else {
console.log("not equal");
}
for array comparison you can check this post
what you have to do here is
if (["w"][0] === ["w"][0]) { // match for the elements in the array
console.log("seems equal");
} else {
console.log("not equal");
}
I have a function to test if a prompt input is a number, like so:
function myFunction()
{
var person = prompt("Please enter your name", "");
if (person != null)
{
if(isNaN(person))
{
document.write("hello " + person + "<br><br>");
}
else
document.write("You gave me a number");
}
else
{
document.write("You didn't answer.<br><br>");
}
}
but every time I enter a number it keeps outputting hello + the number. I've been googling this function for quite some time and it doesn't make sense to me, it seems like it should work. Why is person returning true?
NaN is a special value in Javascript. What isNaN does is check to see if the value passed is equal* to this special value. If you want to check if something is, say, not a stream of numbers, you can use a regular expression:
if (!/^\d+(\.\d+)?/.exec(person)) {
Or parse the value as a number and see if it converts back to the same string:
var n = parseFloat(person);
if (n.toString() !== person) {
*There's a reason that we don't use === but it's outside the scope of this answer.
The isNaN function checks if a value is NaN. NaN is a value that occurs when making operations that require numbers with non-numbers. Please see the documentation.
However the function does not check if the value is of type number. Too check if a value is of type number use the typeof operator
typeof person === 'number'
Your code is the correct way of using the isNaN method. However for anyone else reading this post I have seen a strange anomaly where the documented usage of IsNaN hasn't worked properly and I got around the problem by combining the parseInt method with the IsNaN method. According to the W3c web site (https://www.w3schools.com/jsref/jsref_isnan.asp) the IsNan('123') should return false and IsNan('g12') should return true, but I've seen scenarios where this isn't the case.
If you're having trouble getting the documented methods to work try this code below:
var unitsToAdd = parseInt($('#unitsToAdd').val());
if(isNaN(unitsToAdd)) {
alert('not a number');
$('#unitsToAdd').val('1');
returnVal = false;
}
Alternatively you can try this method which is well tested.
function isNumber(searchValue) {
var found = searchValue.search(/^(\d*\.?\d*)$/);
//Change to ^(\d*\.?\d+)$ if you don't want the number to end with a . such as 2.
//Currently validates .2, 0.2, 2.0 and 2.
if(found > -1) {
return true;
}
else {
return false;
}
}
Hope this helps.
I am trying to make a simple if-else statement, but when I run the code, it always returns true, even if I enter something in the prompt that I know should be false. I have ran it through JsFiddle, and it seems that the code snippet is perfectly valid.
var captchaTest = 5;
var captchaInput = prompt('What is five plus five?');
if ('captchaTest + captchaInput = 10') {
alert('You passed, you may continue'); window.location.href = 'pagepass.html';
}
else {
alert('Failed, try again.'); window.location.href = 'main.html';
}
Can someone tell me what I did wrong?
Non-empty strings in JavaScript are truthy. 'captchaTest + captchaInput = 10', when evaluated as Boolean, is true.
You need to remove the quotation marks and change = to ==:
if (captchaTest + captchaInput == 10)
Apart from the answer that other provided I would also make a point that as per your captcha question, your condition should be like this
if (captchaInput == 10){
alert('You passed, you may continue'); window.location.href = 'pagepass.html';
}
else {
alert('Failed, try again.'); window.location.href = 'main.html';
}
I don't see any use of the variable captchaTest
You shouldn't be using a 'captchaTest + captchaInput = 10' as it is a String and always evaluates to true unless it is an empty one.
Also you should use comparison operator == instead of assignment operator =
So remove the quotes
if ((captchaTest + captchaInput) == 10)