Javascript variable comparison - javascript

I have javascript with global variable declared:
var IsUserAllowed = false;
And I have a function:
function setSelectedIdsInput(inputLogicalId) {
if (IsUserAllowed) {
This does not work, I assume the value of IsUserAllowed is in string.
So i did:
var isUserAllowedStr = IsUserAllowed.toString().toLowerCase();
if (isUserAllowedStr == "true") {
This works, Since im new to java script i wanted to know if its ok to compare strings like this.
This due to fact that doing:
if (isUserAllowedStr.localeCompare("true")) {
Did not work either !
Thanks!
Update - i suspect the global var was string and not Boolean. this why the if failed. when i did alert(IsUserAllowed) the output was "False"

var IsUserAllowed = false;
then
function setSelectedIdsInput(inputLogicalId) {
if (IsUserAllowed) {
// something true
} else {
// something false
}
or
if(IsUserAllowed === true)
but it is useless.

Try:
if (isUserAllowed === true) {
}

isUserAllowed is a boolean (true / false):
You can check it by simply doing
if (isUserAllowed) { }
Or
if (isUserAllowed === true) { }

Your example should work as expected.
You can play around in this JSFiddle to test for yourself: http://jsfiddle.net/bT8hV/
var IsUserAllowed = false;
function setSelectedIdsInput() {
if (IsUserAllowed) {
alert('TRUE');
}
else {
alert('FALSE');
}
};
setSelectedIdsInput();

Related

Trying to solve If/else problem with specific string and boolean

Problem
I've tried multiple avenues and watched videos. I'm stuck...
function exerciseThree(typeOfPizza){
let lovesPizza;
// In this exercise, you will be given a variable, it will be called: typeOfPizza
// You are also given another variable called: lovesPizza;
// Using an if/else statement assign lovesPizza to true if typeOfPizza is 'pepperoni', assign it to false if it is 'olives'
What I've tried:
if (lovesPizza==='pepperoni') {
// The value is empty.
return true;
}
else {
(lovesPizza==='olives')
return false;
}
Another attempt
// if(lovesPizza===pepperoni){
// return true
//}
//else (lovesPizza===olives){
// return false
// }
Another one
//if (lovesPizza.equals(pepperoni))
// return "true";
//else (lovesPizza.equals(olives))
// return "false"
As the comments say, you're looking for if / else. You should also double check your reading of the question, you had your checking / assigning variables the wrong way around
function exerciseThree(typeOfPizza){
let lovesPizza;
if (typeOfPizza === 'pepperoni') {
lovesPizza = true;
} else if (typeOfPizza === 'olives') {
lovesPizza = false;
}
console.log('lovesPizza:', lovesPizza);
};
exerciseThree('pepperoni');
exerciseThree('olives');
I would highly recommend using a switch statement in this case here. Switch statements run faster and are easier to work with in my opinion.
But to point out what you're doing wrong:
Here you are checking if lovesPizza has the value of pepperoni. But you should be checking typeOfPizza. This is why you're most likely getting undefined:
if (lovesPizza==='pepperoni') {
// The value is empty.
return true;
}
else {
(lovesPizza==='olives')
return false;
}
Check out how this looks with a switch statement.
function exerciseThree(typeOfPizza) {
switch (typeOfPizza) {
case 'pepperoni':
return true;
case 'olives':
return false;
default:
return false;
}
}
exerciseThree('pepperoni');
exerciseThree('olives');
Your else statement needs an if
if(somethingisTrue)
{
return "it is true";
}
else if(somethingelseistrue)
{
return "no the other thing was true";
}
else
{
return "nothing is true"
}
Also === checks the strings equal and are both strings. It is often better to make sure the if is case insensative
if(!typeOfPizza)
{
//raise an error as null was passed in
return "false"
}
else if(typeOfPizza.toLowerCase().trim()==="pepperoni"){
{
return true..... you can build the rest
I often write a function (prototype) called cleanString or compareString to perform all the normal cleaning up of strings.
A simple solution is but doesn't use ifs as asked.
function exerciseThree(typeOfPizza){
let lovesPizza= typeOfPizza==="pepperoni";
return lovesPizza;
}
I certainly hope you teacher is playing a trick on you.
There is no sane suggestions what to do if you send for instance 'ham' into it, and not handle all possibilities are just sloppy.
let lovesPizza;
function exerciseThree(typeOfPizza){
if(typeOfPizza === 'pepperoni') {
return true;
} else if (typeOfPizza === 'olives') {
return false;
} else {
return undefined;
}
}
lovesPizza = exerciseThree('pepperoni');
console.log(lovesPizza); // true
lovesPizza = exerciseThree('olives');
console.log(lovesPizza); // false
lovesPizza = exerciseThree('ham');
console.log(lovesPizza); // undefined

javascript if state function doesn't read boolean

My code work with resize function boolean change with width,
but my function contain if statement doesn't read the boolean,
what is problem with my code?
I used = ==, but I don't know how to use them exactly
var footerMenu = ['#about', '#help']
var slideSwitch = false
function slideDown(){
footerMenu.forEach(function(list){
$(list+' p').click(function(){
$(list+' ul').slideToggle(300)
})
})
}
function slideClear(){
for( let i = 0; i < footerMenu.length; i++){
$(footerMenu[i]+' p').click(function(){
var choice = footerMenu[i]
footerMenu.splice(i, 1);
footerMenu.forEach(function(list){
$(list+' ul').slideUp(300)
})
footerMenu.splice(i, 0, choice);
})
}
}
function slideTotal(){
if(slideSwitch = true){
slideDown()
slideClear()
}
}
$(document).ready(function() {
checkWidth();
});
$(window).resize(function(){
checkWidth();
});
function checkWidth(){
$vWidth = $(window).width();
if($vWidth <576){
console.log("Width: Less than 576");
slideSwitch = true
}else{
console.log("Width: More than 576");
slideSwitch = false
}
}
slideTotal()
I hope correct my code, if I don't have any wrong please advice me how to solve it
= is the assignment operator. It changes the value of what is on the left hand side. It is usually not what you want in an if statement unless you really know what you are doing.
== and === are the comparison operators. The different between them is that == automatically converts the two arguments to the same type, whereas === does not. But that doesn't really matter, my advice is to always use === to compare variables in an if statement.
Also, comparing to true (x === true) is completely pointless because that is what an if statement already does; it is unnecessary.
(side note: you could do if (x === true === true === true), and that would be the same as if (x).)
The code you want is:
function slideTotal() {
if (slideSwitch) {
slideDown();
slideClear();
}
}
Well, to start:
function slideTotal(){
if(slideSwitch = true){
slideDown()
slideClear()
}
}
change: slideSwitch = true
to: slideSwitch == true

How to avoid "null" with match()

I am using a method to find Media Queries in code.
function checkMediaQueries() {
var css = cssText;
var patt1 = /#media/gi;
countMQ = css.match(patt1).length;
if (countMQ == 0) {
return false;
} else {
return true;
}
}
It all works fine when it finds some Media Queries. But when the method cant find any, it wont return anything because countMQ is null. I know the problem, but cant find a solution for it.
How can i avoid this result and make my method return false instead?
Thx for help
Remove the .length, as null has no length
var countMQ = css.match(patt1);
and check for truthy, not 0
if (countMQ) {
return true;
} else {
return false;
}
or even null, if you wan't to be more specific
if (countMQ === null) {
or simpler
function checkMediaQueries() {
return cssText.match(/#media/gi) ? true : false;
}
FIDDLE

How to use the return true/false in js

I have a function, for example check navigator params, like that :
function paramsDevice() {
if ( navigator.userAgent. etc ... ) {
return true;
} else {
return false;
}
}
how to use the return, in a other part of js code ?
if (paramsDevice == false)
not working and i have no error
In your code you are comparing undefined variable paramsDevice with the boolean false.To compare returned by paramsDevice() value try the following :
if (paramsDevice() == false)
You can also assign a variable to the result to use it in the if statement :
var paramsDevice = paramsDevice()
if (paramsDevice == false)
use === to compare with false .You can assign your function a variable.Then you can check the variable if (paramsDevice == false)
var paramsDevice = function() {
if (1 === true) {
return true;
} else {
return false;
}
};
if (paramsDevice === false) {
alert('working....');
}
WORKING Demo

Return from inner function in JavaScript?

I have a jQuery-powered JavaScript function which iterates over a list of fields and checks to see whether they are empty; if so, blocks the submission of the form.
required_fields.forEach(function(field) {
if (field.val() == '')
{
field.addClass('field-highlight');
return false;
}
else
{
field.removeClass('field-highlight');
}
});
// I want to return to here from the return false point
How can I structure this differently to do what I want?
Just use a variable to keep track of the validation:
var is_valid = true;
required_fields.forEach(function(field) {
if (field.val() == '') {
field.addClass('field-highlight');
is_valid = false;
return false;
} else {
field.removeClass('field-highlight');
}
});
return is_valid;
Or, you can just use the field-highlight class as well:
required_fields.forEach(function(field) {
if (field.val() == '') {
field.addClass('field-highlight');
return false;
} else {
field.removeClass('field-highlight');
}
});
return $('.field-highlight').length == 0;
use a boolean in the forEach closure, which would be set to true, if the field value is empty. Check that value before submission of form
It sounds like you want to do the following
Update the elements with the field-highlight class based on whether or not they have a value
Block the form submission if any are empty
If so then try the following
var anyEmpty = false;
required_fields.forEach(function() {
if ($(this).value() == '') {
$(this).addClass('field-highlight');
anyEmpty = true;
} else {
$(this).removeClass('field-highlight');
}
});
if (anyEmpty) {
// Block the form
}
Did you write the "forEach" function? If so, that could check the return value of the anon function, and if it is ever false, stop iterating.
If your required_fields is a jQuery object, you could just do this:
var stop = required_fields.removeClass('field-highlight')
.filter("[value == '']").addClass('field-highlight')
.length;
return !!stop
Or perhaps more efficient like this?
var stop = required_fields.filter('.field-highlight').removeClass('field-highlight')
.end().filter("[value == '']").addClass('field-highlight')
.length;
return !!stop

Categories

Resources