Javascript function as argument not taking effect - javascript

I have this code:
var point = 2;
var change = function(){point = 5};
function makeChange(point,change){
change();
alert(point);
}
makeChange(point,change);
The idea is to give the user the ability to pass a condition for the value of point before using it in the function.
But it doesn't take effect.
When I add alert(point) into the change function it alerts 5 but then alerts 2 in the makeChange function.

you can return point in change()
var point = 2;
var change = function(){ return point=5; };
function makeChange(point,change){
alert(change);
}
makeChange(point,change());

The problem is because of your parameter having the same name as the global variable point. In the code below:
var point = 2;
var change = function(){point = 5};
function makeChange(point,change){
change();
alert(point);
}
The call to change() inside makeChange will assign the local parameter point defined here makeChange(point,change) to 5. Not the global point which will remain as 2.
A easy way to solve this is to not use the same name point in the paramater as the global variable. Otherwise due to scoping JavaScript will think you are taking about the locally defined point inside makeChange:
var point = 2;
var change = function(){point = 5};
function makeChange(Point,Change){
Change();
}
makeChange(point,change);
alert(point);

You can do something like this when you call function.
makeChange(point,function(){return change})

Your code is doing fine - in fact, if you do a alert(point); right after makeChange(point,change); you'll see that 5 is returned.
The confusing bit is that the number (namely, 2) is passed into the makeChange function by value instead of the reference (namely, point). Therefore, if you alert point inside makeChange, the originally passed value will be given: 2.

I think the problem with this code is confusion between local and global variable.
So when you are passing variable in function makeChange(point,change) its behaving like local variable for function makeChange now in the next line when you calling the change function its changing global point value.
and then when you are doing alert since in function priority is local variable so you are getting 2.
You can use return approach for same.
var point = 2;
var change = function(){point = 5 return(point)};
function makeChange(point,change){
point=change();
alert(point);
}
makeChange(point,change);

Related

Global scope, variable outside function Javascript

I have declared var example at the beginning (it should be in global scope, or?!).
Why it is undefined after calling the function?
var example;
function test(){
var x = 2;
var y = 5;
var example = x + y;
console.log(example); // 7: works OK after calling the function
};
test();
console.log(example); // undefined ?!
Edit:
Hello, Thanks for your answers, I´ve found an article about this - Variable Shadowing
The reason is you have initialized the variable twice. First Initialization outside the function block which is globally available, Second within the function block which is specifically available to the function block.
Your Second Initialization will override the first within the function. After execution of the function, the second example variable will no longer be available and it will be referencing the globally declared first example variable.
var example;
function test(){
var x = 2;
var y = 5;
example = x + y;
console.log(example); //Prints the value
};
test();
console.log(example); // Prints the value
the first console.log(example) is running the example inside the function block, so it will print the value of the command you gave.
the second console.log(example) is running the example you declare in first line which is doesn't has value, so it will print undefined.

How assignment works in JavaScript?

I was asked what happens when we assign a value to a variable?
Meaning, let's say we have a variable data and we assign some value to it,
var data = 5
What actually happens in the background? What is the initial value of data and what happens, how value is assigned?
I tried to google articles for it, but I couldn't find anything related to working, may be I was not using correct keywords. If anyone have any article that I could follow or provide me some explanation that would be really great.
Because you are using var, the variable named data is first created by the interpreter at the start of the containing function block and its initial value at that point is undefined. This concept of moving the declaration to the start of the function block is called variable hoisting. This data variable will be a piece of memory internal to the interpreter. It will probably be allocated within a stack frame object.
A reference on hoisting:
Hoisting on MDN
Basics of hoisting in Javascript
Note also that functions declared like this:
function x() {
// code here
}
Are also hoisted so two functions in the same scope can call each other without worrying about declaration order.
When the interpreter gets to the point of executing the code where the declaration/assignment line is located, it will assign the value of 4 to the variable.
So, if your code was like this:
function myFunction() {
var sum = 3 * 4;
console.log(sum * 3);
var data = 5;
console.log(sum * data);
}
myFunction();
Then, what the interpreter actually does internally is this:
function myFunction() {
var sum = undefined, data = undefined;
sum = 3 * 4;
console.log(sum * 3);
data = 5;
console.log(sum * data);
}
myFunction();
In fact, you can even write this (somewhat ugly) code:
function myFunction() {
var sum = 3 * 4;
data = 6; // this will not be an error
console.log(data);
console.log(sum * 3);
var data = 5; // the declaration of data is hoisted
console.log(sum * data);
}
myFunction();
because, this is how the interpreter handles that:
function myFunction() {
var sum = undefined, data = undefined;
sum = 3 * 4;
data = 6; // this will not be an error
console.log(data);
console.log(sum * 3);
data = 5;
console.log(sum * data);
}
myFunction();
Note that let and const are block-scoped, not function-scoped and, if you try to reference them before their declaration, it is an error whereas var lets you do that. var is somewhat legacy and there is rarely (if ever) a reason to use var any more. It is safer to code with let and const instead. If you want function scope, you can still put your let or const at the top level of your function. But, you should generally declare your variables within the block that they are used/needed (restrict the scope to only what is needed).
The cpu will try to find a location in memory to hold the value of 5 and store the value in that address and store the address in the variable declared by var.

