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)
Related
[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?
I'm practicing functions and stumped. The code only produces the if block regardless of prompt. Is this a type conversion thing. What am I missing?
function init() {
function dogAllowed(breed) {
var breed = prompt("what type of dog");
if (breed = "pitbull") {
console.log("dogNotAllowed");
} else {
console.log("dog Allowed");
}
}
dogAllowed();
}
window.onload = init();
In your if statement, you need comparison equals (==) not assignment equals (=). So: if (breed == "pitbull") should work.
The comparison operator in JavaScript is ==, or === for strict equality. = is an assignment operator ("put the value on the right inside the variable on the left), and it happens returns the value that was assigned. Here, that value is "pitbull", so your if (breed = "pitbull") is equivalent to breed = "pitbull" followed by if ("pitbull"). JavaScript evaluates non-empty string as true, so you always enter the first branch of that if.
if (breed === "pitbull") should work, and so should if (breed == "pitbull"). Read more about the difference between the two at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators
Since you are not doing a closure, I would recommend separating the functions and also using a ternary operator. I also think you should properly indent your code because it well help people understand it better.
As the other answers mentioned you are using an assignment operator = when you should be using an equality operator. I recommend to never use == because it does type conversion which can lead to more problems later on. Personally I always use === and do the data type conversion myself rather than leaving it up to javascript because its much less prone to bugs.
You can separate your functions like this:
function init() {
dogAllowed();
}
function dogAllowed (breed) {
var breed = prompt("What breed of dog?");
console.log(breed === "pitbull" ? "Dog not allowed" : "Dog allowed" )
}
window.onload = init();
In Javascript how this pattern operates and by what name would you refer to it?
var valid = (value === value2 (car.color));
And how is different from:
var valid2 = if(value === value2){ car.color }
Those aren't even close to the same. In the first example, you have a function, value2(), which accepts a variable car.color as a parameter, returns something, which is then compared to value. It's not exactly clear that value2 is a function by the declaration or naming used in the code here, however, and the spacing doesn't help clarify it's purpose.
Your second example won't parse correctly, because you can't assign a variable to an If statement. If it were possible, it still wouldn't make sense, because if value == value2, you enter a code block where the only statement is not valid.
It appears that value2 is a function, so if value2 returns something that is equal to value then valid is true, otherwise false. Your second statement, var valid2 = if(value === value2){ car.color },
however, is invalid 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).
Consider the code at the bottom, inside a regular function, that checks if some argument was provided or not, and assigns a default value to a variable named message. If the argument is truthy or an empty string, It is simply converted to a string and is stored in the message variable, otherwise the type of argument will be stored in message.
I know it's possible to shorten if else statements to assign default values to variables, like:
var message = arguments[0] || jQuery.type(arguments[0]);
which if only the arguments[0] is truthy will be stored in message. But how to make an exception for an empty string which is a falsy value, without having to use a long if else statement?
if(arguments[0] || arguments[0] === '')
var message = arguments[0].toString();
else
var message = jQuery.type(arguments[0]);
var message = ((arguments[0] || arguments[0] === '') ? arguments[0].toString() : jQuery.type(arguments[0]));
It sounds like you're looking for a shorthand if/else. If so, you can find the answer to your question here. Basically what you need is a ternary operator.
Excerpt below:
var x = y !== undefined ? y : 1;