Second Line of Else Block Not Running [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 12 months ago.
Improve this question
In my else block, the second line does not appear to be running. It runs setHelperText but seems to ignore setAlertValue.
const [alertValue, setAlertValue] = useState("error");
const [errValue, setErrorValue] = useState("Error State");
const [helperText, setHelperText] = useState('Input "success" to remove error');
const handleChange = (e) => {
setErrorValue(e.target.value);
if (e.target.value === "success") {
setAlertValue(null);
setHelperText("Update input to re-enable error");
} else
setHelperText('Input "success" to remove error');
setAlertValue("error"); // this line does not run
};
<TextField
label="Error State"
message="this is an ERROR message"
alert={alertValue}
value={errValue}
onChange={handleChange}
helperText={helperText}
/>

Curly braces are missing in your code. It should be like this:
if (e.target.value === "success") {
setAlertValue(null);
setHelperText("Update input to re-enable error");
} else {
setHelperText('Input "success" to remove error');
setAlertValue("error");
};

Related

JavaScript unexpected undefined value [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 29 days ago.
Improve this question
I am running the following JavaScript code:
// Return true if the given username and password are in the database,
// false otherwise.
function validCredentials(enteredUsername, enteredPassword) {
// Database of usernames and passwords
let usernames = ["smith", "tron", "ace", "ladyj", "anon"];
let passwords = ["qwerty", "EndOfLine", "year1942", "ladyj123", "PASSWORD"];
// Search the usernames array for enteredUsername
// Only return true if the enteredUsername is in username, and the
// same location in passwords is enteredPassword
if (usernames.includes(enteredUsername)){
var correctPassword = passwords[usernames.indexOf(enteredUsername)];
if(enteredPassword == correctPassword){
return true;
}
}
else {
return false;
}
}
console.log("Login for ladyj: " + validCredentials("ladyj", "ladyj123")); // true
console.log("Login for ace: " + validCredentials("ace", "wrong")); // false
console.log("Login for jake: " + validCredentials("jake", "???")); // false
I am expecting console.log("Login for ace: " + validCredentials("ace", "wrong")); return false, but it returned undefined. Can anyone tell me what went wrong?
You don't return in all possible branches (namely, if the username exists, but the password is incorrect). Move the return false outside the else to be the final statement in the function.
Alternatively, you could simplify the chain of if and else into one statement:
return usernames.includes(enteredUsername) &&
passwords[usernames.indexOf(enteredUsername)] === enteredPassword;

How to fix Illegal return statement error? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
It gives the Illegal return statement Error in my console, pertaining this part of the code ""return message.reply("Missing Permissions!").then(m => m.delete(5000));""
if(cmd === `${prefix}clear`){
if (message.deletable) {
message.delete();
}
if (!message.member.hasPermission("MANAGE_MESSAGES")) {
return message.reply("Missing Permissions!").then(m => m.delete(5000));
}
if (isNaN(args[0]) || parseInt(args[0]) <= 0) {
return message.reply("This is not a number").then(m => m.delete(5000));
}
let deleteAmount;
if (parseInt(args[0]) > 100) {
deleteAmount = 100;
} else {
deleteAmount = parseInt(args[0]);
}
message.channel.bulkDelete(deleteAmount, true)
.catch(err => message.reply(`Something went wrong... ${err}`));
If this code is not inside of a function, than you can't use return, as there is nothing to return it from: return can only be used inside of a function.

Why are my variables not being correctly defined in my if...else statement? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
In the code below, I've defined a function called checkPassword(), which takes in a single argument, passwordCorrect, which will be either true or false.
I've also defined two variables, accessGranted and message, which currently have no values (they're undefined) and will be overwritten and defined by your if statement if you've written it correctly.
I need to write an if statement inside the function that updates the two variables, accessGranted (a boolean), and message (a string), to meet the requirements below
Requirements:
1) If passwordCorrect is true, accessGranted should have a value of true and message should have a value of 'Welcome to the admin panel!'
2) In any other case, accessGranted should have a value of false and message should have a value of 'Wrong password.'
var accessGranted;
var message;
function checkPassword(passwordCorrect) {
if passwordCorrect == true {
accessGranted = true;
message = "Welcome to the admin panel!";
}
else {
accessGranted = false;
message = "Wrong password."
}
}
console.log('Access Granted:', accessGranted);
console.log('Message:', message);
You need to call the function and fix your syntax error. If statements need parentheses in javascript.
let accessGranted;
let message;
function checkPassword(passwordCorrect) {
if (passwordCorrect) {
accessGranted = true;
message = "Welcome to the admin panel!";
}
else {
accessGranted = false;
message = "Wrong password."
}
}
checkPassword(true)
console.log('Access Granted:', accessGranted);
console.log('Message:', message);

`await` command causes variable to lose scope [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I am using await to pull data from the database. There's a variable secuity_ok that is true on one line, and then false on the next. Can anyone see what the issue is?
Note – if I comment out the line: let session = ..., then it all works.
Controller.prototype.changePassword = async function(request, response) {
let model = request.body;
var secuity_ok = false;
var user = await userService.getUserByEmail(model.email);
if (user && this.isAuthenticatedUser(request, user.id)) {
secuity_ok = true;
} else {
let session = await authenticationService.createSessionByEmailPassword(model.email, model.oldpassword),
secuity_ok = !!session;
console.log( 'A', secuity_ok ); // true
}
console.log( 'B', secuity_ok ); // false
if (!secuity_ok) {
this.sendForbiddenError(response, {
error: 'Cannot change password: Application safeguards are preventing this action'
});
return new Promise(() => {});
}
...
}
Output:
A true
B false
Output should be:
A true
B true
You have a comma at the end of the first line here:
let session = await authenticationService.createSessionByEmailPassword(model.email, model.oldpassword), // <--- Note comma here
secuity_ok = !!session;
That makes secuity_ok part of the let statement, so it's an extra, inner declaration of secuity_ok that only has scope inside the parentheses of the else clause.

Angular JS -> cannot read property [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
Cannot read property 'result' of undefined
Angular Function :
.controller('forgotCtrl', function($scope,$http,$ionicPopup,$state,$ionicHistory) {
$scope.forgot=function(data1){
var link1 = 'http://localhost/uxo_data/forgot.php';
var json10 = {n : data1.mobile };
$http.post(link1, { data1: json10 })
.then(function (res){
$scope.response = res.data1.result;
console.log(res.data1.result);
if($scope.response.created=="1"){
$scope.title="Password Reset!";
$scope.template="Please Check your associated Email Account!";
//no back option
$ionicHistory.nextViewOptions({
disableAnimate: true,
disableBack: true
});
$state.go('login', {}, {location: "replace", reload: true});
}else if($scope.response.exists=="1"){
$scope.title="Failed";
$scope.template="Number you entered doesn't exist";
}else{
$scope.title="Failed";
$scope.template="Contact Our Technical Team";
}
var alertPopup = $ionicPopup.alert({
title: $scope.title,
template: $scope.template
});
});
}
})
Output i get from rest-api is :
{"result":{"created": "0" , "exists": "1" }}
I Checked in Web Debugging tool, php code is working fine and giving above response as output.
change this line from
$scope.response = res.data1.result;
to
$scope.response = res.data.result;
The response will have a data object which you are accessing incorrectly.
console.log(res.data1.result); // => data1 is undefined
try below code:
console.log(res.data.result);

Categories