d3 svg symbol syntax [duplicate]

I noticed a difference when calling a function with empty parentheses, or without any parentheses at all. However, I am not passing any arguments to the function so I wondered, what would be the difference between:
window.onload = initAll();
and
window.onload = initAll;
Please explain the principle behind it.
window.onload = initAll();
This executes initAll() straight away and assigns the function's return value to window.onload. This is usually not what you want. initAll() would have to return a function for this to make sense.
window.onload = initAll;
this assigns the actual function to window.onload - this is possible because in JavaScript, as #Felix says, functions are first class objects - without executing it. initAll will be executed by the load event.
You may also see something like this:
window.onload = () => initAll();
This will create a new function that, when called, will call initAll immediately. Parentheses are necessary here for that "call initAll immediately" part to work. But, because it's wrapped in a function, nothing will execute until that outer function itself is called, and you assign the reference of that outer function to window.onload, so initAll will also be executed on the load event.
What Pekka says is correct, but I want to elaborate a little with an example that will help explain to someone who doesn't fully understand function pointers or delegates.
I won't use window.onload because that's a bit contrived to demonstrate. I'll use a simple multiply function to demo instead:
function Multiply(operator, operand) {
return operator * operand;
}
This could equally be written:
Multiply = function(operator, operand) {
return operator * operand;
}
While in the first example, the implication may not be obvious, the second example shows more clearly that we're assigning a function which has 2 parameters to a variable called Multiply, and this concept of functions as assignments is common throughout JavaScript. This is a small demonstration of the fact that functions are "first class citizens", that is, they can be passed around exactly as if we were passing around values.
So now to the difference of assignment:
var operator = 3;
var operand = 4;
var ret = Multiply(operator, operand);
At the point of defining the ret variable, Multiply is executed and the return value is assigned - ret becomes equal to 12.
Let's try that again a different way:
var operator = 3;
var operand = 4;
var ret = Multiply;
Now, at the point of defining ret, ret becomes your Multiply function as opposed to being the result obtained from your Multiply function. Calls to ret() will cause your Multiply function to be executed, and you can call it exactly as if you'd called Multiply(operator, operand):
var out = ret(3, 4);
is the same as
var out = Multiply(3, 4);
You have effectively said that you are going to use ret as a delegate for Multiply(). When calling ret, we're really referring to the Multiply function.
Back to your window.onload. Think of this as:
window.onload = function() {
//Doing what all good window.onload functions should do...
}
initAll = function() {
return 12;
}
So as you can see, window.onload is a function just like any other function, there's nothing special about it. You can assign it a value, assign it a function, null it out if you wish - the point is that there's nothing any more special about window.onload than there is about your own function. The only slightly different thing is that it gets called by the window when it's loaded. [Disclaimer: I've never actually nulled out window functions, so I'm not sure if this will cause negative repercussions. One would hope they check to see if a function is assigned before calling it i.e. if (window.onload) window.onload();].
Now calling initAll() what we're saying is:
window.onload = initAll();
which might as well say:
window.onload = 12;
But when we say initAll without the parentheses, what we're really saying is: I want to replace whatever my window.onload function is, with a new function - i.e. I want to replace it with my initAll function, so that any calls to window.onload runs my initAll code.
So:
window.onload = function() {
//Doing what all good window.onload functions should do...
}
is replaced with:
window.onload = function() {
return 12;
}
So any call to window.onload will execute your initAll function instead of whatever window.onload was originally. You have replaced the original function with your new function.
In fact, you could equally write:
window.onload = function() {
//Write all your init code right in here instead of having a separate
//initAll function.
}
Another example that may demonstrate better is this:
var d = new Date();
var currentTime = d.getTime();
Whatever the time was at the time d is defined ends up assigned to currentTime. Great, but that's only useful if we want to find out what time the function containing that code was called - i.e. at page load time. What if we want the current time any time that currentTime is called?
var currentTime = function() {
var d = new Date();
return d.getTime();
}
var a = currentTime(); //The current time at the point a is defined...
var b = currentTime; //b is a functional reference to currentTime...
var c = b(); //The current time when variable c is defined
var d = c; //The current time when variable c was defined
Notice how we call b() in our c and d assignments exactly as we could call currentTime()?
Functions in javascript are first-class citizens, and as such, can be assigned to other variables or passed around as arguments.
So, when you do
window.onload = initAll;
You are setting the onload property of the window object to reference the initAll function itself.
When you do
window.onload = initAll();
You are setting the onload property to hold the return value of initAll, since it will execute in place on that line.
I'm 6 years late but I feel this could have been explained a lot simpler than the above answers.
So here is the TLDR; or bird's eye view when calling functions using and not using ()'s
Lets take this function for example:
function foo(){
return 123;
}
if you log "foo" - without ()
console.log(foo);
---outout------
function foo(){
return 123;
}
Using no () means to fetch the function itself. You would do this if you want it to be passed along as a callback.
if you log "foo()" - with ()
console.log(foo());
-----output-----
123
Using () after a function means to execute the function and return it's value.
initAll is a reference to a function value and the brackets operator appended to the function name RUNS this function object.
So if you do something like
a = initAll
then a will become the same as initAll - for example you can do a() - but with
a = initAll()
the variable a will get the return value of the executed initAll function

