How to set a value to a variable inside ternary - javascript

Is it possible to set the value of a variable inside a ternary based on a state change?
Something like:
{ this.state.change ? myObj.changeIt = true : null }
writing it like this returns an error: Assignment to property of function parameter 'myObj'

You need parenthesis for an assignment inside of a ternary, because you have some expressions left hand side.
this.state.change ? (myObj.changeIt = true) : null;
Beside that, you better take a imperative style.
if (this.state.change) myObj.changeIt = true;

Related

My If Statement is not functioning in Jquery

I have assigned my selected option to a variable. However, when I use my if statement to compare the variable and a string, the if statement executes the code regardless of if the variable is equal to my string.
I have tried rewriting the code and doing some research on javascript if statements but, to my knowledge, I am unaware of any errors in my code.
$(document).ready(function(){
$("#main_dropdown").change(function(){
let selectedMajor = $(this).children("option:selected").val();
if (selectedMajor = 'arts') {
alert("Your selected major is: " + selectedMajor);
}
});
});
You are attempting to compare them using = which will actually assign 'arts' to the selectedMajor variable. Use == instead which will compare them.
If you need to make sure the types are the same as well, use ===.
In javascript = is used to assign a value to a variable, == is actually the eqaulity check operator.
Also use trim() function to check the compared value doesn't contain any leading/trailing space.
Try changing,
if (selectedMajor = 'arts') {
as,
if (selectedMajor.trim() == 'arts') {
Hope this helps!.
Your if statement is using the assignment =. You want to compare with the ==.
selectedMajor = 'arts' is an Assignment which will always return the value on left hand side.
Simple assignment operator is used to assign a value to a variable. The assignment operation evaluates to the assigned value
let x = 3;
console.log(x = 3)
If you want to compare the value you should Abstract Equality == or Strict Equality ===
let x = 3;
console.log(x === 3)

JavaScript get condition text (or array of values) of ternary's condition operator

[wasn't sure how to word this question exactly, but] say I have some code:
var myValue = 6;
var newValue = myValue == 6 ? myValue : 3;
notice that I'm using the ternary operator to check if a variable fulfils a certain condition, and if so, then I set my newValue to that variable, and if not, something else.
So the (slight) problem:
In a case like this, I have to actually write the variable name twice (myValue == 6 ? myValue : ...), this usually isn't a problem, but say I have a very long variable name, or even the property of a certain array or something else I don't want to manually write out, or even make a new variable; I just want to set the new variable equal to the value of the variable in the condition.
If my condition is simply if the expression exists, then I could obviously do:
newValue = myValue || 3;
but if I'm checking any other condition, I have to write the checking-variable twice, so is there any way to access the ternary's condition text, at least, or even an array of the variables involved in the condition so I have some kind of hope to access it, or is there any other way to do one-line conditions like this, without assigning a new variable?

What is this ternary expression doing?

I have a function I'm testing that takes two arguments Definition and Element, and has a ternary statement in it that goes like
otherThingName: (_.has(Definition.thing, 'thingName') ? Element[Definition.thing.thingName] : null)
Now Definition.thing.thingName will exist, but Element does not have a property named Definition.
Is that property being set on Element while at the same setting otherThingName?
A ternary expression is sort of a short hand if/else, so in the first instance, its testing the statement (_.has(Definition.thing, 'thingName').
I don't work with underscore, but it looks like this test is checking if Definition.thing has a property of thingName.
If this comes back true, it will set otherThingName to be Element[Definition.thing.thingName].
Otherwise it will set it to null.
Element[Definition.thing.thingName] is looking at an object called Element, and pulling back the property with the key matching the value of Definition.thing.thingName.
For example, if
Definition.thing.thingName == "name",
Element[Definition.thing.thingName] == Element["name"] == Element.name.
Hope this helps.
Expanding out the text it becomes a bit more clear:
var str;
if (_.has(Definition.thing, 'thingName')) {
str = Element[Definition.thing.thingName]
} else {
str = null;
}
...
otherThingName: str
It looks like it is defining the member of some object 'otherThingName' to be either whatever Element has set for field Definition.thing.thingName if that exists, or null otherwise.

Setting up variable to return function value or false

I wasn't sure how to properly word the title for this question but jumping right into it,
Using the the ? : operator I setup a JavaScript variable and an if statement like so:
var test = callsAFunction ? test : false;
if I do this, will test equal whatever the function returns here? Or will it be undefined since it's "Technically" not set yet?
What I'm trying to do is set a variable to either what data it gets back and is run through a function, or set it to Boolean false so it will process through my Boolean check as an error. I figured this approach was best but I'm running into issues determining how to go about this. Below are my code snippets:
var hash = self.getHashFromMasterRecords(d[0]);
if(hash === false){
done("Can't find master record hash", self.requestData, self);
}
Obviously it needs to turn false as a Boolean in order to pass as an error. I want to do this without having to call the function more than 1 time for this sequence.
So if I do var hash = self.getHashFromMasterRecords(d[0]) ? hash : flase; would hash return the value? Or undefined?
Thank you ahead of time, if I need to post more info let me know.
The syntax:
var a = (b) ? c : d;
Will set a equal to c if b is evaluates to something truthy, and d if b evaluates to something falsy. If I understand you correctly, you want to set a variable to the return value of a function, and if that function fails, set it to some default value. To do that, use ||:
var a = b() || 'error occurred!';
In the line above, if b() evaluates to something falsy, a will get the value of error occurred!. If b() evaluates to something truthy, it will get the return value of b().
It would be undefined. As long as your function returns a falsey value when it returns you can use the or (||) operator:
var hash = self.getHashFromMasterRecords(d[0]) ?? false;
Although, if that is a concrete example there is little value in the above code as you'd already have a falsey value by just storing the result from the function.

How does the single equal sign work in the if statement in javascript

Recently I saw a statement that works in javascript on the internet and I wonder what the meaning of a single equal sign (=) in javascript as I mostly use in if statements is.
It is a comparison function which include double equal sign (==)
if(i = 1) {
alert(i);
}
This works, I wondered what would happen when the if statement gets assigned to the value of 1 to the variable i and check the value of i which is the same as:
i = 1
if(i) {
alert(i)
}
But I soon realised that the assignation of a value variable needs to have the keyword var
so I changed the code to:
if(var i = 1) {
alert(i);
}
This time the code doesn't work. Why?
The first part of your analysis is of course correct.
Now, the interesting part might be why your last code if (var ...) { doesn't work.
It doesn't work because
1)
var something
is a statement, not an expression.
2) here's how ECMAScript defines the if statement :
IfStatement :
if ( Expression ) Statement else Statement
if ( Expression ) Statement
You must put an expression in the if clause, not a statement.
More on expressions vs statement in this article.
If you check the console, it says Unexpected token var. You're just not supposed to declare variables in the condition of an if statement.
If you ever do actually mean to make an assignment inside the condition, just declare the variable first, like this:
var i;
if(i = 1){
alert(i);
}
I see that you already know the difference between assignment and comparison, though, which is good :)
Single = is indeed an assignation, if you put it in the if condition it will not compare i against 1 but assign the variable i with the value 1 and then use that value as the condition itself, making i a truthy value. So yes, it is the same as you second example.
Also, in javascript it is better to use === instead of == if you are expecting the items to be the same type :
if (1 == '1') {
alert('this is true'); // where you might actually expect it to be false,
in this case it will work properly if you use triple equals (===).
if (1 === '1') {
alert('this is false'); // which is expected
}
Single = is an assignment operator and will always equate to true in an if statement (assuming it is a non negative value).
Double = ,as in ==, is a comparison and will equate to true only if the values on either side of the operator are equal.
Single "=" means "assign to the left var".
As a return value for the IF, you get the value assigned, and since it is 1, the "true" branch is executed.
However, if you put "var" into the IF, it won't return the assigned value, and I think it won't even work at all.
Mistaking "=" and "==" is a common typo.
Your assertion is correct, in that the code is essentially assigning the value 1 to i and then evaluating the expression's truthiness (1 coeerces to true, so the condition passes).
The last example fails because you can't declare variables inside condition expression.
When you don't explicitly invoke the var keyword, the value will be assigned to any existing variable called i that's available in your scope, or, if none exists, create a property i and assign it to the global object (window), which are all callable without invoking the global object (which is why calling, say location will refer back to window.location — unless you've defined var location in scope).

Categories