I'm wondering
1. why the console is throwing out a specific result
2. how to get the console to throw out the result I want based on the code
I've tried both removing the else condition and adding it, but I'm stuck because I don't know what the code is thinking.
isMarried = false;
if (isMarried = false) {
isMarried = 'Nope, not at all! ';
}
console.log(firstName + ' is a ' + age + ' year old ' + job + '. Is he married? ' +isMarried );
//This outputs false for isMarried instead of "Nope, not at all!"
If I add an else like so:
if (isMarried = false) {
isMarried = 'Nope, not at all! ';
} else {
isMarried = 'Oh yeah';
}
//The same code outputs "Oh yeah." I'm a bit confused why it's happening like this. Any thoughts?
Basically, I expected the computer to see isMarried as a false boolean, and if this is the case, I wanted to set the variable to the string seen above. Otherwise, if I changed it to true, for example, the it would be a different string.
You don't use assignment operators (=) inside conditionals. Inside conditionals, you need to use comparison operators (==, !=, >=, <, etc.)
You are assigning a value to your isMarried(false) inside the IF statement .. you need to use compare operators like ==
a == b // this operator will return a `Boolean` value (`true` Or `false`)
a = b // this operator will return the value of `b` (right value)
So :
isMarried = false // this will return the right value (false) which means the IF statement
// won't work and the else code will be auto executed
Try this, Give me green tick if this code satisfied ya..
var isMarried = false;
if(isMarried==false){
isMarried = "Not at all";
}else{
isMarried = "Oh yeah";
}
console.log(isMarried)
Related
I am at the beginning of learning JavaScript and came across different behaviour when declaring a variable with strings and && (the string doesn't show if used first) vs Strings and ||.
Edit:
I was essentially wanting to output the string before the Boolean value in the console.log and now realise that due to && going from left to right which is different for || that I need to add the number to both sides like the code below the "Snippet Edit" comment in code below (OR am I still wrong?)
Example:
const passDriversLicense = true;
const hasGoodVision = false;
//OR: Declaring a variable with strings and ||
let shouldDrive = ('1 ' + passDriversLicense || hasGoodVision);
console.log(`${shouldDrive} that she should drive`) // Output in console is "1 true that she should drive"
//AND: Declaring a variable with strings and &&
shouldDrive = ('2 ' + passDriversLicense && hasGoodVision);
console.log(`${shouldDrive} that she should drive`); // Output in console is "false that she should drive" which doesn't have the string before it, like in the OR version IE I would think it should output "2 false that she should drive"
//Snippet Edit
shouldDrive = ('1 ' + passDriversLicense && '1 ' + hasGoodVision);
console.log(`${shouldDrive} that she should drive`);
Trimming out the unnecessary baggage and substituting in the values directly, your question comes down to this:
const one = '1 ' + true || false;
console.log(one);
const two = '2 ' + true && false;
console.log(two);
Which should make it clearer what's going on.
In the first case, the left side of the || is '1 ' + true. This is a truthy expression, so the whole thing evaluates to that: '1 true'.
In the second case, with &&, not only the left side needs to evaluate to a truthy expression, but the right side does too. But the right side is false, which isn't truthy - and && evaluates to the right-hand side if the left side isn't truthy.
You could remove the + trues to get the same sort of effect:
const one = '1 ' || false;
console.log(one);
const two = '2 ' && false;
console.log(two);
This is called short-circuiting
More generally, the operator (&& and ||) returns the value of the first falsy operand encountered when evaluating from left to right, or the value of the last operand if they are all truthy.
This behavior is useful for patterns such as:
const myNumbers = [];
const highestNumber = Math.max(...myNumbers) || 0; // If Math.max() returns a falsy value, it will replace it with a 0 instead
A similar tool exists for specifically null or undefined values: the ?? operator: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator
You need to learn how logical operators work with Booleans in Javascript.
line#3 passDriversLicense || hasGoodVision = true //because true || false = true
line#5 passDriversLicense && hasGoodVision = false // because true && false = false
Go through these:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND
A group of me and two other people are working to make a Jeopardy game (themed around United States History questions) all in JavaScript. For our final Jeopardy screen, the two teams will each bet a certain amount of money. To prevent a team from typing in random letters for a bet (i.e typing in "hasdfhgasf" instead of an actual amount), we're trying to write an 'onEvent' command that checks to see if a bet is null. If that bet is null, then the code should come up with a message on the screen that tells them to check their bets again.
We tried using statements like, if "null" or if " " but neither of these statements works. We've worked with using getNumber and getText commands, along with just regular variable comparisons with or booleans. So far, we haven't had any luck with these methods.
Here's the group of code we're having issues with:
onEvent("finalJeopardyBetSubmit", "click", function() {
team1Bet = getNumber("team1BetInput");
team2Bet = getNumber("team2BetInput");
console.log(team1Bet);
console.log(team2Bet);
if (getText("team1BetInput") == "" || getText("team2BetInput") == "") {
console.log("Check bet!");
finalJeopardyError();
} else if ((getText("team1BetInput") != 0 || getText("team2BetInput") != 0)) {
console.log("Check bet!");
finalJeopardyError();
} else if ((getNumber("team1BetInput") < 0 || getNumber("team2BetInput") < 0)) {
console.log("Check bet!");
finalJeopardyError();
} else if ((getNumber("team1BetInput") > team1Money || getNumber("team2BetInput") > team2Money)) {
console.log("Check bet!");
finalJeopardyError();
} else {
console.log("Done");
}
});
You can also check out the whole program on Code.org if you'd like to get a better look.
We expect that with the console.log commands, it should say "check bet" if the bets return as null. Instead, the code has ended up fine, and not displaying our error message, even if we type in nothing or just random letters.
a null variable will evaluate to false. Try:
if(variable){
// variable not null
}else{
// variable null
}
Convert the value to a Number first using Number(value) and then check for falsy values using the logical not ! operator. If they enter alphabetic characters, then calling Number('abc') results in NaN.
If a value can be converted to true, the value is so-called truthy. If
a value can be converted to false, the value is so-called falsy.
Examples of expressions that can be converted to false are:
null; NaN; 0; empty string ("" or '' or ``); undefined.
The ! will change any of the falsy values above to true, so you can check for all of them with just the first if statement below.
onEvent("finalJeopardyBetSubmit", "click", function() {
// Convert these values to numbers first
var team1Bet = Number(getNumber("team1BetInput"));
var team2Bet = Number(getNumber("team2BetInput"));
if (!team1Bet || !team2Bet) {
// Handle invalid number error
}
else if (team1Bet < 0 || team2Bet < 0) {
// Handle invalid range error
}
else if (team1Bet > team1Money || team2Bet > team2Money) {
// Handle insufficient funds error
}
else {
// Finish game
}
})
You can read more about the logical operators here.
For some reason, no matter what I bind to the variable theNumber, I still get the console outputting the first console.log() inside of the numberCheck(). I expected this to output the second console.log(), but it refuses. I have tried many different syntactical changes. Maybe I just don't understand the expression !Number.isNaN(). I thought that this meant if the number is a number than its true, but I might be wrong.
Keep in mind, I'm new. I understand terminology so feel free to communicate with whatever words. But my javascript logic is subpar.
let theNumber = 'god'
function numberCheck(x) {
if (!Number.isNaN(x)) {
console.log('You picked a number')
}
else {
console.log('why won't this log');
}
}
numberCheck(theNumber)
numberCheck(12)
The output:
You picked a number
You picked a number
FIXED and Working as Expected:
let theNumber = 'god'
function numberCheck(x) {
if (isNaN(x)) {
console.log('You picked a number')
}
else {
console.log('why wont this log');
}
}
numberCheck(theNumber)
numberCheck(12)
The output:
why wont this log
You picked a number
In JS NaN is a value that differs from a type to another, basically NaN for strings, NaN for ints etc, what that method is doing is checking if the passed value is a NaN of type Number.
You have to cast the argument x to a number
let theNumber = 'god'
function numberCheck(x) {
if (!Number.isNaN(Number(x))) {
console.log('You picked a number');
} else {
console.log('why won\'t this log');
}
}
numberCheck(theNumber);
numberCheck(12);
Using "isNaN" function can be tricky sometimes (see this part of the documentation "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN").
Since it seems you want just verify if a variable is a number or not, you can make it that way:
var theNumber = 100;
function numberCheck(x){
if(typeof x === 'number'){
console.log('Nice you picked a number');
}else{
console.log('It is not a number');
}
}
numberCheck(theNumber);
"typeof" function will return the type of the variable "x".
I have a function to test if a prompt input is a number, like so:
function myFunction()
{
var person = prompt("Please enter your name", "");
if (person != null)
{
if(isNaN(person))
{
document.write("hello " + person + "<br><br>");
}
else
document.write("You gave me a number");
}
else
{
document.write("You didn't answer.<br><br>");
}
}
but every time I enter a number it keeps outputting hello + the number. I've been googling this function for quite some time and it doesn't make sense to me, it seems like it should work. Why is person returning true?
NaN is a special value in Javascript. What isNaN does is check to see if the value passed is equal* to this special value. If you want to check if something is, say, not a stream of numbers, you can use a regular expression:
if (!/^\d+(\.\d+)?/.exec(person)) {
Or parse the value as a number and see if it converts back to the same string:
var n = parseFloat(person);
if (n.toString() !== person) {
*There's a reason that we don't use === but it's outside the scope of this answer.
The isNaN function checks if a value is NaN. NaN is a value that occurs when making operations that require numbers with non-numbers. Please see the documentation.
However the function does not check if the value is of type number. Too check if a value is of type number use the typeof operator
typeof person === 'number'
Your code is the correct way of using the isNaN method. However for anyone else reading this post I have seen a strange anomaly where the documented usage of IsNaN hasn't worked properly and I got around the problem by combining the parseInt method with the IsNaN method. According to the W3c web site (https://www.w3schools.com/jsref/jsref_isnan.asp) the IsNan('123') should return false and IsNan('g12') should return true, but I've seen scenarios where this isn't the case.
If you're having trouble getting the documented methods to work try this code below:
var unitsToAdd = parseInt($('#unitsToAdd').val());
if(isNaN(unitsToAdd)) {
alert('not a number');
$('#unitsToAdd').val('1');
returnVal = false;
}
Alternatively you can try this method which is well tested.
function isNumber(searchValue) {
var found = searchValue.search(/^(\d*\.?\d*)$/);
//Change to ^(\d*\.?\d+)$ if you don't want the number to end with a . such as 2.
//Currently validates .2, 0.2, 2.0 and 2.
if(found > -1) {
return true;
}
else {
return false;
}
}
Hope this helps.
I am trying to make a simple if-else statement, but when I run the code, it always returns true, even if I enter something in the prompt that I know should be false. I have ran it through JsFiddle, and it seems that the code snippet is perfectly valid.
var captchaTest = 5;
var captchaInput = prompt('What is five plus five?');
if ('captchaTest + captchaInput = 10') {
alert('You passed, you may continue'); window.location.href = 'pagepass.html';
}
else {
alert('Failed, try again.'); window.location.href = 'main.html';
}
Can someone tell me what I did wrong?
Non-empty strings in JavaScript are truthy. 'captchaTest + captchaInput = 10', when evaluated as Boolean, is true.
You need to remove the quotation marks and change = to ==:
if (captchaTest + captchaInput == 10)
Apart from the answer that other provided I would also make a point that as per your captcha question, your condition should be like this
if (captchaInput == 10){
alert('You passed, you may continue'); window.location.href = 'pagepass.html';
}
else {
alert('Failed, try again.'); window.location.href = 'main.html';
}
I don't see any use of the variable captchaTest
You shouldn't be using a 'captchaTest + captchaInput = 10' as it is a String and always evaluates to true unless it is an empty one.
Also you should use comparison operator == instead of assignment operator =
So remove the quotes
if ((captchaTest + captchaInput) == 10)