Doing Math in Multiple Javascript Functions

I'm new to the Javascript world and trying to figure out this assignment my teacher assigned. Here is his description of what is expected:
Build a function that will start the program. Please call it start()
From the start() function, call a function called getValue()
The getValue() function will get a number from the user that will be squared.
Also from the start function, call a function called makeSquare()
The makeSquare() function will square the number that was received by the user in the getValue() function.
Make sure that you display the results of squaring the number inside of the makeSquare() function.
Here is what I have so far:
function start() {
getValue();
getSquare();
}
function getValue() {
var a = prompt("Number please")
}
function getSquare() {
var b = Math.pow(a)
document.write(b)
}
start()
This assignment doesn't have to be working with any HTML tags. I've only got the prompt box to work, nothing else does though. Am I using variables in a way that can't be used?
You were close. But it seems that you don't understand scoping and how exactly to use the pow function.
Math.pow:
Math.pow takes two parameters, the base and the exponent. In your example, you only provide the base. That will cause problems as the function will return the value undefined and set it to b. This is how it should have looked (if you wanted to square it):
Math.pow(a, 2);
Scoping:
Every function has it's own scope. You can access other variables and functions created outside the function from within the function. But you cannot access functions and variables created inside another function. Take the following example:
var c = 5;
function foo() { // we have our own scope
var a = c; // Okay
}
var b = a; // NOT okay. a is gone after the function exits.
We could say that a function is private. The only exception is that we can return a value from a function. We return values using the return keyword. The expression next to it is the return-value of the function:
function foo() {
return 5;
}
var a = foo(); // a === 5
foo() not only calls the function, but returns its return-value. A function with no return-value specified has a return value of undefined. Anyway, in your example you do this:
function getValue() {
var a = prompt("Number please")
}
and access it like this:
// ...
var b = Math.pow(a)
Do you see the error now? a is defined in the function, so it can't be accessed outside of it.
This should be the revised code (Note: always use semicolons. I included them in for you where necessary):
function start() {
getSquare();
}
function getValue() {
var a = prompt("Number please");
return a;
}
function getSquare() {
var b = Math.pow(getValue(), 2); // getValue() -> a -> prompt(...)
document.write(b);
}
start();
As this is an homerwork, I won't give you direct answer, but here's some clue.
In javascript variables are functions scoped. That mean that var a inside getValue is only available in there.
You can return a value from a function.
Functions are first class object in javascript, so you can pass them as parameter to other function and finally call them inside that function.
Am I using variables in a way that can't be used?
Yes, that's where your problem lies. Variables in most programming languages have a scope that determines where they're available. In your case, a and b are local variables of the functions getValue() and makeSquare() respectively. This means they're not available outside the function they're declared in.
Generally speaking, this is a good thing. You should use restricted scopes for your variables to make the "flow" of data through your program clearer. Use return values and parameters to pass data between functions instead of making your variables global:
function start() {
var a = getValue();
makeSquare(a);
}
// Return a value entered by the user
function getValue() {
return prompt("Number please")
}
// Write the square of the `a` parameter into the document
function makeSquare(a) {
var b = Math.pow(a)
document.write(b)
}
Your getValue() needs to return the value, so that you then can pass it to the getSquare() function.
In my opinion, you should always end each line with ;
You will probably need to parse the user input into a number. For that you can use parseFloat(string).
Math.pow takes two arguments, so to get the square, you would have to pass 2 as a second argument when calling it.
I edited your code with some clarifying comments:
function start() {
// Catch the value returned by the function
var value = getValue();
// Pass the returned value to the square-function
getSquare(value);
}
function getValue() {
// Parse the user input into a number, and return it
return parseFloat(prompt("Number please"));
}
// Let the square-function take the user input as an argument
function getSquare(a) {
// Math.pow takes a second argument, which is a number that specifies a power
var b = Math.pow(a, 2);
document.write(b);
}
start();
Another, less good way
In JavaScript, variable-scoping is based on functions. If a variable is declared using the var keyword, it is only available to that function, and its child-functions. If it is declared without the var keyword, or declared outside any function, it becomes a global variable, which will be accessible by any code run on that page.
That said, you could get rid of the var keyword inside the getValue() function, which would make the variable a global. You could then access it from within getSquare() the way you tried in your example.
This is generally not a good idea though, since you would "pollute" the global namespace, and you would be running the risk that you accidentally have another script using a global variable with the same name, which would cause all kinds of trouble, when the scripts start to work with the same variable.
You can try this.
<script type="type/javascript">
function start(){
makeSquare(getvalue());
}
function getvalue(){
return prompt("enter a number");
}
function makeSquare(a){
var result=Math.pow(a,2);
alert(result);
}
start();
</script>

