JavaScript If Statement + Uncaught TypeError - javascript

1. I want ratingClass = 'fresh' if rating > 59 OR if audience_rating > 70. How?
I tried with
if (rating > 59) || (audience_rating > 70) {
var ratingClass = 'fresh';
Here's the code:
if (rating > 59) {
var ratingClass = 'fresh';
} else if (rating > 0){
var ratingClass = 'rotten';
} else {
var ratingClass = 'na';
}
if (audience_rating > 59) {
var audienceClass = 'fresh';
} else if (audience_rating > 0){
var audienceClass = 'rotten';
} else {
var audienceClass = 'na';
}
$parentEl.addClass(ratingClass);
2. In line 114 of http://pastebin.com/UN8wcB7b I get Uncaught TypeError: Cannot read property 'length' of undefined every ~3 seconds when hideRotten = true. Is it easily fixed and/or do I need to worry about it at all?
I am new to JavaScript coding, currently I am trying to learn by doing. Can you recommend any resources to learn writing Chrome Extensions with JavaScript?
Thanks :-)

it's because you are trying to read the length of a null element. So put a condition to test if movies are null in your if statement on line 114 so it says something like
if(data.movies && data.movies.length > 0)
Though if you're setting some data in this if statement that will be used other places in the code you may have to put checks like this in other places as well to completely avoid this type of problems.

