Javascript. Give value to variable depending on parameter value - javascript

I have been given a Javascript code, and there is a sentence I cannot fully understand:
var isFaculty = (paramArray[0] == "yes"),
isFaculty variable is used afterthat in a equation, where more variables are involved. While the latter are defined along the code, the former is supposed to be defined (i.e. numerical value) by that sentence, as it depends on a parameterArray that the user should introduce (the parameter array is of size 3, anyway). For cell [0], paramArray can have two values, namely "yes" or "no".
I am wondering a possibility, but any help is welcome.
Thanks in advance,
/Jorge.

(paramArray[0] == "yes")
This is like a mini if statement that returns either true or false.
isFaculty is a boolean variable that captures that result.
Once the true or false is caught it can be used as a numeric 1 or 0 that even though is not recommended but could be multiplied by a number to turn it into a 0 if it's false or leave it unchanged if it's true

thanks for your help. The point is that isFaculty variable is involved in a formula as follows:
var xExample = 1/(1+Math.exp(-(-2 + 4*city - 0.11*gender + 0.6*isFaculty + 0.2*city*gender - 0.424885*city*isFaculty - 0.3*citygenderisFaculty)));
consequently, I understand that isFaculty gets value 1 or 0 depending on being true or false?

== is a comparator that will return a boolean value, so the code you have will assign true or false to isFaculty
The var name isXxxx would suggest to me that its value would be boolean.
So what you have is basically:
var isFaculty - for the variable isFaculty
= - assign the value of the following expression
paramArray[0] - take the first value from the array paramArray
== - check if it matches in content but not necessarily type with
"yes" - the string value that you are looking for to assign true
Implicitly this also means that if the content of paramArray[0] does not match with the content of the string value "yes" then the value of isFaculty will be false.
This could be used as a 'flag' later on by using false as 0 and true as 1.

Related

How to use a variable in Math.floor

I want to get the max amount of money a person has with
let targetUser = message.guild.member(message.mentions.users.first()) || message.guild.members.get(args[0]);
var targetForMath = userData[targetUser.id].money;
and I want to use that variable to set the max amount for a Math.floor. I tried
let randomStealCoins = Math.floor(Math.random() * targetForMath) + 1;
but when I use that it gives me NaN. How can I make it so it gives me the actual an actual number not something weird?
If targetForMath is undefined, that will give you NaN:
Since:
Math.random() * undefined -> NaN
I would ensure that targetForMath is a valid number.
I'm not gonna mention that you're mixing var and let, other than to say that you're doing it and should be careful of that.
The first question I'd ask is what the typeof userData[targetUser.id].money is, and more specifically what its value is. If it's a number, boolean, null, or empty array (?!) it should work, or at least not return NaN. However, if it's a string, undefined, or any other value, JavaScript won't really know what you mean when you say, for example, multiply Math.random() times "fish".
Usually in this case it's a good idea to console.log out what userData[targetUser.id] is, just to make sure the object you're getting back from that is actually what you think it is. Is there actually a property on the userData object defined by the targetUser's id?

What does an if (number) return?

I seem to be having a hard time understanding what this does to my code?
const $counters = $('.js-item-counter')
if($counters.length)
{
}
What would this if statement return?
I can tell that the value is 1, but does this make sense?
I am trying to fix some frontend issues, and ran into something like this..
In Javascript, 0 is a falsey value. Anything other than 0 is considered true.
So what your code is doing is, it is making sure that the $counters is present in the DOM because if it were, it would give the length of > 0.
.length property tells you how many elements of the given selector are present in the DOM. If it is 0, then the element isn't present. If it is more than 0, then the element is present and you can act upon it as you wish.
The if statement will return true or false based on the condition.
If $counters.length > 0, it will return true and if block will be executed. Otherwise, it will return false and block won't be executed.
It returns true if the number inside the if statement is greater than or equal to 1 and false if it is 0.
It's a simple test to see if any elements of that class exist. Using length of a jQuery object is the most common jQuery approach to count matches in the collection
If it is anything other than zero it is truthy and zero is falsy
There used to be a size() method but that was deprecated and if you read in it's docs it tells you to use length instead
if the target element is stand for integer that having initial value of 1, then you should do this way
if($counters > 1)
{
//note length is only for checking of element existance
}
length coerced to true for any length other than 0 and false for 0:
console.log(
!!0,
!!1,
!!10
);

Understanding the double exclamation point

I'm trying to understand what exactly the double exclamation mark does. Yes, I saw this question, with lots of answers. So I know in principle what it does, but I don't know why one would ever need to use it.
From what I understand, it converts the value to a boolean. So let's say I have the following code:
var myBool = !!(index === 0 || index > len);
Can't I just leave out the !! and I will get the same result:
var myBool = (index === 0 || index > len);
What do I gain by adding !!? Is't it already a boolean vaule?
The purpose of !! is to canonicalize any type of truthy or falsey value to the corresponding boolean value.
If the value is already known to be a boolean, such as the result of a comparison operator, there's no point in it and it's redundant. So it's useless in the example you gave.

