Is there a better way to 'do nothing' in javascript if statement? - javascript

My url looks like this = https://studentscafe.com/menu/2
I'm trying to check whether or not it has 2 different url params...
1.) ?dinner=1
or
2.) &dinner=1
If #1 is present, do nothing
If #2 is present, do nothing
But if neither are present, default to adding ?dinner=1 to the url.
Is there a better way to have a default do nothing in an if statement? Fiddle here for example.
var path = 'https://studentscafe.com/menu/2';
if (path.indexOf('?dinner=1') >= 1) {
console.log('has ?');
// do nothing leave url as it is
} else {
console.log('does not have ?');
if (path.indexOf('&dinner=1') >= 1) {
// do nothing leave url as it is
} else {
path = path + '?dinner=1';
}
}
Expected output: if the url doesn't have #1 or #2: https://studentscafe.com/menu/2?dinner=1

Instead of
if (something) {
// do nothing
} else {
// do what you need
}
You can use
if (!something) {
// do what you need
}
In your case:
if (path.indexOf('?dinner=1') == -1 && path.indexOf('&dinner=1') == -1) {
path = path + '?dinner=1';
}

Using a regular expression and the ! negation operator, this can be rather simple:
var path = 'https://studentscafe.com/menu/2';
if (!/[?&]dinner=1/.test(path)) {
path += '?dinner=1';
}
console.log(path);

You can do this way.
var path = 'https://studentscafe.com/menu/2';
// Since there is no change to path if it contains either ?dinner=1 or &dinner=1
if (path.indexOf('dinner=1') >= 1) {
console.log('has dinner');
// do nothing leave url as it is
} else {
path = path + '?dinner=1';
}

In modern JS you may simply do like
['?dinner=1','?dinner=2'].every(s => !path.includes(s)) && (path += '?dinner=1');

Related

How can I make it so that at any point during my function the user can type "reset" and it will take them back to the beginning of my function?

