JS file won't let me have more than two variables - javascript

I am a newbie at JS, and am trying to make my own Chrome extension with some source-free code I found on the internet. I am still learning and playing around, so some stuff is new or unknown to me, and therefore I ran into this little error. Tried to create an extension, which changes font on two Twitter accounts but when I try to add more than two Twitter accounts, Chrome states there was an error in one of the lines.
I have this code, which works perfectly:
if (link && (link.href === "https://twitter.com/Handle1" ||
link.href === "https://twitter.com/Handle2")) {
If I add one, two or more handles in this part, Chrome doesn't return any errors, which I know why and it's great. It also doesn't return it in this part, if I have only two handles, like shown here:
if (tweet.dataset.clickToOpenTarget.indexOf("https://twitter.com/Handle1/") === 0 ||
tweet.dataset.clickToOpenTarget.indexOf("https://twitter.com/Handle2/") === 0) {
But it returns an error, when I try to add another handle, like here:
if (tweet.dataset.clickToOpenTarget.indexOf("https://twitter.com/Handle1/") === 0 ||
tweet.dataset.clickToOpenTarget.indexOf("https://twitter.com/Handle2/") === 0) ||
tweet.dataset.clickToOpenTarget.indexOf("https://twitter.com/Handle3/") === 0) {
Chrome says it's because of an "Unexpected token ||" but I don't know why. If it accepts two handles, and the operator is "OR", why it doesn't accept three or more handles?

syntax error, one more ) before ||.
if (
tweet.dataset.clickToOpenTarget.indexOf("https://twitter.com/Handle1/") ===
0 ||
tweet.dataset.clickToOpenTarget.indexOf("https://twitter.com/Handle2/") ===
0 ||
tweet.dataset.clickToOpenTarget.indexOf("https://twitter.com/Handle3/") === 0
) {
}
Actually, your code can be simplified to below which might help you find where the bug is.
var clickToOpenTarget = tweet.dataset.clickToOpenTarget;
var hrefs = [
"https://twitter.com/Handle1/",
"https://twitter.com/Handle2/",
"https://twitter.com/Handle3/",
];
var hasClickToOpenTarget = hrefs.some(function (href) {
return clickToOpenTarget.indexOf(href) === 0;
});
if (clickToOpenTarget) {
console.log("hello");
}
Also, eslint or prettier is recommended to help you find these errors.

If you reformat the problematic segment, it looks like this:
if (tweet.dataset.clickToOpenTarget.indexOf("https://twitter.com/Handle1/") === 0 ||
tweet.dataset.clickToOpenTarget.indexOf("https://twitter.com/Handle2/") === 0) ||
tweet.dataset.clickToOpenTarget.indexOf("https://twitter.com/Handle3/") === 0) {
However, in the second line, you can see that there's an extra ), which tells the JavaScript interpreter that the if statement has ended, so it throws an error when it sees an unexpected || immediately after the if statement.
I assume it was just a simple syntax mistake when you tried to add another clause to your if-statement. Removing this extra ) fixes the problem:
if (tweet.dataset.clickToOpenTarget.indexOf("https://twitter.com/Handle1/") === 0 ||
tweet.dataset.clickToOpenTarget.indexOf("https://twitter.com/Handle2/") === 0 ||
tweet.dataset.clickToOpenTarget.indexOf("https://twitter.com/Handle3/") === 0) {

Related

Angular 7.2.5 + Typescript 3.2.4: Cannot read property 'aaa' of undefined

I have the following lines of code:
if ((this.axes.x && this.axes.x.property === 'run_number') ||
(this.axes.y && this.axes.y.property === 'run_number')) {
this.buildLineGraph(this.axes.y.property === 'run_number');
} else {
this.buildScatterGraph();
}
most of the time runs without problems but from time to time fails if any of the element in the chains:
this.axes.x.property
this.axes.y.property
giving the error:
Cannot read property 'aaa' of undefined
with aaa being the undefined element: axes, x, y, etc.
How do I check for every possible undefined element? Do I need a long chain of nested if statement?
I am answering my own question but feel free to post a better and more elegant solution as a separate answer so I can vote for it.
if (this && this.axes && this.axes.x && this.axes.y && this.axes.x.property && this.axes.y.property) {
if ((this.axes.x && this.axes.x.property === 'run_number') ||
(this.axes.y && this.axes.y.property === 'run_number')) {
this.buildLineGraph(this.axes.y.property === 'run_number');
} else {
this.buildScatterGraph();
}
}

JavaScript with coffescript syntax- if condition : optimize if statement structure

I have a function and I'm testing 4 variables, I want to optimize the structure of my if statement test, can some one help ? :
$scope.filterActivated = ->
if $scope.postParams.options.scopes.report.from || $scope.postParams.options.scopes.report.to || $scope.postParams.options.template_id || $scope.displayOptions.query.length > 0
return true
else
return false
you can remove true/false and optimize it a little bit like this:
$scope.filterActivated = ->
options = $scope.postParams.options
options.scopes.report.from or options.scopes.report.to or options.template_id or $scope.displayOptions.query.length > 0
Edit: JS for you:
$scope.filterActivated = () => {
let options = $scope.postParams.options;
return options.scopes.report.from || options.scopes.report.to || options.template_id || $scope.displayOptions.query.length > 0;
};
Not sure what you mean by optimizing, but a shorthand of that could be:
$scope.filterActivated = ->
$scope.postParams.options.scopes.report.from
|| $scope.postParams.options.scopes.report.to
|| $scope.postParams.options.template_id
|| $scope.displayOptions.query.length;
Edit:
Initially, I used the ternary syntax, but that's not supported by CoffeeScript. For reference Ternary operation in CoffeeScript
Edit 2:
Reduced it a bit more, #user633183 suggested using Boolean but I think this gives the same result.

Refactoring JavaScript function results

I'm working on a project using Leaflet's Mapping API. Right now, I'm cleaning up my code and there's one section I feel could be made better.
I have it set when the location is found, the location is checked both in accuracy and in bounds:
function checkLocation(position)
{
if(position.accuracy > 100)
{
return 4;
}
else if((position.latlng.lat <= **bound** || position.latlng.lat >= **bound**) || (position.latlng.lng >= **bound** || position.latlng.lng <= **bound**))
{
return 5;
}
return 0;
}
Basically, if the accuracy is too low, I throw an error with error code 4. If the coordinates are outside of where I want them to be, I throw an error with error code 5 (These are to correspond to Leaflet's builtin error codes 1-3 so I can switch on them later). I return 0 just to say there wasn't an error.
This function is called by the locationFound event, which has the following code:
var temp = checkLocation(position);
if(temp != 0)
{
// Handle error code
return;
}
This also works, but I'm not fond of how this looks. What I want is for this bit to only take like two to three lines, preferably without an if statement. I originally had the code for checkLocation in this section, but I thought having it on its own would make for cleaner and more reader-friendly code.
My question is is there any way to improve this bit? I looked into lambda expressions but didn't think it fit and I tried using a Promise, but at that point, I was losing lines trying to cut down on lines. I don't want to code golf the code, but I'm still pretty new to JavaScript and I don't know if there's any way to simplify this while still looking professional. I'm also up for changing the checkLocation function if it means improving the code.
If you refactor to this:
function invalidAccuracy(position) {
return position.accuracy > 100;
}
function outOfBounds(position) {
return (position.latlng.lat <= **bound** || position.latlng.lat >= **bound**) || (position.latlng.lng >= **bound** || position.latlng.lng <= **bound**);
}
You can handle it like this:
function checkLocation(position) {
if(invalidAccuracy(position))
return 4;
if(outOfBounds(position))
return 5;
return 0;
}
You can (if you want) put it in 1 line then:
return invalidAccuracy(position) ? 4:
outOfBounds(position) ? 5 :
0;

JS OR statement just not working

I know this question has been asked a million times but I've gone through just about every method suggested in other threads and cannot seem to figure out why the OR statement in my IF is not working. And would like some explanation as to how to use the OR function if I am doing this completely wrong.
I have the following code
if((a != 'error') || (a != 'stay')) {
//Do something here
}
And regardless if the a is error or stay the code is being executed anyway
I have also tried
if((!a == 'error') || (!a == 'stay')) {
//Do something here
}
And without brackets, but noting seems to work.
Thanks in advance
Your condition is a tautology. It's true no matter what the value of a is. If a is 'error' then a is not 'stay' and vice versa. It seems like what you want is
if (a != 'error' && a != 'stay') { /* ... */ }
You are including the (!) sign together in the brackets which is an error and will not make the logical operator work. You need to put the (!) sign outside and before the bracket. Check this code below for more clarity.
var a = "hello";
var b = "stay";
var c = "error";
if(!(a == 'error') || !(a == 'stay')) {
console.log("Hello");
};
for best practice, you should have it like this
var a = "hello";
var b = "stay";
var c = "error";
if(!(a == 'error' || a == 'stay')) {
console.log("Hello");
};

How do you make a javascript "if" statement with both "and" and "or"?

I'm trying to make a page where you fill in some input boxes and check a radio button, and if you complete all of it, you can click a div, and animations happen. The specific input boxes are not the only ones on the page. I'm trying to use a javascript "if" statement that has a bunch of "and"'s and an "or" in parentheses, but when I open the page, the code doesn't run. This isn't all my code, and I know the javascript and it's libraries are linked because I've been coding this site for a while, and everything has worked up until now. I checked the code in a javascript validator and it seemed fine. I'm not sure what I'm doing wrong.
$(document).ready(function(){
if ( $(".managementCompanyName").val() !== '' &&
$(".approvedBy").val() !== '' &&
$(".contractStartDate").val() !== '' &&
$(".proposalNumber").val() !== '' &&
$(!$("input[name='proposalReviewedForInvoice']:checked").val() || !$("input[id='proposalNotReviewedForInvoice']:checked").val()) ) {
//do stuff
}
});
Alternatively I have
$(document).ready(function(){
if ( $(".managementCompanyName").val() !== "" &&
$(".approvedBy").val() !== "" &&
$(".contractStartDate").val() !== "" &&
$(".proposalNumber").val() !== "" &&
$("input[name='proposalReviewedForInvoice']:checked").val() !== "" ) {
//do stuff
}
});
This code seems to work on another part of the site where there's only one input as a requirement.
Thank you if you can spot my error.
Wrap the || part in parentheses, otherwise the first operand to || is actually the last result from the last &&.
/*$*/(!$("input[name='proposalReviewedForInvoice']:checked").val() ||
!$("input[id='proposalNotReviewedForInvoice']:checked").val()) ) {
And actually it seems that you rather had them wrapped in a $(), which will always return a jQuery object, which will always be "truthy" in the condition.
for handling errors much better if you only used the "OR (||) " condition.
$(document).ready(function(){
var management = $(".managementCompanyName").val();
var approved = $(".approvedBy").val();
var contract = $(".contractStartDate").val();
var proposed_num = $(".proposalNumber").val();
var proposed_rev = $("input[name='proposalReviewedForInvoice']:checked").val();
if ( management == '' || approved == '' || contract == '' || proposed_num == ''
|| proposed_rev == '' ) {
// error message
} else {
// do stuff
}
});

Categories