Declaring a variable then changing it with an if statement? - javascript

Is it necessary to add an if/else statement when declaring a variable within a function? Can I just set the variable first and then change it if a condition is met?
function doSomething() {
var a = 1;
if(something) {
a = 2;
}
}
vs
function doSomething() {
var a;
if(something) {
a = 2;
} else {
a = 1;
}
}

Yes you can do that (technically). Regarding understanding or code complexity, keep it as simple as possible.
I think your intentions would be even clearer if you used the conditional operator:
var a = something ? 2 : 1;

No, it's not necessary, as long as evaluating the second value in the initialisation has no side effects (in your case, the literal 1, it has none).
However, using if-else might show your intention better and make the code cleaner; though that is more a matter of style than functionality. Personally I would even prefer a conditional expression:
var a = condition ? 2 : 1;

Yes, you can do that - even shorter like this
var a = 1;
if (something) a = 2;

Related

Javascript on click event not reading else statement or variables

I'm trying to make a click handler that calls a function; and that function gets a string and basically slices the last character and adds it to the front, and each time you click again it should add the last letter to the front.
It seem so easy at first that I thought I could just do it using array methods.
function scrollString() {
var defaultString = "Learning to Code Javascript Rocks!";
var clickCount = 0;
if (clickCount === 0) {
var stringArray = defaultString.split("");
var lastChar = stringArray.pop();
stringArray.unshift(lastChar);
var newString = stringArray.join('');
clickCount++;
} else {
var newArray = newString.split("");
var newLastChar = newArray.pop();
newArray.unshift(newLastChar);
var newerString = newArray.join("");
clickCount++;
}
document.getElementById('Result').innerHTML = (clickCount === 1) ? newString : newerString;
}
$('#button').on('click', scrollString);
Right now it only works the first time I click, and developer tools says newArray is undefined; also the clickCount stops incrementing. I do not know if it's an issue of scope, or should I take a whole different approach to the problem?
Every time you click you are actually reseting the string. Check the scope!
var str = "Learning to Code Javascript Rocks!";
var button = document.getElementById("button");
var output = document.getElementById("output");
output.innerHTML = str;
button.addEventListener("click", function(e){
str = str.charAt(str.length - 1) + str.substring(0, str.length - 1);
output.innerHTML = str;
});
button{
display: block;
margin: 25px 0;
}
<button id="button">Click Me!</button>
<label id="output"></label>
It is, in fact, a scoping issue. Your counter in inside the function, so each time the function is called, it gets set to 0. If you want a counter that is outside of the scope, and actually keeps a proper count, you will need to abstract it from the function.
If you want to keep it simple, even just moving clickCount above the function should work.
I do not know if it's an issue of scope
Yes, it is an issue of scope, more than one actually.
How?
As pointed out by #thesublimeobject, the counter is inside the function and hence gets reinitialized every time a click event occurs.
Even if you put the counter outside the function, you will still face another scope issue. In the else part of the function, you are manipulation a variable (newString) you initialized inside the if snippet. Since, the if snippet didn't run this time, it will throw the error undefined. (again a scope issue)
A fine approach would be:
take the counter and the defaultString outside the function. If the defaultString gets a value dynamically rather than what you showed in your code, extract its value on page load or any other event like change, etc. rather than passing it inside the function.
Do not assign a new string the result of your manipulation. Instead, assign it to defaultString. This way you probably won't need an if-else loop and a newLastChar to take care of newer results.
Manipulate the assignment to the element accordingly.
You can use Javascript closure functionality.
var scrollString = (function() {
var defaultString = "Learning to Code Javascript Rocks!";
return function() {
// convert the string into array, so that you can use the splice method
defaultString = defaultString.split('');
// get last element
var lastElm = defaultString.splice(defaultString.length - 1, defaultString.length)[0];
// insert last element at start
defaultString.splice(0, 0, lastElm);
// again join the string to make it string
defaultString = defaultString.join('');
document.getElementById('Result').innerHTML = defaultString;
return defaultString;
}
})();
Using this you don't need to declare any variable globally, or any counter element.
To understand Javascript Closures, please refer this:
http://www.w3schools.com/js/js_function_closures.asp

How do I add up a number to a properties in my object?

I have an object like this:
var statistics = {
won: 0,
tie: 0,
lost: 0
};
I have a function that adds 1 to won:
var plus1 = function() {
return statistics.won++;
}
I call that function within an if/else statement like this:
plus1();
But it doesn't work. Does anyone have an idea?
It's probably that x++ returns x instead of x+1.
You are looking for
var plus1 = function() {
return ++statistics.won;
}
Looking at your code I don't really see any reason why you would return your result.
I would rewrite the function to simply be
function plus1() {
statistics.won++;
}
When it comes to having it update, I can't see any were in your code where you actually update the html. After you've run plus1(). If I run console.log(statistics) in my Console I can see that statistic.won goes up whenever I win.
As already mentioned in the comment above, if you run wins() after you've run plus1() it will all work.
This is due to to way pre/post incrementation works in JavaScript:
var one = 1;
var two = 1;
// increment `one` FIRST and THEN assign it to `three`.
var three = ++one;
// assign `two` to `four`, THEN increment it
var four = two++;
So in your code, you're assigning the value of statistics.won to the return value first and then incrementing it. You can see the difference in how they work here.
So, as I mentioned in the comments, return ++statistics.won; is the solution you need.