Pass name of global var to function that alters var?

I encountered a strange problem today.
The good: I successfully changed a global var value from within a function(in other words the below example works fine when "passedVarName" is substituted with "a").
The bad: When trying to pass the global var name "a" (rather than putting it directly in the function) it fails to work.
Below is what I can't seem to get working:
(on click document should write "2" but instead writes "NaN" ?)
Javascript:
var a = 1;
function click(passedVarName){
passedVarName ++;
document.write(passedVarName)
};
HTML:
Click this Button to alter global var "a".
This is a pretty bad Code Smell, but if you know it's global, then this'll work:
var a = 1;
function click(passedVarName){
window[passedVarName]++;
document.write(passedVarName)
};
Click this Button to alter global var "a".
This passes string 'a' to your function, not the variable a.
You need to pass it as click(a);
Corrected example :
http://html-bin.appspot.com/aghodG1sLWJpbnIMCxIEUGFnZRjhjxoM
[ Did not use jsfiddle.net to avoid confusion by seperating javascript and HTML ]
Passing a global variable as a param to a function creates a copy of that var inside the function. The global doesn't change.
This example will generate the same output everytime you click on the first div:
//html
<div onclick="foo(a)">Click here</div>
<div id="txt"></div>​​​​​​​​​​​​​
//js
window.a = 152;
window.foo = function(varr) {varr++; $("#txt").html(varr)}​
However, it seems like if you pass your variable as a property of an object, pass that object to the function, and inside your function modify the variable, it has global effect :
//html
<div onclick="foo(a)">Click here</div>
<div id="txt"></div>​​​​​​​​​​​​​​​​
//js
window.a = { val:152};
window.foo = function(varr) {varr.val++; $("#txt").html(varr.val)}​
Here is a jsFiddle that works: http://jsfiddle.net/2Ahdb/3/
Forgive me if I misinterpret your knowledge of programming, but a global variable is something that can be accessed and modified by any part of your programming, you do not need to pass it through a function to modify it.
IF you are trying to modify global variables through a function, javascript has some limitations. Only objects are passed by reference.
var a = 5;
var b = { value: 5 };
function changeMe(x) {
x = 10;
}
changeMe(a); //... still 5
function changeMeAlso(x) {
x.value = 10;
}
changeMeAlso(b); //.. changed to { value: 10 }

Categories