Alert Based on Else/If In - javascript

very new to coding. I am testing to see if I can make an alert display based on a variable. I have the below code and I am trying to figure out why, in its current state, it is not displaying the "bye" alert. Here is the code:
document.getElementById("square").onclick=square;
function square(){
var test="a";
if (test="v") {
alert("hi");
}
else{
alert("bye");
}
}

You are using = which is an assignment operator.
Problem is in line
if (test="v") {
instead of =, use
if (test== "v") {
OR
if (test==="v") {
The identity (===) operator behaves identically to the equality (==) operator except no type conversion is done, and the types must be the same to be considered equal.

In your if statement, you need to write:
if (test === "v") {
alert("hi");
}
The way you have it right now, if (test="v") sets the variable test to the value v before evaluating the if statement. This is basically the same as doing this:
function square() {
test = "a";
test = "v";
if (test) {
alert("hi");
} else {
alert("bye");
}
}
Here, if(test) just asks if the variable test is not null, undefined, or an empty string ''. Because your variable does have a value "v", if(test) will always be true, so alert('hi') will always be run.

Because you are using = instead of == to compare variable test with value v.
The equal operator is for assignments: you use it to assign a value to a variable.
An assignment expression return the value you're assigning, so, in your case, v.
And since in javascript every non-empty string is coerced as true boolean value, your if branch is executed.
You should have used the == or === operator instead.
The == operator coerced two values to the same type, and return true if they are equal. So, for example,
2 == 1 + 1 => true
but also
"2" == 1 + 1 => true
The === operator is for strict equality. It doesn't coerce values type, and only return true if they are equal both in type and value. So, for example,
2 == 1 + 1 => true
but
"2" == 1 + 1 => false
because you're comparing a string with a number

To check a condition you should use a == b to check if value a is equal to value b
in your code you set the value of test variable to 'v'

Related

Javascript “!” How to interpret the operator?

I cannot interpret this code block. "(! control)" should return true, but the actual value from the foreach function is not running this part, but the "else" part that runs the "false" value below. How is this possible?
let control = false; // False Döndürdük
const filmlist = Storage.getFilmsFromStorage();
filmlist.forEach(function (film) {
if (title === film.title) {
control = true;
}
});
if (!control) // ıs return true? {
const newFilm = new Film(title, director, url);
UI.addFilmToUI(newFilm);
Storage.addFilmToStorage(newFilm);
UI.displayMessages("success", "Film basarili eklendi");
UI.clearInputs(titleElement, directorElement, urlElement);
e.preventDefault();
} else {
UI.displayMessages("danger", "Eklemeye calistiginiz film sistemde mevcuttur");
}
The logical NOT (!) operator (logical complement, negation) takes truth to falsity and vice versa. It is typically used with Boolean (logical) values. When used with non-Boolean values, it returns false if its single operand can be converted to true; otherwise, returns true.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_NOT
let state = true;
console.log(!state)
NOT logical operator
In programming, we use the ! operator followed by a boolean to indicate the contrary.
For example, if we have this code here:
let num = 2;
if(!num){
console.log("This will not reach");
} else {
console.log("This will reach");
}
In this example, the expected output is "This will reach", because the expression will evaluate the number as true (I recommend that you look about falsy values in Javascript and the difference between equality and strict equality operators).
So, you can read it as: If num is not true.
Actually, you could use it to transform boolean values as a switch:
let isOn = true
toogleSwitch(){
isOn = !isOn;
}
This will change the value of the isOn variable to it's respective boolean contrary. If is set primary true, after executing the toggleSwitch, it will be false.

Why does forEach change my Boolean Value?

I am making a movie database with 3 movies. I want to make a function that takes an argument (array) and console.log("You have watched this movie") when "haveSeen: true"
var movies = [
{
title: ...,
haveSeen: true
},
{
title: ...,
haveSeen: true
},
{
title: ...,
haveSeen: false
}
]
function display(arr) {
arr.forEach(function(element) {
if(element.haveSeen = true) {
console.log("You have watched this movie")
}
})
}
When i run "display(movies)" in the console. The console will change all Boolean values of haveSeen to "true". Why? I want the console to only console.log two times because I have only set two movies to "haveSeen: true"
Your problem is that in your function, you have this line:
if(element.haveSeen = true) {
The single = is the assignment operator, used only when assigning values to variables. Change this to === and it'll work:
if(element.haveSeen === true) {
or because it's Boolean, remove the comparison entirely:
if(element.haveSeen) {
You need to understand the difference between the assignment operator = the equivalence operator == and the equals operator ===.
let x = 1;
if (x = 2) will always be truthy as you just assigned 2 to x and 2 is truthy.
The === operator is what you want to use when testing if something is equal to something else.
if (x === 1) is true and (x === 2) is false.
The == equivalence operator is another thing that you might see people use but many coding standards discourage it's use as the result might not always be what you expect. As in (2 == '2') is true as in the integer 2 is equivalent to the string 2 but they are not equal in the (2 === '2') sense.
Seeing that you are testing a boolean value you don't need any operator and can just use
if (element.haveSeen)

If statement with only a number in Javascript

I found this function to put numbers in fractions and I am trying to figure out what everything means. There is one thing I can't figure out.
Here's the code:
function reduce(numerator,denominator) {
var gcd = function gcd (a,b) {
if (b) {
return gcd(b, a%b);
} else {
return a;
}
};
gcd = gcd(numerator,denominator);
return [numerator/gcd, denominator/gcd];
}
What does the if (b) mean. I know that if there is just the variable in the if statement it is checking if the variable is true or false. How would this apply to a number? When would this go to the else statement?
This is to do with how things get converted to Boolean, i.e. whether something is truthy or not
if (0 || NaN || undefined) { // these are "falsy"
// this never happens
} else if (1 /* or any other number*/ ){ // these are "truthy"
// this happens
}
If b is:
0
null
undefined
NaN
Or an empty string ""
it will be evaluated as false. Otherwise, it will be evaluated as true.
In javascript you can check if the variable is assigned by putting it in an if statement. If it has a value it will be true (well unless its value is false or 0). If it has no value or evaluates at null it will return false. Looks like they are verifying it has a value before passing it into the function.
Any expression in if statement will be implicitly converted to boolean before evaluated.
In the code you posted, it's usually used to check if a parameter is passed, in which case undefined is a falsy value and will be converted to false. AJPerez has given an answer on the falsy values (except for he forgot NaN).
function reduce(numerator,denominator){
var gcd = function gcd(a,b){
if (b) {
// if two arguments are passed, do something
return gcd(b, a%b);
}
else {
// only one argument passed, return it directly
return a;
}
};
gcd = gcd(numerator,denominator);
return [numerator/gcd, denominator/gcd];
}
However, this approach may be buggy if the argument you're checking is indeed passed by falsy.

While Loops Syntax Errors

The course is asking me to form a while loop and I keep getting errors or infinite loops. What am I doing wrong?
var understand = true;
while(understand= true){
console.log("I'm learning while loops!");
understand = false;
}
You are using an assignment operator (=) and not an equals test (==).
Use: while(understand == true)
Or simplified: while(understand)
Update from comments:
=== means the value and the data type must be equal while == will attempt to convert them to the same type before comparison.
For example:
"3" == 3 // True (implicitly)
"3" === 3 // False because a string is not a number.
= means assignment, while == is comparison. So:
while(understand == true)
Also note that while and other branch structures, take conditions. Since this is a Boolean you can just use itself:
while(understand)
Also a note of the difference between == and === (strict comparison). The comparison == will attempt convert the two sides to the same data type before it compares the values. While strict comparison === does not, making it faster in most cases. So for example:
1 == "1" // This is true
1 === "1" // This is false

Javascript,doesn't show undefined number

I've created a variable with keys and values which looks like:
var e = new Array();
e[0] = "Bitte";
e[1] = "Danke";
Besides this I added a line in the variable which shows a text when the number is undefined.
e[NaN] = "Change Settings";
So when the variable e is NaN ("undefined"), I want that he doesn't displays the Number of the variable e in the input. I tried to achieve this as you can see, but it won't function.
if (neuezahl = NaN) {
document.getElementById("saveServer").value="";
} else {
document.getElementById("saveServer").value=""+neuezahl+"";
}
You have assigned neuzahl not compared it, aside that use the isNAN function:
if (isNAN(neuezahl))
{
document.getElementById("saveServer").value="";
}
else
{
document.getElementById("saveServer").value=""+neuezahl+"";
}
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/isNaN
NaN can't be compared directly (it's not even equal to itself NaN === NaN ==> false). Use isNaN() to detect NaN:
if (isNaN(neuezahl)) {...}
the condition in the if statement may not correct. Now you use "=" not "==", it is an assignment statement and the condition will always true. So if you want to check "neuezahl" is "NaN", function isNaN may help.
if (isNaN(neuezahl)){...}
else {}

Categories