If statement is not working properly

I'm trying to change the condition in which data is written to a table. I noticed a strange result when trying to change this: it seems WriteToTable function would runno matter what if condition I subjected it to. To test this I did the following:
var TestThis=0;
if (TestThis=1000){
WriteToTable(iPlaceDisplayNum, place.name, place.rating, xScoreFinal, iProspect, place.url, place.formatted_phone_number);
alert ('This alert should not be displaying.');
}
The function will still execute and the alert will be still be displayed when the script runs. I'm not sure why?
Here's the rest of the function, the problem is towards the bottom:
function printme(place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
if (typeof place.reviews !== 'undefined') {
var xScore = 0;
var xGlobal = 0;
for (var i = 0; i < place.reviews.length; i++) {
reviews = place.reviews[i];
for (var x = 0; x < reviews.aspects.length; x++) {
aspectr = reviews.aspects[x];
xScore += aspectr.rating;
xGlobal++;
}
}
var xScoreFinal = (xScore / xGlobal);
}
if (typeof xScoreFinal !== 'undefined') {
iPlaceDisplayNum++;
var iProspect;
if (xScoreFinal < 2.3) {
iProspect = 'Yes';
}
//Not sure what's going on here
var TestThis=0;
if (TestThis=1000){
WriteToTable(iPlaceDisplayNum, place.name, place.rating, xScoreFinal, iProspect, place.url, place.formatted_phone_number);
alert ('This alert should not be displaying.');
}
}
}
}
You are assigning a value to your variable in your if condition check. Your TestThis variable is being assigned value 1000, which will be true after being converted to boolean by JavaScript. That's why your function is being always executed. You can read more about the automatic type conversion here.
Now to fix your code, change this -
if (TestThis=1000)
to this -
if (TestThis == 1000)
or if you don't want automatic type conversion -
if (TestThis === 1000)
Sometimes people like to reverse the values in the comparison, in the following way -
if (1000 === TestThis)
This is called a Yoda Condition (yeah, named after the Grand Jedi Master Yoda) . The benefit is that in case someone mistakenly puts only a single equal, it will result in an error as you cannot assign anything to a constant. I have never used it personally though (and probably never will because I find it rather unconventional).
JavaScript allows you to assign a value in a conditional, so this TestThis=1000 results to 1000 and in a conditional statement positive numbers (actually anything not 0) result to an evaluation to true.
To make it a conditional, you should do TestThis===1000 (and you should almost always use the === over the == as the === forces an actual comparison of the two and doesn't try to convert one part of the conditional to equal the other.)
You can also do 1000 === TestThis (or conversly 1000 == TestThis) Some people say this is bad coding, because it's difficult to read. I'll leave that up to you to decide, but this absolutely won't allow you to accidentally assign a value in the conditional because you can't assign a value to 1000.
In the if statement, you're setting TestThis to 1000, rather than comparing it to 1000. The = operator returns the value that was set, which evaluates to true because it is not undefined, 0, or null. You simply need to use the == operator.
if(TestThis == 1000)
if (TestThis == 1000)
Change like this.
For comparing equality in if you must have ==
Change:
if (TestThis=1000)
To:
if (TestThis==1000)
You're actually assigning to TestThis which will return true and execute the conditional block.

Why does this JQuery only work if I console.log a bad variable? [duplicate]

This question already has answers here:
Why does this append only work if I console log a bad variable
(2 answers)
Closed 9 years ago.
I am relatively new with jquery, and am trying to change an up and down arrow on a js accordion on each click, unfortunately, I have run into an error where it only works if I console.log a bad variable. Does anyone have any guidance as to what I might be doing wrong when I onclick="embiggen(1)" for example if its accordion id one?
There are some other issues surrounding the html, but specifically why is this only working if I console.log;?
function arrowup(id){
$('#downarrow'+id).remove();
$('#dropdown'+id).append('</a>');
$('#dropdown'+id).append('<i id="uparrow'+ id +'" class="icon-1 icon-chevron-up">');
}
function arrowdown(id){
$('#uparrow'+id).remove();
$('#dropdown'+id).append('</a>');
$('#dropdown'+id).append('<i id="downarrow'+ id +'" class="icon-1 icon-chevron-down">');
}
//Switches the arrows
function embiggen(id){
var up = $('#uparrow'+id).length;
if (up == 1){
arrowdown(id);
console.log(i see you);
}
var down = $('#downarrow'+id).length;
if (down == 1){
arrowup(id);
}
}
The bad console.log() makes it "work" because the error breaks the script execution before entering the second if statement.
Fixing the real issue
down == 1 is always true. You should use an else statement:
if ($('#uparrow'+id).length){
arrowdown(id);
} else if ($('#downarrow'+id).length){
arrowup(id);
}
Understanding it
down == 1 is always true independently of up == 1. Here's your logic explained in pseudo-code in both scenarios:
var up = 1, down = 0;
if (up) { down = 1; up = 0; } //enters this block, down now is 1
if (down) { down = 0; up = 1; } //enters this block as down == 1
var up = 0, down = 1;
if (up) { down = 1; up = 0; } //doesn't enter this block
if (down) { down = 0; up = 1; } //enters this block as down == 1
You just have put an else in there so the execution flow does not enter the second if statement in case the first one succeeds.
if (up) {}
else if (down) {}
Truthy/Falsy values
To explain why I'm using .length isolated inside the conditional statement: in JavaScript, the number 0 is a falsy value and 1 is truthy, hence these can be used directly inside the if statement and it will be interpreted based on the internal ToBoolean algorithm logic. Obviously you can == 1 if you feel like, that's more clear though slightly redundant.
A possibly simpler way around
Going a little off-topic, but your goal can most likely be achieved in an easier way. I may be oversimplifying your logic, but depending on your intents you may just toggle between those two classes:
function embiggen(id) {
$('#arrow'+id).toggleClass('icon-chevron-up icon-chevron-down');
}
Then, you'd no longer have to create a new #downarrow/#uparrow element each time the function is called. If said arrow has JS behavior attached, you can check which logic to execute through an if statement using hasClass().
It works because when an error occurs, JavaScript skips the rest of your function body.
The problem in your case is that the function arrowdown() creates #downarrow+id, making the next condition truthy and calling the function arrowup().
You either need an alternative branch, using Fabricio's answer, or return immediately after making changes to the DOM that would otherwise change the state:
function embiggen(id) {
if ($('#uparrow'+id).length) {
return arrowdown(id);
}
if ($('#downarrow'+id).length) {
return arrowup(id);
}
// ehm, something else happened?
}

Avoiding having to write the same word over and over again

I'm very new to javascript so this question might sound stupid. But what is the correct syntax of replacing certain words inside variables and functions. For example, I have this function:
function posTelegram(p){
var data = telegramData;
$("#hotspotTelegram").css("left", xposTelegram[p] +"px");
if (p < data[0] || p > data[1]) {
$("#hotspotTelegram").hide()
} else {
$("#hotspotTelegram").show()
}
};
There is the word "telegram" repeating a lot and every time I make a new hotspot I'm manually inserting the word to replace "telegram" in each line. What would be a smarter way of writing that code so that I only need to write "telegram" once?
Group similar / related data in to data structures instead of having a variable for each bit.
Cache results of calling jQuery
Use an argument
function posGeneral(p, word){
// Don't have a variable for each of these, make them properties of an object
var data = generalDataThing[word].data;
// Don't search the DOM for the same thing over and over, use a variable
var hotspot = $("#hotspot" + word);
hotspot.css("left", generalDataThing[word].xpos[p] +"px");
if (p < data[0] || p > data[1]) {
hotspot.hide()
} else {
hotspot.show()
}
};
You can't always avoid this kind of repetition (this is general to all programing languages).
Sometimes, you can make generic functions or generic classes, for example a class which would embed all your data :
Thing = function(key, xpos) {
this.$element = $('#hotspot'+key);
this.xpos = xpos;
};
Thing.prototype.pos = function (p, data) {
this.$element.css("left", this.xpos[p] +"px");
if (p < this.data[0] || p > this.data[1]) {
this.$element.hide()
} else {
this.$element.show()
}
};
And we could imagine that this could be called like this :
var telegramThing = new Thing('telegram', xposTelegram);
...
telegramThing.pos(p, data);
But it's really hard to make a more concrete proposition without more information regarding your exact problem.
I recommend you read a little about OOP and javascript, as it may help you make complex programs more clear, simple, and easier to maintain.
For example, using a Thing class here would enable
not defining more than once the "#hotspotTelegram" string in your code
reusing the logic and avoid making the same code with another thing than "telegram"
not having the Thing logic in your main application logic (usually in another Thing.js file)
But don't abstract too much, it would have the opposite effects. And if you don't use objects, try to keep meaningful variable names.
var t = "Telegram";
var $_tg = $('#hotspotTelegram');
$_tg.css("left", "xpos"+t[p] + "px"); // not sure about this line, lol
$_tg.hide();
$_tg.show();
etc.
you can create a selector as variable, something like this
function posTelegram(p){
var data = telegramData;
var $sel = $("#hotspotTelegram");
$sel.css("left", xposTelegram[p] +"px");
if (p < data[0] || p > data[1]) {
$sel.hide()
} else {
$sel.show()
}
};

Categories

Resources