I want to push an error message to a field if it is invalid.
this code works
let message = [];
if (!isvalid) {
message.push("Please enter a value");
}
How can I achieve this with ternary operator.
The way I did.
message.push((!isvalid) ? "Please enter a value" : null)
But this code is also pushing null to the array.
like:: message=[null]
Honestly, it's not a good way to do it. It does not make sense to use a ternary where one logical branch of the condition leads to ...do nothing. Ternary only makes sense where you want to return one of two values depending on the condition.
If you want to be concise you could use:
!isValid && message.push('foo');
though some linters won't like you for it. It has the disadvantage that it is less readable than a simple if. If you must use the ternary, you could also do this:
!isValid ? message.push('Please enter a value') : void 0; // or null
but it's ugly and bad because of that useless hanging false branch of the ternary expression. Don't do it.
Can you try (!isvalid) ? message.push("Please enter a value") : null ?
Related
I want to use the if else statement in the ternary operator
if (open) {
setOpen(false)
} else {
setOpen(true)
navigator.clipboard.writeText(link)
}
There is no problem in "if" I cant figuring out how to convert else to ternary. Like something the code below:
open ? setOpen(false) : setOpen(true) ; navigator.clipboard.writeText(link)
Something like this or is there another method to do the job?
Don't.
You're trying to use the ternary conditional operator for the wrong reason. It is not a drop-in replacement for any if block.
The ternary conditional operator is an expression. It resolves to a value, which can be used elsewhere. For example:
let x = someCondition ? 1 : 0;
The expression resolves to a value, either 1 or 0, and that value is used in an assignment statement.
The code you're showing is not an expression. What you have is a series of statements, conditionally executed based on some value. An if block is a structure for conditionally executing statements.
The code you have now is correct.
Yes, it's possible to write multiple statements in ternary if else cases:
The format is:
condition ? codeLine1 : ( codeLine2 , codeLine3 )
Which makes your statement as:
open ? setOpen(false) : (setOpen(true), navigator.clipboard.writeText(link));
Combine multiple statements in parenthesis separated by commas in between each line.
That being said it's recommended to use old fashioned way of if-else statement if multiple statements are involved.
Please select answer if it helps and let me know if any questions.
Yes. it is possible (although not a best practice and not recommended)
they way to to it is by:
Put everything inside parenthesis
Seperate each statement with comma (",")
e.g:
condition ? statement1 : ( statement2, statement3, statement4 )
Try this snippet:
let a = 1;
let b = 1;
a == b ?
(console.log("they"),console.log("are"), console.log("equal")) :
(console.log("they're"), console.log("not equal"));
categoryId = categoryId === '' && location.pathname.match(regExp) ?location.pathname.match(regExp)[1] : categoryId
I know this is a ternary operator but what does categoryId === '' && location.pathname.match(regExp) do here? particularly no clue on '' && location.pathname.match(regExp)
is it a boolean?
So I will take you through the piece of code you have provided as detailed as my free time now can permit me and from the top of my head.
categoryId is a variable that is accepting the result of what is on the right. thus the = sign.
categoryId === '' This part here is simply making a comparison between the results in categoryId to an empty string '' which will return a boolean. So its saying "is the result in categoryId an empty string? true or false.
&& this is saying that we are going to check under condition so check the above one and another...
location.pathname.match(regExp) this is the 2nd check... checking if a url path matches a certain regex definition/condition in regExp (you have not provided that so I can't say much there)
Now note that due to the use of &&, both conditions must return true before the true statement is run else it will be false.
? this is saying; if true, run the next condition/statement
location.pathname.match(regExp)[1] this is the condition/statement it will run if result is true.
: this means if it is false, run the next condition/statement
categoryId this is the condition to run when the result is false.
This type of conditional statement is called a "Conditional/Ternary Operator" find a bit more details here: https://www.w3schools.com/js/js_comparisons.asp
I hope this helps. If its not clear let me know so I clarify. Best way to learn!
I would like to print "Error" message every time a word is not found in a variable from prompt input, it does work with single comparison like for example if (variable!== "word"). But whenever i try to compare multiple words that are defined in the if statement with (variable!= "word1" || variable! != "word2") it returns true even if the word is "word1" or "word2".
var input = prompt ('Enter a string: "word1", "word2" or "word3"?');
if(input!== "word1" || input!=="word2" ||input!== "word3"){
console.log("Error");
}
else{
//do some functions
};
This is what you're looking for:
if ( !['word1', 'word2', 'word3'].includes(input)) console.log("Error");
If the input is not part of the array (correct answers), then the Error will be logged.
Your specific error is because of using || (OR) instead of && (AND).
You want to ask "if the input isn't "word1" AND it also isn't "word2" AND it also isn't "word3"", and you can write the condition exactly like that. When you use OR, the if statement will always be true since the input can't be all 3 values at once.
Either way, I agree with Jordan that you ought to use an array.includes() for checking against many valid inputs.
You can use indexOf with an array containing the words.
const searchArray = ["word1","word2","word3"];
if(searchArray.indexOf(input) == -1){console.log("Error")};
I'm very new to JS - only a couple days in.
Trying to write a very basic prompt evaluated by an if statement.
When I run the code below, the user is prompted, but the statement is never evaluated by the if statement.
Any help? -- I realize the answer is probably simple and obvious, but as a SUPER beginner, what do I do?
var bool = prompt("What is an example of a boolean?");
if (typeof(bool) === "boolean") {
print("correct! that is a boolean");
print(bool) ;
};
In this case, assuming the user inputs something in the prompt, the type of the bool variable will always be a string. You'd rather check if the input compares to the string "true" or "false" etc., like this:
if (bool.toLowerCase() == "true" || bool.toLowerCase() == "false") {
...
}
I have a pretty much simple logic in a return function, but it doesn't work as expected. Of course I can make the code slightly longer and solve the issue, but I want it to be as small as possible.
Here is my code:
#Return title if exists or false otherwise
getPageTitleFromMainContent = (mainContent) ->
mainContent.find('#pageTitle') ?.length ?= false
if y = (getPageTitleFromMainContent $("#mainContent"))
y.css color:red
As you see, if it finds the #pageTitle in #mainContent, it should make it red. But the function doesn't return the #pageTitle if found, it returns .length.
From js2coffee.org I see that the code is compiled into:
var getPageTitleFromMainContent, y;
getPageTitleFromMainContent = function(mainContent) {
var _ref, _ref1;
return (_ref = mainContent.find('#pageTitle')) != null ? (_ref1 = _ref.length) != null ? **_ref1 : _ref.length = false : void 0;**
};
if (y = getPageTitleFromMainContent($("#mainContent"))) {
y.css({
color: red
});
}
And it should be _ref : _ref.length = false : void 0;, not _ref**1** : _ref.length = false : void 0; .
http://jsfiddle.net/X8VjJ/1/
Thank you!
if it finds the #pageTitle in #mainContent, it should make it red
You can accomplish this with the much simpler:
$('#mainContent #pageTitle').css(color: 'red')
Since, if it doesn't find #pageTitle in #mainContent, it will try to change the css of an empty set of elements -- a no-op.
The code as you've presented it doesn't really make sense. ?. is unnecessary, as the jQuery selector will not return null or undefined if it doesn't match; it will return an empty set of elements. So it will always be returning length, which will always be a number, so the assignment will never execute, since it depends on length returning null or undefined. Which is good, since you probably don't want to set the length of the elements to false.
Finally, this isn't the ternary if statement. CoffeeScript's ternary if statement looks like this: if foo then bar else baz.
Not sure that code makes sense. You're effectively trying to assign TO the length property, unless length is defined. If it is defined, it simply returns the length property. Looks like the code and behaviour is correct, but your understanding of the existential operator and return values is wrong. If you want to return the found element you probably need to disconnect it from the length check.
Maybe something like:
getPageTitleFromMainContent = (mainContent) ->
arr = mainContent.find('#pageTitle')
if arr.length then arr else false
As Ian explained in his more elegant answer, you do not need to use the existential operator on arr (assuming jquery), since it will always be an array of elements (with zero length if not found).