The error definitely means
typeof data.movies === "undefined"
to avoid this I will recommend
...
$.getJSON(movieUrl, function(data){
// data can be undefined becoz of various reasons and so is data.movies
if(!(typeof data === "undefined") && !(typeof data.movies === "undefined")) {
//put similar checks in ur code
...

1) the condition after the if must always be completely surrounded in brackets:
// wrong
if (rating > 59) || (audience_rating > 70) {
// has to be:
if ( rating > 59 || audience_rating > 70 ) {
or if you are unsure about the operator precedence:
if ( (rating > 59) || (audience_rating > 70) ) {
2) You have to check first, if the movies attribute exists in your data respone (Because if it doesn't, you also can't call length on it):
// can throw error if data.movies === undefined
data.movies.length > 0
// the safe way, check data.movies first:
if (data.movies && data.movies.length > 0)
this is pretty much equivalent to the long version*:
if (typeof(data.movies) === `undefined` && data.movies.length > 0)
* Not exactly, read this article why

Related

I failed Javascript tech interview but I dont know why

I was only allowed to use google document for writing.
Could you please tell me what I did wrong? The recruiter wont get back to me when I asked her why I failed
Task 1:
Implement function verify(text) which verifies whether parentheses within text are
correctly nested. You need to consider three kinds: (), [], <> and only these kinds.
My Answer:
const verify = (text) => {
   const parenthesesStack = []; 
   
  for( let i = 0; i<text.length; i++ ) {
const closingParentheses = parenthesesStack[parenthesesStack.length - 1]
if(text[i] === “(”  || text[i] === “[” || text[i] === “<”  ) {
parenthesisStack.push(text[i]);
} else if ((closingParentheses === “(” && text[i] === “)”) || (closingParentheses === “[” && text[i] === “]”) || (closingParentheses === “<” && text[i] === “>”) ) {
   parenthesisStack.pop();
} 
  };
return parenthesesStack.length ? 0 : 1;  
}
Task 2:
Simplify the implementation below as much as you can.
Even better if you can also improve performance as part of the simplification!
FYI: This code is over 35 lines and over 300 tokens, but it can be written in
5 lines and in less than 60 tokens.
Function on the next page.
// ‘a’ and ‘b’ are single character strings
function func2(s, a, b) {
var match_empty=/^$/ ;
if (s.match(match_empty)) {
return -1;
}
var i=s.length-1;
var aIndex=-1;
var bIndex=-1;
while ((aIndex==-1) && (bIndex==-1) && (i>=0)) {
if (s.substring(i, i+1) == a)
aIndex=i;
if (s.substring(i, i+1) == b)
bIndex=i;
i--;
}
if (aIndex != -1) {
if (bIndex == -1)
return aIndex;
return Math.max(aIndex, bIndex);
} else {
if (bIndex != -1)
return bIndex;
return -1;
}
};
My Answer:
const funcSimplified = (s,a,b) => {
if(s.match(/^$/)) {
return -1;
} else {
return Math.max(s.indexOf(a),s.indexOf(b))
}
}
For starters, I'd be clear about exactly what the recruiter asked. Bold and bullet point it and be explicit.
Secondly, I would have failed you from your first 'for' statement.
See my notes:
// Bonus - add jsdoc description, example, expected variables for added intention.
const verify = (text) => {
// verify what? be specific.
const parenthesesStack = [];
for( let i = 0; i<text.length; i++ ) {
// this could have been a map method or reduce method depending on what you were getting out of it. Rarely is a for loop like this used now unless you need to break out of it for performance reasons.
const closingParentheses = parenthesesStack[parenthesesStack.length - 1]
// parenthesesStack.length - 1 === -1.
// parenthesesStack[-1] = undefined
if(text[i] === “(” || text[i] === “[” || text[i] === “<” ) {
parenthesisStack.push(text[i]);
// “ will break. Use "
// would have been more performant and maintainable to create a variable like this:
// const textOutput = text[i]
// if (textOutput === "(" || textOutput === "[" || textOutput === "<") {
parenthesisStack.push(textOutput)
} else if ((closingParentheses === “(” && text[i] === “)”) || (closingParentheses === “[” && text[i] === “]”) || (closingParentheses === “<” && text[i] === “>”) ) {
parenthesisStack.pop();
// There is nothing in parenthesisStack to pop
}
};
return parenthesesStack.length ? 0 : 1;
// Will always be 0.
}
Not exactly what the intention of your function or logic is doing, but It would fail based on what I can see.
Test it in a browser or use typescript playground. You can write javascript in there too.
Hard to tell without the recruiter feedback. But i can tell that you missundertood the second function.
func2("mystrs", 's', 'm') // returns 5
funcSimplified("mystrs", 's', 'm') // returns 3
You are returning Math.max(s.indexOf(a),s.indexOf(b)) instead of Math.max(s.lastIndexOf(a), s.lastIndexOf(b))
The original code start at i=len(str) - 1 and decrease up to 0. They are reading the string backward.
A possible implementation could have been
const lastOccurenceOf = (s,a,b) => {
// Check for falsyness (undefined, null, or empty string)
if (!s) return -1;
// ensure -1 value if search term is empty
const lastIndexOfA = a ? s.lastIndexOf(a) : -1
const lastIndexOfB = b ? s.lastIndexOf(b) : -1
return Math.max(lastIndexOfA, lastIndexOfB)
}
or a more concise example, which is arguably worse (because less readable)
const lastOccurenceOf = (s,a,b) => {
const safeStr = s || '';
return Math.max(safeStr.lastIndexOf(a || undefined), safeStr.lastIndexOf(b || undefined))
}
I'm using a || undefined to force a to be undefined if it is an empty string, because:
"canal".lastIndexOf("") = 5
"canal".lastIndexOf(undefined) = -1
original function would have returned -1 if case of an empty a or b
Also, have you ask if you were allowed to use ES6+ syntax ? You've been given a vanilla JS and you implemented the equivalent using ES6+. Some recruiters have vicious POV.

Codewars: SyntaxError unexpected token '&&' in a If else statement

Trying to solve Opposites Attract kata with an if else statement to check if flower1 has even/odd pedals as well as flower2 using &&.
if ((flower1 % 2) == 1) && ((flower2 % 2) == 0){
return true;
Which gives a SyntaxError: unexpected token '&&'
if( ((flower1 % 2) == 1) && ((flower2 % 2) == 0) ){
return true;
}
You did it correctly just didn't have enough brackets

How do I return a true when checking against 4 values in Javascript?

I have an if statement that has to allow for 4 parameter values and I am having trouble getting the syntax correct.
I have tested the 2 parts of the OR statement below separately and these return a true and false respectively but what I want is because the first argument returned a true for the do something to occur.
var d = 4;
var t = 2;
if ( (d >= 3.5 && d < 6) || (t >= 3.5 && t < 6) ){
console.log('true'); // do something
} else {
console.log('false');
}
I expect the if statement to be TRUE because the first part of the OR statement is correct and any code within to run.
UPDATE-------------------------------------------
Still getting issues, I have expanded the sample code to include what I am seeing
var dlG = "2";
var dl = "3.5";
if(parseFloat(dlG) < 3.5){
console.log("DLG Red");
}else if ( parseFloat(dlG) >= 3.5 && parseFloat(dlG) < 6 ){
console.log("DLG Purple");
}else if (parseFloat(dlG) >= 6){
console.log("DLG Green");
}
if(parseFloat(dl) < 3.5){
console.log("dl Red");
}else if ( parseFloat(dl) >= 3.5 && parseFloat(dl) < 6 ){
console.log("dl Purple");
}else if (parseFloat(dl) >= 6){
console.log("dl Green");
}
if((parseFloat(dl) < 3.5) || (parseFloat(dlG) < 3.5)){
console.log("Both Red");
}else if ((parseFloat(dl) >= 3.5 && parseFloat(dl) < 6 ) || (parseFloat(dlG) >= 3.5 && parseFloat(dlG) < 6 )){
console.log("Both Purple");
}else if ((parseFloat(dl) >= 6) || (parseFloat(dlG) >= 6)){
console.log("Both Green");
}
Essentially the first and second if statements work independently but I wanted to combine them with an OR statement in the 3rd if statement where I would expect to see 'Both Purple' in the console log but I see 'Both Red'.
Any ideas what I need to change?
I was approaching the problem from the wrong angle, on my example above the first if statement returned TRUE on certain criteria. On the second if statement the middle part (the first else if) returned TRUE on certain criteria.
I could not work out while the 3rd if statement was not working as expect but it was because the first and second parts both were returning TRUE.
Approaching the problem (in my larger code set) without using the if statements (and else parts) but using a different methodology has resolved the issue.
Thank you Randy and Colin for your help

If statement causes: Uncaught SyntaxError: Unexpected token <

I am trying to randomly select an option using Math.random()
This is the code I have so far.
function randChoice() {
var chance = Math.floor(Math.random() * 100);
if (chance > -1 && < 50) {
console.log("Option 1"); // 1
} else if (crateId > 49 && < 71) {
console.log("Option 2"); // 2
} else if (crateId > 70 && < 91) {
console.log("Option 3"); // 3
}
}
When I run it, I get an error saying Uncaught SyntaxError: Unexpected token <.
What is wrong with my syntax? I've been looking for at least an hour, but I can't find anything that will help or any indication of what went wrong.
This crateId > 49 && < 71 is not valid syntax.
There needs to be either a variable name or a literal between any two binary operators, only unary operators may be adjacent.
It needs to be: crateId > 49 && crateId < 71.

Location.pathname.indexOf not working with 'Or' ( || )

I'm trying to use location.pathname.indexOf to make conditional jQuery work on some pages on my site.
This works:
if (location.pathname.indexOf("/example/5820.htm") != 0){}
This works:
if (location.pathname.indexOf("/example-1/3569.htm") != 0) {}
This doesn't work:
if (location.pathname.indexOf("/example/5820.htm") != 0 || location.pathname.indexOf("/example-1/3569.htm") != 0) {}
I've done this a ton of times and for some reason this code is not working. I'm wondering if I'm missing something little in the code or if it's something else?
Tim already answered this question, but don't forget:
.indexOf() will return -1 when the string isn't found, not 0.
if (location.pathname.indexOf("/example/5820.htm") != 0){}
Should be:
if (location.pathname.indexOf("/example/5820.htm") != -1){}
Or:
if (location.pathname.indexOf("/example/5820.htm") >= 0){}
http://www.w3schools.com/jsref/jsref_indexof.asp
basically you're saying this:
var a = 0;
var b = 1;
if (a != 0 || b != 0) {};
Which is equal to
if (!(a == 0 && b == 0)) {};
However, you actually want this:
if (!(a == 0 || b == 0)) {};
Which is equal to:
if (a != 0 && b != 0) {};

Categories