let level = 0;
let usersName;
let path;
const getBotReply = (msg) => {
if (level === 0) {
level = 1;
usersName = msg;
return "Chur " + usersName + ". Do you live in Raglan?";
}
if (level === 1) {
level = 2;
if (msg === "yes") {
path = "left-yes";
return "Do you know how to surf?";
}
if (msg === "no") {
path = "right-no";
return "Are you from Auckland?";
}
}
Basically I want it so that instead of typing yes or no. The user will type reset and it will return to "level 0"
I've tried:
if (msg === "reset") {
level = 0;
}
If you put your if-check for reset at the top then you have done it correctly, and you simply forgot a return in the solution you suggested?
If you don't include a return stament in the if-check the function will just continue, so it will run the next if check, which matches the level being 0 and it will assume that "reset" is the name of the user.
So if you include
if(msg === "reset"{
level = 0
return
}
It should work just fine, you can leave the return blank or include a message. I included a JS fiddle which is literally your code with the fixed if check: https://jsfiddle.net/5tu7c20n/
in this case, I believe it would be preferable to include a while loop.
while(msg === "reset"){level = 0};

true == false evaluates to true somehow?

I've been working to scrape some webpage that is using the OWASP CRSFGuard project for protection. The library seems to be causing one of my requests to get a 401 so I started digging through their code and noticed the following;
function isValidDomain(current, target) {
var result = false;
/** check exact or subdomain match **/
if(current == target || current == 'localhost') {
result = true;
} else if(true == false) {
if(target.charAt(0) == '.') {
result = current.endsWith(target);
} else {
result = current.endsWith('.' + target);
}
}
return result;
}
From what I can tell, there must be instances where this code is executed; result = current.endsWith('.' + target);. Given true == false is inherently false, how would the code reach that statement? Is this some JS oddity (I know we're not using the strict === equality, but seriously...)?
Answer: It will never reach that code block.
function isValidDomain(current, target) {
var result = false;
/** check exact or subdomain match **/
if (current == target || current == 'localhost') {
result = true;
} else if (true == false) {
if (target.charAt(0) == '.') {
result = current.endsWith(target);
} else {
result = current.endsWith('.' + target);
}
}
return result;
}
var trueFalse = document.getElementById('trueFalse');
trueFalse.innerHTML = isValidDomain('true', 'false') ? 'WTF!' : 'All is good in the JS World';
trueFalse.addEventListener('click', function(e) {
trueFalse.innerHTML = (true == false) ? 'WTF!' : 'All is good in the JS World Still';
});
<div id="trueFalse"></div>
I would say that Blazemonger is most likely correct.
That else if probably had some other condition at some point, and for whatever reason, they decided they didn't want that block of code to execute anymore, so they changed the condition to something that is always false.
It's also not entirely uncommon to see programmers use 1 === 0 as an indication for false. Why they would want to do this is anybody's guess.

What location.hash.match return if there is no hash?

please can you tell me what does location.hash.match return if there is no hash ?
My code :
function getHashValue(key) {
return location.hash.match(new RegExp(key + '=([^&]*)'))[1];
}
test = getHashValue('test');
if (test == 'abc') {
//code WORKS
}
else if (test == 'sal') {
//code WORKS
}
else if (test == "") {
//code DOESNT WORKS
}
but It doesn't works
I forget to mentionned that my code 'getHashValue' return the value of the hash Exemple : #test=abc
sorry I forget to mentionned it
Why not just?
test = getHashValue('test');
if (test === undefined) {
//code
}
EDIT
The error was from a null return in the match() call. The following change will return an empty string if the match is "" or null.
function getHashValue(key) {
var match = location.hash .match(new RegExp(key + '=([^&]*)'));
return match ? match[1] : "";
}
If you run location.hash in your browser console on any website where you're not using a hash, you'll find that it returns the empty string "".
As such, a regex match on that will find 0 results, returning null, at which point, you try to access null[1]...
location.hash will be empty string and your function:
function getHashValue(key) {
return location.hash.match(new RegExp(key + '=([^&]*)'))[1];
}
Will indeed return undefined. The problem is that you are checking "undefined" value incorrectly. Change your code to:
test = getHashValue('test');
if (typeof(test) === 'undefined') {
//code
}

JavaScript ternary operator into full if/else statement issue

I have following ternary statement:
$.history.init(function(url) {
load(url == "" ? "#some-page" : url);
});
Which I have rewrote into:
$.history.init(function(url) {
load(
if( url == ""){ url = "#some-page"
} else { url = url }
);
});
I now the is an error on line 3 if(url == ""), but I don't understand what error.
Any suggestion much appreciated.
In JavaScript, an if is not an expression. It does not return a value and cannot be put inside a function call. That is, this is not valid:
func(if (a) { ... } else { ... });
This is the main difference between if and ?:--the operator is an expression and returns a value; if is a statement, does not return a value and cannot be used everywhere.
Your best bet if you have to avoid the ternary operator is to do something like:
if (url == "") {
url = "#some-page";
}
load(url);
You can also achieve the same effect using ||:
function (url) {
load(url || "#some-page");
}
This is the shortest and most idiomatic way to write your code.
if expressions dont return anything in JS. So that basically does load(undefined).
Try this instead:
if (url === '') {
url = '#some-page';
}
load(url);
Note you don't need to else at all, because if the value is present you have nothing to change.
rewrite it as
$.history.init(function(url) {
if( url == ""){
url = "#some-page";
}
load( url );
});
Your rewritten code is invalid. Try this:
$.history.init(function(url) {
if(url == "") {
load("#some-page");
} else {
load(url);
}
});
You need the if statement to be outside of the load function, i.e.
$.history.init(function(url) {
if (url === "") {
url = "#some-page";
}
load(url);
});
Note that you don't need the else clause as url = url is a redundant operation.

Javascript for conditional URL append or redirect based on window.location.href

I am trying to make a bookmarklet that when clicked will check the URL of the current tab/window to see if it contains 'char1' and/or 'char2' (a given character). If both chars are present it redirects to another URL, for the other two it will append the current URL respectively.
I believe there must be a more elegant way of stating this than the following (which has so far worked perfectly for me) but I don't have great knowledge of Javascript. My (unwieldy & repetitive) working code (apologies):
if (window.location.href.indexOf('char1') != -1 &&
window.location.href.indexOf('char2') != -1)
{
window.location="https://website.com/";
}
else if (window.location.href.indexOf('char1') != -1)
{
window.location.assign(window.location.href += 'append1');
}
else if (window.location.href.indexOf('char2') != -1)
{
window.location.assign(window.location.href += 'append2');
}
Does exactly what I need it to but, well... not very graceful to say the least.
Is there a simpler way to do this, perhaps with vars or a pseudo-object? Or better code?
A (sort-of) refactoring of dthorpe's suggestion:
var hasC1 = window.location.href.indexOf('char1')!=-1
var hasC2 = window.location.href.indexOf('char2')!=-1
var newLoc = hasC1
? hasC2 ? "https://website.com/" : window.location.href+'append1'
: hasC2 ? window.location.href+'append1' : '';
if (newLoc)
window.location = newLoc;
Calling assign is the same as assigning a value to window.location, you were doing both with the addition assignment += operator in the method anyway:
window.location.assign(window.location.href+='append2')
This would actually assign "append2" to the end of window.location.href before calling the assign method, making it redundant.
You could also reduce DOM lookups by setting window.location to a var.
The only reduction I can see is to pull out the redundant indexof calls into vars and then test the vars. It's not going to make any appreciable difference in performance though.
var hasChar1 = window.location.href.indexOf('char1') != -1;
var hasChar2 = window.location.href.indexOf('char2') != -1;
if (hasChar1)
{
if (hasChar2)
{
window.location="https://website.com/";
}
else
{
window.location.assign(window.location.href+='append1');
}
}
else if (hasChar2)
{
window.location.assign(window.location.href+='append2');
}
Kind of extendable code. Am i crazy?
var loc = window.location.href;
var arr = [{
url: "https://website.com/",
chars: ["char1", "char2"]
}, {
url: loc + "append1",
chars: ["char1"]
}, {
url: loc + "append2",
chars: ["char2"]
}];
function containsChars(str, chars)
{
var contains = true;
for(index in chars) {
if(str.indexOf(chars[index]) == -1) {
contains = false;
break;
}
}
return contains;
}
for(index in arr) {
var item = arr[index];
if(containsChars(loc, item.chars)) {
window.location.href = item.url;
break;
}
}
var location =window.location.href
if (location.indexOf('char1')!=-1 && location.indexOf('char2')!=-1)
{window.location="https://website.com/";}
else if (location.href.indexOf('char1')!=-1) {window.location.assign(location+='append1');}
else if (location.indexOf('char2')!=-1) {window.location.assign(location+='append2');}

Categories

Resources