JavaScript newbie learning (increments) [duplicate] - javascript

This question already has answers here:
Increment variable by more than 1?
(5 answers)
Closed 1 year ago.
starting to learn JavaScript, and I am currently learning incrementations and decrement, is it possible to increment on your desired value?
example: increment = 10
let earnedUsd = 10;
earnedUsd ++;
console.log(earnedUsd ++ = 10);

There are many ways to do that. Here are 3 examples to show the solutions. I recommend to use the 1st and 2nd way, 3rd way is not optimal.
//1st way
var a = 5;
a++
//2nd way
var b = 5;
b += 1;
//3rd way
var c = 5;
c = c + 1;
console.log(a)
console.log(b)
console.log(c)

let earnedUsd = 10;
console.log(earnedUsd++) // earnedUsd = earnedUsd + 1
console.log(earnedUsd += 10) // earnedUsd = earnedUsd + 10
MDN Increment
MDN +=

earnedUsd++ increments the value by 1
It returns the new value, which you could (for example) put into another variable or output with console.log. In your case, you are simply incrementing earnedUsd and not doing anything with the result. That is fine.
You have mis-spelled the second usage: you probably meant earnedUsd += 10
On its own, the following statement will simply increase the stored value of earnedUsd by 10.
earnedUsd += 10
It returns the new value, so you can console.log it if you want.
console.log(earnedUsd += 10)
This will display the new value. This pattern of writing code was common in C, but we try to discourage it in Javascript because it can be easy to miss, when skim-reading the code, that you are actually changing the stored value of earnedUsd.
earnedUsd ++= 10 is a syntax error. To add 1, just use ++. To add 10, just use +=10.

Related

'Swap' values within a range

I get data that is a floating point value between 1 and 7.
1 is bad, 7 is good.
Sometimes, when I get that data, I'd like to 'reverse' it, as the questions were written negatively, where 1 is good, and 7 bad.
A score of 1 should be 'swapped' to a score of 7.
A score of 2 should be 'swapped' to a score of 6.
A score of 2.5 should be 'swapped' to a score of 4.5.
Originally I thought I could use an array:
const array = [1,2,3,4,5,6,7]
return array[answer] - 1;
or Math.abs(answer - 6) but neither are going to work out.
I think you don't need an array, if your values are fixed (from 1 to 7) you can just substract from 8:
return 8 - answer;
Here is a simple function to achieve that:
function reverseRating(rating) {
return 8 - rating
}
The following function accomplishes this:
function reverseOnScale(answer, from, to) {
answerMinus = answer - from;
reversedMinus = Math.abs(answerMinus - (to - from));
reversed = reversedMinus + from;
return reversed;
}
Usage example:
reverseOnScale(5, 1, 7);
Outputs the value 3.

Declare JavaScript variable only with ' ' marks

I saw one of the masters doing this:
var example = '';
Then later he continued with this:
example += '<div>just a div</div>';
I wanna know if there's any difference from doing this:
var example;
example += '<div>just a div</div>';
I don't really know if by doing the second method I'm doing wrong and I have to code like shown if the first example.
Updated!
Thank you so much for your answers, Ok I got it I need to define my variable to be able to work woth it, but then another question came... This master also is doing this:
var guess;
and then he does:
guess += myfunction( upper );
where myfunction was declared as follows:
function myFunction( upper ){
return Math.floor( Math.random() * upper ) + 1;
}
So, why here is different? Can any of you answer this please?
Thank you!
Second update!
Again Thanks!
I decided to post the whole code the JS master was doing, at this point I don't understand, so probably you'll be able to clear my doubts.
var randomNumber = myFunction( 10 );
var guess;
var attempts = 0;
var answer = false;
function myFunction( upper ){
return Math.floor( Math.random() * upper ) + 1;
}
do{
guess = prompt( "I created a number from 1 till 10, can you guess it?");
attempts += 1;
if( parseInt( guess ) === randomNumber ){
answer = true;
}
}while( ! answer )
document.write( "Took you " + attempts + " attempts to guess the number " + randomNumber);
Please have a look at:
var guess;
and how later is being declared, so why here works perfectly but in my first example I have to put the '' when declaring my variable?
I hope my question is clear enough for you!
Thank you for your time and patient!
When you do:
var example;
example += '<div>just a div</div>';
You end up with:
`"undefined<div>just a div</div>"`
This is because when you don't initialize a variable, it is undefined, which can be converted to a sensible string "undefined" when you try to add it to another string.
When you do:
var guess;
guess += myfunction( upper );
function myFunction( upper ){
return Math.floor( Math.random() * upper ) + 1;
}
You are adding a number to undefined. This results in NaN (not a number) because undefined cannot be converted into a sensible number.
You can check this yourself next time by opening up your browser's developer tools and running the code in the console.
Edit:
When you do:
var guess;
guess = prompt( "I created a number from 1 till 10, can you guess it?");
There's no issue because you are simply assigning a string to the guess variable. In the previous examples you were adding something to a variable, which means if they are different types then JavaScript has to try to do something sensible.
If you don't initialize your variable it has a value of undefined.
In your last example, you are really saying example = undefined + '<div>just a div</div>' and undefined will be converted to a string and output that way. Probably not what you want.
In general it is a good idea to initialize your variables before you use them which is why var example = '' is preferable in this case.
var myvar
myvar += 'asdf'
console.log(myvar) // prints undefinedasdf
var othervar = ''
othervar += 'sdfasdf'
console.log(othervar) // prints sdfasdf
If you don't initialize the variable then it will be undefined
Appending to undefined object doesn't help.
var example = '';
Here you are initializing an empty string to the variable and therefore appending a string to another string will give the desired output of string concatenation.
Output:
"undefined<div>just a div</div>"
"<div>just a div</div>"
Yes there is a difference the first snipet from the master creates a variable example and gives it a default value, the second statement concatinates the value with 'just a div'
.Your code has an error as it is adding a value to a non-existed value as variable example has no default value.