what would happen if you use two equals rather than only one in your execution block after an if conditional in JavaScript?

I am still learning, so I'm sorry if my question is not well formatted.
I was trying to write a function to insert a word to a string in a specified position, however I made a mistake which is writing two equal signs == rather than one in the execution block and this resulted in wrong output when tested.
However, I already know that the execution of code after if/else needs to not be boolean and I noticed this typo and I corrected it by removing one equal sign and the function worked perfectly fine but I was just left wondering why have I never questioned the significance of strictly having one equal sign when executing code after if conditionals.
so here is the wrong code:
function insert(original,to_insert,position){
if (to_insert == "undefined" && position == undefined){return original;}
else if (position == undefined){position == 0}
var x = original.slice(0,position);
var y = original.slice(position);
console.log(x + to_insert + y);
}
insert('We are doing some exercises.','JavaScript ');
//Wrong output >>>> "We are doing some exercises.JavaScript We are doing some exercises."
insert('We are doing some exercises.','JavaScript ', 18);
//correct output>>>> "We are doing some JavaScript exercises."
and here is the correct code:
function insert(original,to_insert,position){
if (to_insert == "undefined" && position == undefined){return original;}
else if (position == undefined){position = 0}
var x = original.slice(0,position);
var y = original.slice(position);
console.log(x + to_insert + y);
}
insert('We are doing some exercises.','JavaScript ');
//correct output >>>> JavaScript We are doing some exercises."
insert('We are doing some exercises.','JavaScript ', 18);
//correct output>>>> "We are doing some JavaScript exercises."
would you please explain what happens inside my wrong code, like what causes the function to not run properly when booleans were used, obviously the function runs once at a time, so what difference would an absolute value of position make compared to a variable value of position.
Thanks in advance
else if (position == undefined){position == 0}
In your wrong code, position remains undefined since you did not do an assignment, you simply checked if position (which is undefined) is equal to 0
So, when you did var x = original.slice(0,position); slice() simply ignored the 2nd argument, which in this case is undefined and sliced from start to end, which is the default behaviour in case the 2nd argument is not used.
From MDN:
The slice() method extracts a section of a string and returns a new string.
str.slice(beginSlice[, endSlice])
endSlice
Optional. The zero-based index at which to end extraction. If omitted, slice() extracts to the end of the string. If negative, it is treated as sourceLength + endSlice where sourceLength is the length of the string (for example, if endSlice is -3 it is treated as sourceLength - 3).
In your case, since you pass undefined (because position == undefined), it's like you omitted it
One equal is to assign values to variables, two equals are for camparing two variables. This is the simplest way to explain it.
= - assigning operator
== - comparing operator
if (position == undefined){position == 0}
This mean if your position is undefined position must be 0. Like it should be 0 but you are not defining it. Two equals is usually use to do comparution actually : does position is equals to 0
However one equal mean you assign the value 0 to position.
I can see two problems in your code.
if (to_insert == "undefined" && position == undefined){return original;}
Here you are checking if to_insert is equal to the string "undefined", but not undefined.
else if (position == undefined){position == 0}
Writing position == 0 will just return a boolean. So in this case, it'll return false (because it execute only if position == undefined returns true).
So it's like if in your code, you had a false between two lines, and you don't change the value of any variable.
else if (position == undefined){position = 0}
By writing only one =, you assign the value 0 to the variable position.
So, when you call the slice() method, the second argument is still undefined, so the method ignore it and just slice the string to the end.
Hope I helped you understand !
You're essentially asking, "What is the difference between using one equals sign (=) and using two equals signs (==)?"
Assume we have the following initialization for both examples:
var pikachu_hp;
One equality sign (=):
pikachu_hp = 50;
This sets the variable, pikachu_hp, to have the Number data type with a value of 50.
Two equality signs (==):
pikachu_hp == 60;
This compares the value (not data type, that's three (===) equals signs in JavaScript) of pikachu_hp against what is on the right hand side; in this case, that's the Number 60. If pikachu_hp has a data value of 60, the expression returns true. If pikachu_hp has a data value of anything else but 60, the expression returns false. Again, I call this an "expression" because it does not equate to anything; it represents either a true or false value.

Check for bool in JavaScript

I've got the following jQuery (I've got it wrapped in the document ready function and all that, so please know I'm just showing you the inside of the function.
..
var itemIsSold = $("#itemIsSold").val();
alert(itemIsSold);
if(!itemIsSold) {
...
}
where itemIsSold is a hidden input field. I get the value False upper case F when it hits the alert but never enters my next if statement. I know this has to be something stupid simple.
If the input's value contains the string "False", that will not translate into a false boolean value. You will need to actually check for itemIsSold == "False".
Since the value of the hidden input field is a string, !"False" will be evaluated to false. Note that any string other than a string with the length of 0 is treated as true. So you should rather compare the string value to another string value like "False":
if (itemIsSold == "False") {
// …
}

Categories

Resources