Making a function parameter a variable within the same function - javascript

I want to pass my function's size parameter to be used inside the same function, specifically inside an 'if' statement.
function text_size(size){
if (size = '1'){
alert('something')
}
else if (size = '2'){
alert('something else')
}
}
This function is called inside another function (didn't write the whole function):
if (newImg.height > 750, newImg.width > 750){
text_size('1')
}
else if (newImg.height < 500, newImg.width < 500){{}
text_size('2')
}
As for now it always alerts 'something' regardless of the parameters.

Short answer:
Change if (size = '1'){ to if (size == '1'){ (and do the same for the second if).
Longer answer:
size = '1' sets size to '1' and evaluates as '1', which is evaluated as true in javascript. This makes the code inside the first if statement always run.

function text_size(size){
if (size === '1'){
alert('something')
}
else if (size === '2'){
alert('something else')
}
}
= assign a value to a variable
== do assertions between left and right conditions of the ==
=== do like == but also check type (string, integer, etc..)

if (newImg.height > 750, newImg.width > 750){
text_size('1')
}
should be (to use logically and, for or its ||):
if (newImg.height > 750 && newImg.width > 750){
text_size('1')
}

As #Tzach said, the problem comes from
if (size = '1'){
You have to use size == '1' instead.
Why? because if you use only one '=', in means that you are doing an assigantion :
var size = 0;
if (size = 1){...}
alert(size); //size is now equal to 1
var size = 0;
if (size == 1){...}
alert(size); //size is equal to 0

Related

I have an error in my school javascript project

I have multiple errors in my code. When I run the code, it gives an error saying that there is an unexpected identifier. Here is the full error, "SyntaxError: Unexpected identifier at /script.js:46:16". However, when I check through lines 46 through 16, I cant find any unclosed functions or methods. When I comment the if statement on line 46, it just gives an error on the other if statement. Can someone help me?
Heres the code:
function print(str){
console.log(str)
}
function farhToKelvin(far){
const cel = Math.floor(far / (9/5) - 32)
const kel = cel + 273
return kel
}
function farhToCelsius(far){
const cel = Math.floor(far / (9/5) - 32)
return cel
}
function convertToFarh(type, val){
type.toLowerCase()
val.toLowerCase()
if (type == "kelvin"){
return Math.floor(far / (9/5) - 32 - 273)
}
else if(type == "celsius"){
return Math.floor(far / (9/5) - 32)
}
}
while (farh != "exit"){
var farh = prompt("enter a farhanhite tempature: ")
var type = prompt("convert it to celsius, or kelvin")
type.toLowerCase()
if (type == "celsius"){
const c = farhToCelsius(farh)
var val = convertToFarh(c)
if (val > 50 or val == 50){
print("it is cold, you should wear a coat")
}
if (val > 50 or val == 50){
print("it is hot, you should wear a tank top")
}
}
else if(type == "kelvin"){
const k = farhToKelvin(farh)
var val = convertToFarh(k)
if (val > 50 or val == 50){
print("it is cold, you should wear a coat")
}
if (val > 50 or val == 50){
print("it is hot, you should wear a tank top")
}
}
}
if (val > 50 or val == 50){
In Javascript, instead of or, we use ||. If you have a similar problem again, you might want to take a look at What does this symbol mean in JavaScript?
change
if (val > 50 or val == 50)
to this
if (val > 50 || val == 50)
or better to this
if (val >= 50)
there are similar problems on line 50 and 60 and 64
you need to update them all.
logically line 46 and 50 are the same. based on you print message the line 50 should be
if (val > 50 ) but line 45 should be if ( val <= 50)
so you have both syntax and semantic problems in your code to address
Here's a complete list of the issues you have in your code:
Using or instead of || (as others have stated)
Using incorrect variable name in the convertToFarh function
Omitting type parameter when calling convertToFarh
Attempting to call String.toLowerCase() on a number variable
Misspelling fahrenheit
Using or instead of || (Logical OR)
In your code, I believe you are intending to indicate if (val > 50 || val == 50) { instead of using or as used in other programming languages.
Before:
if (val > 50 or val == 50){
print("it is cold, you should wear a coat")
}
if (val > 50 or val == 50){
print("it is hot, you should wear a tank top")
}
After:
if (val > 50 || val == 50){
print("it is cold, you should wear a coat")
}
if (val > 50 || val == 50){
print("it is hot, you should wear a tank top")
}
This logic also doesn't make sense. Perhaps you mean value < 50 in the first one and val >= 50 in the second?
You also repeat yourself whether you're converting to/from Kelvin or Celsius, so that code could be extracted out into its own function or just reduce the if..else blocks down to only affect the necessary variables and perform the comparison after these blocks.
Using incorrect variable name in convertToFarh function
In the convertToFarh function, you reference a variable named far, but there's no variable by that name. So you either mean to reference the val argument or you are trying to reference the fahr variable declared outside the function. In my code, I assume the former is the case val and rename it as follows:
function convertToFarh(type, val){
type.toLowerCase()
val.toLowerCase()
if (type == "kelvin"){
return Math.floor(val / (9/5) - 32 - 273)
}
else if(type == "celsius"){
return Math.floor(val / (9/5) - 32)
}
}
Omitting type parameter when calling convertToFarh
In both function calls to convertToFarh, you use the c or k variable as the value of the val parameter, but you don't indicate the type. I have fixed this to indicate the type for each part:
var val = convertToFarh("celsius", c);
var val = convertToFarh("kelvin", k);
Attempting to call String.toLowerCase() on a number variable
In the convertToFarh function, you are attempting to call the String.toLowerCase() method on a number type (val) which gives an error. In my code, I simply commented this out and confirmed it can safely be removed.
Misspelling fahrenheit
It might not seem like a big deal, but making sure variables have proper spelling helps when others are reviewing your code (whether bug-fixing or general code review). I have fixed function names, variable names, and any references to fahrenheit in your code to be the proper spelling. This includes:
"enter a fahrenheit temperature: "
function fahrToKelvin and function calls
function fahrToCelsius and function calls
function convertToFahr and function calls
The variable named farh to fahr
Function parameters named far were changed to val to avoid variable name collision
Full code
function print(str) {
console.log(str);
}
function fahrToKelvin(val) {
const cel = (val - 32) / (9 / 5);
return Math.floor(cel + 273.15);
}
function fahrToCelsius(val) {
const cel = Math.floor((val - 32) * 5 / 9);
return cel;
}
function convertToFahr(type, val) {
if (type == "kelvin") {
return Math.floor(val / (5 / 9) - 459.67);
} else if (type == "celsius") {
return Math.floor(val / (9 / 5) + 32);
}
}
var fahr = prompt("enter a fahrenheit tempature: ");
var type = prompt("convert it to celsius, or kelvin");
type = type.toLowerCase();
if (type == "celsius") {
const c = fahrToCelsius(fahr);
var val = convertToFahr("celsius", c);
if (val < 50) {
print("it is cold, you should wear a coat");
}
if (val >= 50) {
print("it is hot, you should wear a tank top");
}
} else if (type == "kelvin") {
const k = fahrToKelvin(fahr);
var val = convertToFahr("kelvin", k);
if (val < 50) {
print("it is cold, you should wear a coat");
}
if (val >= 50) {
print("it is hot, you should wear a tank top");
}
}

If Conditionals Inside of For Loop

I'm looking for insight into my if conditionals within my for loop. Currently, when I execute this function, the initial if conditional outside of the for loop runs, then the for loop starts. My test data has a length of 12, so the for loop runs the if (length > 10) conditional twice, and then runs the else if (length == 10) conditional. However, then it stalls and won't execute the next else if conditional (else if (length > 3 && length <=10 && mergedGroup != [])).
I think the issue lies with mergedGroup != [] but I'm not sure how to say "don't execute this conditional unless length > 3 and length <= 10 and mergedGroup array isn't empty."
Assume all functions and variables inside this executeFullRun function are built and correct (I've tested them line by line in the console, just having issues putting them into one function to run all of them together).
Any insight?
function executeFullRun(players) {
if (group1 != [] && group2!= []) {
makeGroups(players);
}
var length = group1.length + group2.length;
for (i=0;i<length;i++) {
if (length > 10) {
while (group1.length + group2.length > 10) {
winTribalImmunity(group1,group2);
voteOffPreMerge(vulnerablePlayers);
console.log('Group Vote');
length -= 1;
console.log(length);
}
} else if (length == 10) {
if (group1.length + group2.length == 10) {
mergeGroups(group1,group2);
console.log('Merge Groups');
console.log(length);
}
} else if (length > 3 && length <=10 && mergedGroup != []) {
while (length > 3) {
winIndividualImmunity(mergedGroup);
voteOffPostMerge(vulnerableIndividuals);
console.log('Individual Vote');
length -= 1;
console.log(length);
}
} else {
if (length == 3) {
winGame(mergedGroup);
console.log('Winner!');
}
}
}
}
You can't compare an empty array to another empty array by doing someExistingArray != [].
They are completely different object references and therefore are never equal, regardless if contents and length are identical.
Check the array length instead
Try
if (length > 3 && length <=10 && mergedGroup.length) {
And
if (group1.length && group2.length) {

In JavaScript is there a strict equivalent of || when used in assignment of variables?

I have been working on a piece of code that had a set of computations resulting in a new position of another object. Something like the following:
if (foo.length === 0) {
position = 'something';
} else if ((position = bar.compute()) !== false) {
// do nothing
} else if ((position = baz.compute()) !== false) {
// do nothing
} else {
position = 'some default';
}
now looking at this code it looks a bit off to me. A lot actually. I could do the compute() method on bar and baz again inside the body of the if statement but that means double compute time. the compute method itself tries to find a new position and returns false when it does not.
naturally I thought of this as a more elegant coding solution:
if (foo.length === 0) {
position = 'something';
} else {
position = bar.compute() || baz.compute() || 'some default';
}
However this won't work as the compute method can also return a value 0. This should be returned and assigned to the position but it does not. Why? the comparator is not strict.
Is there a way to use this last suggested style of assignment and get 0 to be returned as the position? is there an equivalent of '===' for '||'?
EDIT: note that this is a hypothetical case where x = a || b || c the cases can be a number 0 to N or false when the value is not found. problem is that false == 0 and this is used during assignment.
EDIT: added origin code block change by #T.J.Crowder
the core returns a number that could be 0. or false when it cannot find a value
Your first code block will assign 'some default' if both computes return 0. If you want to only continue when compute returns false, your first code block would need to be:
if (foo.length === 0) {
position = 'something';
} else if ((position = bar.compute()) !== false) {
// do nothing
} else if ((position = baz.compute()) !== false) {
// do nothing
} else {
position = 'some default';
}
(You've since edited the question to copy the above into it.)
or condensing that a bit:
if (foo.length === 0) {
position = 'something';
} else if ((position = bar.compute()) !== false ||
(position = baz.compute()) !== false) {
// do nothing
} else {
position = 'some default';
}
or something similar using typeof to see whether you got back a "number".
Is there a way to use this last suggested style of assignment and get 0 to be returned as the position? is there an equivalent of '===' for '||'?
No, there isn't. You can still use ||, but it'll be more complicated to read and debug. For instance, this would probably work:
if (foo.length === 0) {
position = 'something';
} else {
(position = bar.compute()) !== false || (position = bar.compute()) !== false || (position = 'some default');
}
...but that's pretty hard to understand, arguably an "abusage" of the || rather than a usage of it. You could probably come up with a complicated use of the conditional operator (? :), but it would be similarly more awkward to read and debug.
Just proving to myself that the abusage works:
var foo = ['one'];
test(false, false);
test(0, false);
test(false, 0);
test(1, false);
test(false, 1);
function test(c1value, c2value) {
var position;
if (foo.length === 0) {
position = 'something';
} else {
(position = c1value) !== false || (position = c2value) !== false || (position = 'some default');
}
snippet.log("position for " + c1value + ", " + c2value + ": " + position);
}
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

Javascript if statement not executing 2nd parameter

I have a var that is either 1 or 0, if it's 1 the page should go to cnn.com if it's 0 it should go to google.com. Problem is, when it's 1 or 0 it always goes to google.com. Check out the running version at http://jsbin.com/ucovef/7 Thanks in advance
function random(){
var randomnumber=Math.floor(Math.random()*2)
document.getElementById('randomnumber').innerHTML=(randomnumber);
check_random()
}
function check_random(){
if (randomnumber = 0){
this.location.href ="http://www.cnn.com";
}
if (randomnumber = 1){
this.location.href="http://www.google.com";
}
}
You need:
if (randomnumber == 0)
And:
if (randomnumber == 1)
Expressions randomnumber = 0 and randomnumber = 1 are assignment expressions that assign numbers 0 and 1 to the variables, despite them being inside an if conditional statement.
So, it always goes to google.com because everything not equal to 0 is a true expression in JavaScript.
You have to use == to make a check. = sets the value instead of evaluating it. I would also suggest passing the random number to the function.
function random(){
var randomnumber=Math.floor(Math.random()*2)
document.getElementById('random').innerHTML=(randomnumber);
check_random(randomnumber)
}
function check_random(randomnumber){
if (randomnumber == 0){
this.location.href ="http://www.cnn.com";
}
else if(randomnumber == 1){
this.location.href="http://www.google.com";
}
}
You must use == not = !!!!!!!!!!!!!!!!
Ben, you are using local variable from random in check_random. This won't work. Try this
function random(){
var randomnumber=Math.floor(Math.random()*2)
document.getElementById('randomnumber').innerHTML=(randomnumber);
check_random(randomnumber)
}
function check_random(n){
if (n == 0){
this.location.href ="http://www.cnn.com";
}
if (n == 1){
this.location.href="http://www.google.com";
}
}

Multiple Logical Operators in javascript

I want to check the following
1: Is x a number
2. If x is less that 5 or greater than 15, sound alert
3. If all is ok, callMe()
var x = 10;
if (isNaN(x) && ((x < 5) || (x > 15))) {
alert('not allowed')
}
else
{
callMe();
}
What am I doing wrong?
var x = 10;
if (isNaN(x) || (x < 5) || (x > 15)) {
alert('not allowed')
}
else
{
callMe();
}
This way, if x is not a number you go directly to the alert. If it is a number, you go to the next check (is x < 5), and so on.
All the other answers about the && vs || are correct, I just wanted to add another thing:
The isNaN() function only checks whether the parameter is the constant NaN or not. It doesn't check whether the parameter is actually number or not. So:
isNaN(10) == false
isNaN('stackoverflow') == false
isNaN([1,2,3]) == false
isNaN({ 'prop' : 'value'}) == false
isNaN(NaN) == true
In other words, you cannot use it to check whether a given variable contains a number or not. To do that I'd suggest first running the variable through parseInt() or parseFloat() depending on what values you expect there. After that check for isNaN(), because these functions return only numbers or NaN. Also this will make sure that if you have a numeric string then it is also treated like a number.
var x = 10;
if (isNaN(x) || (x < 5) || (x > 15)) {
alert('not allowed')
}
else
{
callMe();
}

Categories

Resources