Javascript: Basic for loop?

I just completed some form of a competency exam for a programming school, and I got every question correct except this, although it appears really quite easy, yet I couldn't get it. Any ideas?
Observe the code below.
var x = [1,5,7,13];
for(i=0; i < x.length; i++)
{
x[i] = x[3-i] + 2;
}
Once the program is done, what would be in x?
a [3,7,9,15]
b [15,9,11,3]
c [15,9,7,3]
d [15,9,11,17]
The answer is d
first loop
x[0] = 13 + 2 = 15
second loop
x[1] = 7 + 2 = 9
third loop
x[2] = 9 + 2 = 11
fourth loop
x[3] = 15 + 2 = 17
x = {15, 9, 11, 17}
To figure this out, you'll have to understand that x[] is used to refer to a specific index of the array. For example:
var x = [5,6,7];
In this case, x[0] would be equal to 5, assuming a 0-index based array.
Knowing this, let's break down your loop. We'll start by filling in the variable name instead of the variable value step by step, to leave out confusion of following variables in your head.
var x = [1,5,7,13];
for(0=0; 0 < x.length; 0++)
{
x[0] = x[3-0] + 2;
}
For the first iteration, everything starts to become a little clearer as you can tell that now it's setting x[0] (the first value in the array) to equal x[3-0] (which would be x[3], which in turn would be 13 due to the 0-index array), plus 2. 13 + 2 = 15. The first number is 15.
var x = [1,5,7,13];
for(1=1; 1 < x.length; 1++)
{
x[1] = x[3-1] + 2;
}
Let's try one more! x[3-1] is the same as x[2] which is 7; 7 + 2 = 9. Your second number is 9.
Following the same logic you can see how the loop functions and understand how it's referencing the array's values.
The key here is that you're updating the same array you're reading from as you go through it. (Note: generally I'd consider this bad practice and I've seen a lot of programmers fall into this trap - it's very easy to misunderstand the code).
First thing to realize is that x[3-i] basically reads the opposite end of the current index. To be more generic, it should really have been x[(x.length-1)-i] but the 3 is hardcoded in this case.
Now, the first round is easy: 13+2 = 15. 13 because the opposite end of the first element is the last element:
x = [15,5,7,13]
▲ │ this+2
└──────┘
In the second round we replace 5 with 7+2 = 9:
x = [15,9,7,13]
▲ │ this+2
└─┘
In the third round we find ourselves doing something not initially obvious. Instead of replacing 7 with 5+2 we replace it with 9+2 instead because we've already replaced 5 with 9:
x = [15,9,11,13]
│ ▲
this+2 └─┘
Now finally we replace the last element with 15+2 using the same reasoning above:
x = [15,9,11,17]
│ ▲
└───────┘
this+2

number incrementing in Angular.js

I'm attempting to build an app that calculates sales metrics. I have run into an unusual problem in my build.
Part of the app allows users to increase/decrease a variable by 5% and then see how that will effect an overall metric. It also allows the user to see the percentage increase/decrease.
I have the functionality working roughly as intended, however if I enter a number lower than 20 into the input and then try in increase it with my incrementing function it only increments once and then stops.
If the number I enter into the input is 20 or greater it increments in the intended way.
Below is my angular code:
function controller ($scope) {
$scope.firstNumber = 0;
$scope.firstPercent = 0;
$scope.increase = function(id) {
var A = parseInt(id);
var B = A * 5/100;
var C = 0;
var C = A + B;
if (id === $scope.firstNumber) {
$scope.firstNumber = C;
$scope.firstPercent = $scope.firstPercent + 5;
}
};
$scope.decrease = function(id) {
var A = parseInt(id);
var B = A * 5/100;
var C = 0;
var C = A - B;
if (id === $scope.firstNumber) {
$scope.firstNumber = C;
$scope.firstPercent = $scope.firstPercent - 5;
}
};
I can't see anything wrong with my maths, my thinking is that perhaps I'm approaching angular in the wrong way. However I'm not sure.
I have put together a fiddle that shows the full code.
jsFiddle
I have updated the fiddle to use parseFloat. Seems like the numbers are incrementing now.
var A = parseFloat(id);
http://jsfiddle.net/kjDx7/1/
The reason why it was working with values above 20 was that it was just reading the part before decimals each time it tried to increase. So 20 became 21 and 22.05 and so on. As long the the value before decimal kept changing, it showed different (but incorrect) answers.
On the other hand, 10 became 10.5 which when parsed yielded 10. As you can see, this cycle continued endlessly.
The reason why you face the issue is because 5% of anything less than or equal to 20 is less than or equal to 1.
When you parseInt() the value, you always end up with the same number again.
Take 15 for example.
5% of 15 = 15.75
After parseInt(), you get the value 15 again.
You use the same value to increment / decrement each time.
Hence for values below 20, you don't get any changes.
As #Akash suggests, use parseFloat() instead - or why even do that when the value that you get is float anyway
I made a fork of your fiddle. I'm not completely sure what you want to achive.
Take a look at this fiddle.
$scope.increase = function() {
$scope.firstPercent = $scope.firstPercent + 5;
var A = $scope.firstNumber;
var B = (A / 100) * $scope.firstPercent;
var C = A + B;
$scope.firstNumberWithPercent = C;
};
update
After posting, i see that question is already answered. But is this what you really want? When you hit increase, it takes 5 % off of the number in the input field. That is ok, but when you hit decrease after that, it takes 5 % off the number in the same field. So your starting point is different.
100 + 5/100 = 105
105 - 5/105 = 99,75

Using a for loop and document.getElementById to populate an array in Javascript

I have been trying to populate an array using a for loop and taking such values using document.getElementById("spin " + i).value;
The ids on my html for every input tag go from spin1 to spin18.
Any suggestions on what I am doing wrong? Or what I can change?
var nums = [];
for(var i = 1; i <= 18; i++){
var num[i] = parseInt(document.getElementById("spin" + i).value);
nums.push(num[i]);
}
alert(nums.length);
What is the problem? You never mention what kind of results being generated or what the front-end html code looks like.
The js looks compilable, but here are some pointers.
The number 0 is before 1
It's a good habit to get in this mind set, plus it might save you from making stupid mistakes later on. Anyway, just to reinforce this, below is a number chart.
0 10
1 11
2 12
3 13
4 14
5 15
6 16
7 17
8 18
9 19
Avoid unnecessary variables
Having a js compiler that optimizes redundant code is sadly new feature. But still, why have two lines to maintain when you can have one.
var nums = [];
for( var i = 0; i < 18; i++ ) {
nums[i] = parseInt( document.getElementById("spin" + i).value );
}
Don't push, insert
The push method has an expensive overhead so use it with caution.
Loggers
The console has a built in logger, why not use that instead of an alert box?
console.log( nums.length );
try this
var nums = [];
for(var i = 1; i <= 18; i++){
var num= parseInt(document.getElementById("spin" + i).value);
nums.push(num);
}
alert(nums.length);
A couple of things to note:
As PSR has mentioned, you use:
var num[i]
when it should be
var num
getElementById(id).value only works for form elements, you have to use .innerHTML for divs.
This works for me: http://jsfiddle.net/sbqeT/

Categories

Resources