Increment value each time when you run function - javascript

So I need a function which increments the value of a variable say n=0. When ever the function runs, the value of this varible must be incremented and it should not be equal to 0 again. For example consider the following code :
function increment(){
var n = 0;
n++;
return n;
}
Now everytime you run this function you get a value of 1. But my requirement is if you run this function for the 1st time, it should be 1, if you run it for the second time, it should be 2 and so on. Unless you refresh the html page and run the function again, it should not be equal to 0. Can anybody help me?
I'm new to coding and any small help is appreciated. Thanks in advance!!!

Create a closure to hold the value
Closures are functions that refer to independent (free) variables.
In short, variables from the parent function of the closure remain bound from the parent's scope.
var increment = (function(n) {
return function() {
n += 1;
return n;
}
}(0)); // -1 if you want the first increment to return 0
console.log(increment());
console.log(increment());
console.log(increment());

You need to declare n outside of the function.
var n = 0;
function increment(){
n++;
return n;
}
The problem is scopes. when you declare a variable inside of a function it is bound to the local scope of the function. as soon as the function is done the variable is gone.
declaring the variable in the root level of the script places it in the global scope.
another way to do this would be to have a variable outside that you're passing around and then you pass it to the function via a parameter.
var i = 0;
function increment(n){
n++;
return n;
}
i=increment(i);
for more information on scopes and variables, review this page: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Values,_variables,_and_literals#Variable_scope

You can bind the data to the function (since functions are objects).
function increment(){
increment.n = increment.n || 0;
return ++increment.n;
}

What about making the number of times increment was called a parameter ?
function increment(numberOfIncrementCalls){
numberOfIncrementCalls++;
return numberOfIncrementCalls;
}
function increment(numberOfIncrementCalls){
numberOfIncrementCalls++;
return numberOfIncrementCalls;
}
n = document.getElementById("demo");
o = document.getElementById("event");
numOfIncr = 0;
o.addEventListener("click",function(){
numOfIncr = increment(numOfIncr);
var insert = numOfIncr.toString();
n.innerHTML = insert;
});
<html>
<p id="demo"></p>
<button id="event">Click me</button>
</html>

var n = 0;
function increment(){
n++;
return n;
}

Learning about scopes will help you greatly. What you want here is the variable 'n' to be of a global scope.
var n = 0; //Declare n outside of the function makes it accessible to the function
//and to any other functions or expressions that want access to n
function inc() {
n++;
}

You can try this code and store the value in localstorage. All time it will be increase old Value untill you have not clear localstorage...
<script>
localStorage.setItem("n", 0);
increment();
function increment(){
let n;
n = localStorage.getItem('n');
n++;
localStorage.setItem("n", n);
return n;
}
</script>

Every time you call a function the value will be incremented by +1 by this method --
let x = 0;
function increment (){
return x = x + 1;
}

This code will always return 501
a=500;
function increment(n){
return n+1
}
increment(a);
You could equate a to the function
a=increment(a);
That would set a to 501, then 502 etc
However consider using an array for the argument instead
a=[500];
function increment(n){
n[0]++;
}
increment(a);
Now it will increment the value of a[0] even though it doesn't have a return statement. The benefit of this is it means we can have multiple arguments and increment them all, and then return some other variable if you like. Like this
a=[0];
b=[5];
function incrementToTen(n,o)
{
n[0]++;
o[0]++;
if(n[0]>=10||o[0]>=10)
{
return true;
}
else
{
return false;
}
}
So after running incrementToTen(a,b) 5 times it will return true

Related

Need some clarification on a JavaScript lesson. (Constructor Functions)

I have the following code I need some clarification with. I want to understand it perfectly before I move on. I know the example might be silly and I am sure there is a lot of better ways to solve the problem but for the sake of this lesson the person used this example.
All I need is some clarification on how exactly the flow of the score function works and onwards. Where are the values coming from? How is it adding up each time the person gives the right answer?
I basically want to understand how this code generates the number to display to the console every time the user inputs a true value into the alert. I am sorry if I'm not coming through clearly, I just need to understand how the code works from function score() and onwards. I could not for the life of me figure it out. Where is sc getting its values from, and where does it pass it too and; and; and.
Is there anyone that's willing to give me a layout of how this code fits together. I would be eternally grateful.
(function() {
function Question(question, answers, correct) {
this.question = question;
this.answers = answers;
this.correct = correct;
}
Question.prototype.displayQuestion = function() {
console.log(this.question);
for (var i = 0; i < this.answers.length; i++) {
console.log(i + ': ' + this.answers[i]);
}
}
Question.prototype.checkAnswer = function(ans, callback) {
var sc;
if (ans === this.correct) {
console.log('Correct answer!');
sc = callback(true);
} else {
console.log('Wrong answer. Try again :)');
sc = callback(false);
}
this.displayScore(sc);
}
Question.prototype.displayScore = function(score) {
console.log('Your current score is: ' + score);
console.log('------------------------------');
}
var q1 = new Question('Is JavaScript the coolest programming language in the world?',
['Yes', 'No'],
0);
var q2 = new Question('What is the name of this course\'s teacher?',
['John', 'Micheal', 'Jonas'],
2);
var q3 = new Question('What does best describe coding?',
['Boring', 'Hard', 'Fun', 'Tediuos'],
2);
var questions = [q1, q2, q3];
function score() {
var sc = 0;
return function(correct) {
if (correct) {
sc++;
}
return sc;
}
}
var keepScore = score();
function nextQuestion() {
var n = Math.floor(Math.random() * questions.length);
questions[n].displayQuestion();
var answer = prompt('Please select the correct answer.');
if(answer !== 'exit') {
questions[n].checkAnswer(parseInt(answer), keepScore);
nextQuestion();
}
}
nextQuestion();
})();
sc gets its value due to closure. When ever the nested function which is returned by score() and the if statement if (correct) is true then score gets incremented. Consider a general snippet below.
function score(){
let sc = 0;
return function(correct){
if(correct){
sc++; //this is the same variable is upper scope.
console.log(sc)
}
return sc;
}
}
let temp = score();
temp(true);
temp(true);
So in the above snippet the outer function score is only called once and does two things:
initialize a variable sc which is 0
return function in which sc will refer to the sc variable created in upper scope.
The use this is just to prevent making of global variable
Consider another simple snippet.
let count = 0;
function counter(){
count++;
console.log(count)
}
counter();
counter();
counter();
In the above snippet the parent scope is global scope and child scope is scope of function. Now the variable count is present inside the the the counter()(even though its not declared inside counter()) due to closure.
Now in the first snippet the function score() is just like global scope(in second snippet),
In first snippet the returned function is return function(correct){...} is just like the nested counter() function in second snippet.
And sc variable is just like count variable.
Could you maybe just explain the prototype.checkAnswer a little bit more
This method takes two arguments. ans and callback.
Consider the line in function nextQuestion()
questions[n].checkAnswer(parseInt(answer), keepScore);
Now if you notice two parameters are passed to function. One is number of correct answer and other is a callback(a function which is passed to another function be be called later).
We are passing keepScore which I explained above is the function returned by score() i.e function(correct){...}. Now this function is called inside the prototype method. This callback returns the value of sc which is declared in its parent function score. And then its displayed using this.displayScore
Now the thing you maybe confused with is the variable sc in the prototype.checkAnswer. That variable is just to prevent the double writing of this.displayScore();
The function can be written as:
Question.prototype.checkAnswer = function(ans, callback) {
if (ans === this.correct) {
console.log('Correct answer!');
this.displayScore(callback(true));
} else {
console.log('Wrong answer. Try again :)');
this.displayScore(callback(false));
}
}
Even if we declare the other variable sc in prototype.checkAnswer it has not relation with the variable sc inside score(). They are completely different variables because the variables declared with var have function scope.
Conisder the snippet:
function score(){
var sc = 0;
return function(){
sc++;
console.log(`I am sc of score: ${sc}`);
return sc;
}
}
let temp = score();
function wrapper(callback){
var sc = 0;
console.log(`I am sc of wrapper: ${sc}`);
callback();
}
wrapper(temp)
wrapper(temp)
wrapper(temp)
wrapper(temp)
It's self-executing wrapper function. It automatically calls nextQuestion() to begin process
var n = Math.floor(Math.random() * questions.length); selects random question from your questions list
displayQuestion() shows information from second new Question() parameter as possible answers. Third parameter is correct answer.
User inputs it's answer in prompt('Please select the correct answer.'); and if it's not exit, then comparing answer with correct value.
After showing answer code calls keepScore(correct) to add score to final result.
[GOTO #2] using nextQuestion();
Here the score function is a Closure
The state of sc inside score is intialised when score is invoked.
var keepScore = score();
Now the keepScore contains the function which is returned by the closure
that is
function (correct) {
if (correct) {
sc++; // it has a "closure" over it
}
return sc;
}
which accepts a boolean value. that is,
keepScore(true) or keepScore(false)
Now this keepScore function is passed to check answer
questions[n].checkAnswer(parseInt(answer), keepScore);
In check anwer, if the answer is correct it will pass true to the keepScore
callback(true) <=> keepScore(true)
If you want to have more clarity on Closure you can go through this article
https://github.com/getify/You-Dont-Know-JS/blob/master/up%20%26%20going/ch2.md#closure
The slightly tricky bit for the uninitiated here is that the score function returns a function and makes use of a closure.
function score() {
var sc = 0;
return function(correct) {
if (correct) {
sc++;
}
return sc;
}
}
This line:
var sc = 0;
creates a variable for holding the current score and then returns a function you can call to increment that variable. The variable can't be declared inside the function because it would get recreated every time the function was called:
// can't do this. sc gets recreated and reset on every call:
function score (correct) {
var sc = 0;
if (correct) {
sc++
}
return sc;
}
But you also don't want the variable available to everyone, so you don't want to do this either:
// don't want this either.
// score shouldn't be modifiable outside of our keepScore method.
let sc = 0;
function score (correct) {
if (correct) {
sc++;
}
return sc;
}
// this approach works, but now cheaters can set
// the score outside our scorekeeping function:
sc = 999999; // oh noes! hacks!
So what can we do? We can:
First: Create the variable within a function scope, where it's protected from outside shenanigans:
function score () {
var sc = 0; // unavailable outside this function
}
Second: Create another function inside the first that can modify the variable:
function score () {
var sc = 0; // unavailable outside this function
// a new function that has access to the outer function's sc variable.
function(correct) {
if (correct) {
sc++;
}
return sc;
}
}
Finally, returning the inner function from score() gives outsiders a way to register correct answers without exposing the score variable itself:
function score () {
var sc = 0; // unavailable outside this function
// return this function to the caller and voila!
// they now have a self-contained scorekeeper function.
return function(correct) {
if (correct) {
sc++;
}
return sc;
}
}
So now when you do this:
var keepScore = score();
keepScore is that inner function with its own internal sc variable.
If you had a multiplayer edition, you could get one for each player:
// each gets their own instance of
// that inner function with its own
// independent sc variable.
const playerOneScore = score();
const playerTwoScore = score();
playerOneScore(true); // 1
playerOneScore(true); // 2
playerTwoScore(false); // 0
playerTwoScore(true); // 1
I think once you understand this bit, the rest will make a lot more sense.

Is function scope variable not writable

function add() {
var counter = 0;
counter += 1;
return counter
}
Why the counter variable dont get incremented after first iteration? output is always 1.
The addfunction is returning the variable counter which is defined inside the function add. The scope of variable counter is local to function, which means each time you invoke the function, it creates a new variable counter and then initialize to zero and then increment the counter.
If you are looking for a counter implementation, then you need to reference the same counter variable every time and increment that variable. This can be implemented by using closure.
Example: In the below example, there are 2 functions, 1 nested inside the another one. The inner function maintains a reference to the outer function Environment, which in this case contains the counter variable. So, even after the control moves out of the function add, the inner functions maintains a reference to counter variable.
var add = (function(){
var counter = 0;
return function(){
return ++counter;
}
})();
document
.querySelector('#btn')
.addEventListener('click', function(){
document.querySelector('#output').textContent = add();
});
<div id="output">0</div>
<button id="btn">Increment</button>
This is a scoping issue. Change it to
let counter = 0;
function add() {
counter += 1;
return counter
}
Or if you want to be able to do add(), use a nested function
function adder() {
let counter = 0;
return function plus() {
return counter += 1;
};
}
let add = adder();
console.log(add());
console.log(add());
console.log(add());
You can make the counter a global variable and then call the add function:
function add(){
counter = counter + 1;
}

javascript calling a inner function from outside

This is regarding javascript closures working.
I have a function inside another and I want to access this outside of the outer function.
is it possible since it written here that u can achieve closure with this
http://www.w3schools.com/js/js_function_closures.asp
JavaScript Nested Functions
All functions have access to the global scope.
In fact, in JavaScript, all functions have access to the scope "above" them.
JavaScript supports nested functions. Nested functions have access to the scope "above" them.
In this example, the inner function plus() has access to the counter variable in the parent function:
Example
function add() {
var counter = 0;`enter code here`
function plus() {counter += 1;}
plus();
return counter;
}
I am trying to acess plus() from outside
Agree with Grim.
But if you wanna access to plus function outside, you can try this way:
function add(){
var counter = {
value: 0,
plus: function(){
return ++this.value;
}
};
counter.plus();
return counter;
}
Hope it helps.
You cannot. An inner function is only available within the body of the outer function.
I assume your target is to keep value as private property inside add and provide manipulations to it via add.plus() calls:
//define your object with a private "value" and a public modifier "plus"
var add = (function() {
var counter = 0;
var that = {
plus: function() {
return counter++; //equal to your code
}
}
//your integrated first call
that.plus();
return that;
})();
//make a call
add.plus();
DEMO - Working code example.
This may be what you are looking for, especially as related to the tutorial link you provided. It is a step in the right direction.
var plus;
add();
plus();
plus();
plus();
alert(plus());
function add() {
var counter = 0;
plus = (function(counter) {
return function() {counter += 1;return counter;};
})(counter);
plus();
}
It is a straight forward example of closure. I made plus a global variable, but alternatively add() could return the function definition of plus. I took the return value away from add() and moved it to plus(), as with this code counter will always equal 1 when add() is finished.
However, and directly from the tutorial you mentioned, the best way to achieve what they are attempting is with this code, ripped directly from their web page.
var add = (function () {
var counter = 0;
return function () {return counter += 1;}
})();
add();
add();
add(); // the counter is now 3

Set value of counter function

The following code will allow the counter function to be incremented by one every time counter(); is called.
function One() {
var counter = function(initial) {
var c = initial || 0;
return function() {
return c++;
};
}(0);
Too(counter);
}
function Too(counterArg) {
counter();
}
Is there any thing I can replace counter(); with so the counter will decrement? Or even better is there any way for me to set the value of the counter? Like counter = 0 or counter = 20? Also I need to stay away from global variables.
you can assign function as a variable in javascript so now you can do this...
var counter = 0;
var step = 1; // or 20 or whatever
var method = null;
function increment () {
counter += step;
}
function decrement () {
counter -= step;
}
method = icrement;
method();
First, you have a minor typo in your code; presumably you mean
function Too(counterArg) {
counterArg(); // this was just `counter` originally; that will be undefined
}
Second, c++ is a little bit of a weird way to do a counter, since it return c and then increment c, so the counter will start at 0 which is probably not what you want.
(I admit I chuckle a little bit whenever I see c++ in code though. :P )
Okay, on to the main question: I'd do it by adding a method to the counter function called e.g. set.
function One() {
var counter = function createCounter(initial) {
var c = initial || 0;
function counter() {
return ++c;
}
counter.set = function(n) {
c = n;
};
return counter;
}(0);
Too(counter);
}
function Too(counterArg) {
counter(); // 1
counter.set(20); // `c` is now 20
counter(); // 21
counter(); // 22
}
This works because the counter function creates what's called a closure. This is a fairly common concept in JavaScript and there are plenty of good questions and answers about closures on SO that you should look at if you don't know the concept. Basically, even after your anonymous function (which I renamed createCounter) returns, the variable c still exists and can be accessed from any code in createCounter. That's how the counter function works. c cannot, however, be accessed by any code outside createCounter, so if you want to do anything with it, you have to put that code in createCounter. That's what the counter.set method I added does. Since it's within createCounter, it is free to modify c.

Javascript for loop, index variable in function

I'm trying to figure out how to generate functions inside for loop.
I have:
for (var i = fir_0_f.length - 1; i >= 0; i--){
var next = i+1;
var N = i;
// Attemps
//goal0_[i](next,N);
//eval('goal0_'+i+'('+next+', '+N+')');
};
Have done also some searching. [] expects a string, eval() is a B.A.D practice. Is there any other way?
How to set the timeout for each function later? So they would run sequentally?
Thanks a lot!
In JavaScript you could use function expressions to build an array of functions:
var goals = [];
goals.push((function (param1, param2) {
// your code for the first function
}));
goals.push((function (param1, param2) {
// your code for the second function
}));
// ... etc
Then in your for loop, you can simply reference your functions as elements of an array:
goals[i](next, N);
UPDATE:
To call your functions with a delay between each other, you'd have to change your loop logic. Instead of using a for loop, call the first function immediately, and then after it runs, make it call the second one using a setTimeout().
for (var i = fir_0_f.length - 1; i >= 0; i--){
var next = i+1;
var N = i;
setTimeout('goal0_'+i+'('+next+','+N+')', 0);
}
Note: errors thrown by goal0_i won't be caught by the loop.
I've noticed this behavior in Firefox.
That means that the following won't work as you expected:
try{
setTimeout(function_throwing_error, 0);
}
catch(e){
alert("I kill you!");
}
For global functions, you can just do:
window['goal0_'+i](next, N);

Categories