I'm starting learning javascript for a project, I've found a script that does a part of what I need to do, I'd like to know how it works, both for me and in case it needs to be modified.
Originally it was used inside the page, now I've put it in a file on its own and does not work anymore, so I'm dividing it in parts, because I fail to get the whole thing.
Here is what bother me most for now:
1) Is this a declaration of a function? What is its name? How can it be invoked?
(function() {
//some code
})();
2) No clue of what is going on here
var VARIABLE = VARIABLE || {};
3) Am I defining the implementation of methodCall here? Something like overriding a method in Java?
VARIABLE.methodCall = function(parameter) {
console.log("parameter was: " + parameter);
};
Thank you in advance for your help.
1) creates an unnamed function and executes it. this is useful for creating a scope for local variables that are invisible outside the function. You don't need to invoke it aside from this, the '()' at the end does that for you.
2) if variable is null/undefined, set it to an empty object.
3) yes, that should work as you expect, you can call VARIABLE.methodCall(parameter)
in response to your comment, here is a common example
function foo (VARIABLE) {
var VARIABLE = VARIABLE || {};
}
(function() {
//some code
})();
simply runs //some code, but variables in it will not remain, since the function() { } block introduces a new inner scope.
function() { } notation is called a closure, it allows variables be functions. For example,
(function() { })() is a common JavaScript idiom. After the ), there is (), which invokes the expression before as function, so (callback || function(x) { return x; })(x) is allowed.
var a = function a() { return 1; }
var VARIABLE = VARIABLE || {}; uses the short-circuit OR, If VARIABLE is not defined, VARIABLE will be set to {}, an empty object. (otherwise, if VARIABLE exists, it will not change)
x = A || B means "If A evaluates to TRUE, x is A, otherwise, x is B.".
VARIABLE.methodCall, as you said, adds methodCall to VARIABLE, without erasing other values in VARIABLE
Related
No matter whether I define the function after the variable
var a = 1;
function a() {};
typeof a // number
Or if I define the function before the variable
function a() {};
var a = 1;
typeof a // number
the final typeof result is always number
I found some explanation about execution context in http://davidshariff.com/blog/what-is-the-execution-context-in-javascript/
Before executing the function code, create the execution context.
......
Scan the context for variable declarations:
If the variable name already exists in the variable object, do nothing and continue scanning.
but this does not seem to work.
So how can I explain it?
It's to do with JavaScript's variable hoisting. Try this instead:
var a = 1;
var a = function() {};
typeof a // function
You're implicitly declaring the variable multiple times by using the function statement 'function a() {};', which as noted by others hoists the variable and behaves unexpectedly due to the order that the browser registers the declarations.
Behind the scenes, this statement instantiates a function object and assigns the result to the variable passed as the function name (reference) but this is done before the explicit var declarations are performed, and so that overrides the implicit declaration. If you just do the following, it will work more intuitively:
var a = 1;
a = function(){};
console.log(typeof a); // function
This is a better option than the multiple var declaration in the other answer from a logical standpoint because (even though you can), it's not a good practice to declare the variable multiple times anyway.
To specifically answer the 'why' for this question: it's so that you can use these kinds of statements to define functions and use them in your explicit declarations, as in
var a = someFunction();
function someFunction(){ return 'someVal'; }
If the function statements weren't parsed and hoisted first, this wouldn't be possible.
As already mentioned, it has to do with the way JavaScript hoisting works. The main issue to notice is that JavaScript will hoist the complete function definition (along with the function body) up to the top, but keeps the variable initialization where it is (only the declaration is hoisted).
So if you write this:
var a = 1;
function a () {
}
it will be translated to:
var a;
function a() {
}
a = 1;
and if you write this:
function a () {
}
var a = 1;
it will be translated to:
function a () {
}
var a;
a = 1;
So no matter what you do, a = 1; will remain at the very bottom.
Please note that the above "translations" should be seen theoretically. JavaScript probably has a way to omit the var a; statement if there is already a function declaration with the same name. And there also might be a defined order (functions get hoisted before variables or the other way around). But all of this doesn't affect the outcome of the variable initialization being the only part that is NOT hoisted at all.
The code:
(function() {
'use strict'; // es6 is on
var a = {
b: 3
};
(function() {
var a = a.b + 4;
console.log(a);
/** many lines where a is used */
})()
})()
I am expecting to get 7 in console, but I got an exception. I can understand why this happaned, and work-around will be tupically rename internal variable. But I'd like to avoid this, so is there another way to force this working without renaming variables? I am working in es6-compatible env, so might be in es6 there is something for such cases?
var a reserves the local variable name even before any of the function body is executed; it shadows it immediately, not only upon assignment. Imagine it executing like this:
var a = undefined;
a = a.b + 4;
As such, there's no way to get the parent scope's value of a without renaming the inner variable.
To work around this, you can pass the value into your IIFE:
var a = { b: 3 };
(function (_a) {
var a = _a.b + 4;
console.log(a);
})(a)
Or even use the fact that a function parameter already declares a new local variable name:
(function (a) {
a = a.b + 4;
console.log(a);
})(a)
First proposed varian not working for me as far as I have event-listeners there, not a IIFE, so I cannot pass any params, as far as closure parameters controlled by event emmiter.
But the implementation suggested me another solution, whitch is fit perfect:
(function(){
'use strict'; // es6 is on
var a = {b:3};
function getA(){
return a;
}
(function(){
var a = getA().b+4;
console.log(a);
/** many lines where a is used */
})()
})()
u override 'a' by defining ( local version "var a")... just say a = a.b+4; since you did define it, it wont become new global variable and will use the other...
also you are overriding object a with primitive 7 value, so in this self called method it's nothing, but in another place where you want to call it again, there won't be any object, and theres only a primitive left to you
Today, I got completely surprised when I saw that a global variable has undefined value in a certain case.
Example:
var value = 10;
function test() {
//A
console.log(value);
var value = 20;
//B
console.log(value);
}
test();
Gives output as
undefined
20
Here, why is the JavaScript engine considering global value as undefined? I know that JavaScript is an interpreted language. How is it able to consider variables in the function?
Is that a pitfall from the JavaScript engine?
This phenomenon is known as: JavaScript Variable Hoisting.
At no point are you accessing the global variable in your function; you're only ever accessing the local value variable.
Your code is equivalent to the following:
var value = 10;
function test() {
var value;
console.log(value);
value = 20;
console.log(value);
}
test();
Still surprised you're getting undefined?
Explanation:
This is something that every JavaScript programmer bumps into sooner or later. Simply put, whatever variables you declare are always hoisted to the top of your local closure. So, even though you declared your variable after the first console.log call, it's still considered as if you had declared it before that.
However, only the declaration part is being hoisted; the assignment, on the other hand, is not.
So, when you first called console.log(value), you were referencing your locally declared variable, which has got nothing assigned to it yet; hence undefined.
Here's another example:
var test = 'start';
function end() {
test = 'end';
var test = 'local';
}
end();
alert(test);
What do you think this will alert? No, don't just read on, think about it. What's the value of test?
If you said anything other than start, you were wrong. The above code is equivalent to this:
var test = 'start';
function end() {
var test;
test = 'end';
test = 'local';
}
end();
alert(test);
so that the global variable is never affected.
As you can see, no matter where you put your variable declaration, it is always hoisted to the top of your local closure.
Side note:
This also applies to functions.
Consider this piece of code:
test("Won't work!");
test = function(text) { alert(text); }
which will give you a reference error:
Uncaught ReferenceError: test is not defined
This throws off a lot of developers, since this piece of code works fine:
test("Works!");
function test(text) { alert(text); }
The reason for this, as stated, is because the assignment part is not hoisted. So in the first example, when test("Won't work!") was run, the test variable has already been declared, but has yet to have the function assigned to it.
In the second example, we're not using variable assignment. Rather, we're using proper function declaration syntax, which does get the function completely hoisted.
Ben Cherry has written an excellent article on this, appropriately titled JavaScript Scoping and Hoisting.
Read it. It'll give you the whole picture in full detail.
I was somewhat disappointed that the problem here is explained, but no one proposed a solution. If you want to access a global variable in function scope without the function making an undefined local var first, reference the var as window.varName
Variables in JavaScript always have function-wide scope. Even if they were defined in the middle of the function, they are visible before. Similar phenomena may be observed with function hoisting.
That being said, the first console.log(value) sees the value variable (the inner one which shadows the outer value), but it has not yet been initialized. You can think of it as if all variable declarations were implicitly moved to the beginning of the function (not inner-most code block), while the definitions are left on the same place.
See also
Javascript function scoping and hoisting
Javascript variable declarations at the head of a function
There is a global variable value, but when control enters the test function, another value variable is declared, which shadows the global one. Since variable declarations (but not assignments) in JavaScript are hoisted to the top of scope in which they are declared:
//value == undefined (global)
var value = 10;
//value == 10 (global)
function test() {
//value == undefined (local)
var value = 20;
//value == 20 (local)
}
//value == 10 (global)
Note that the same is true of function declarations, which means you can call a function before it appears to be defined in your code:
test(); //Call the function before it appears in the source
function test() {
//Do stuff
}
It's also worth noting that when you combine the two into a function expression, the variable will be undefined until the assignment takes place, so you can't call the function until that happens:
var test = function() {
//Do stuff
};
test(); //Have to call the function after the assignment
The simplest way to keep access to outer variables (not just of global scope) is, of course, to try to not re-declare them under the same name in functions; just do not use var there. The use of proper descriptive naming rules is advised. With those, it will be hard to end up with variables named like value (this aspect is not necessarily related to the example in the question as this variable name might have been given for simplicity).
If the function might be reused elsewhere and hence there is no guarantee that the outer variable actually defined in that new context, Eval function can be used. It is slow in this operation so it is not recommended for performance-demanding functions:
if (typeof variable === "undefined")
{
eval("var variable = 'Some value';");
}
If the outer scope variable you want access to is defined in a named function, then it might be attached to the function itself in the first place and then accessed from anywhere in the code -- be it from deeply nested functions or event handlers outside of everything else. Notice that accessing properties is way slower and would require you to change the way you program, so it is not recommended unless it is really necessary: Variables as properties of functions (JSFiddle):
// (the wrapper-binder is only necessary for using variables-properties
// via "this"instead of the function's name)
var functionAsImplicitObjectBody = function()
{
function someNestedFunction()
{
var redefinableVariable = "redefinableVariable's value from someNestedFunction";
console.log('--> functionAsImplicitObjectBody.variableAsProperty: ', functionAsImplicitObjectBody.variableAsProperty);
console.log('--> redefinableVariable: ', redefinableVariable);
}
var redefinableVariable = "redefinableVariable's value from someFunctionBody";
console.log('this.variableAsProperty: ', this.variableAsProperty);
console.log('functionAsImplicitObjectBody.variableAsProperty: ', functionAsImplicitObjectBody.variableAsProperty);
console.log('redefinableVariable: ', redefinableVariable);
someNestedFunction();
},
functionAsImplicitObject = functionAsImplicitObjectBody.bind(functionAsImplicitObjectBody);
functionAsImplicitObjectBody.variableAsProperty = "variableAsProperty's value, set at time stamp: " + (new Date()).getTime();
functionAsImplicitObject();
// (spread-like operator "..." provides passing of any number of arguments to
// the target internal "func" function in as many steps as necessary)
var functionAsExplicitObject = function(...arguments)
{
var functionAsExplicitObjectBody = {
variableAsProperty: "variableAsProperty's value",
func: function(argument1, argument2)
{
function someNestedFunction()
{
console.log('--> functionAsExplicitObjectBody.variableAsProperty: ',
functionAsExplicitObjectBody.variableAsProperty);
}
console.log("argument1: ", argument1);
console.log("argument2: ", argument2);
console.log("this.variableAsProperty: ", this.variableAsProperty);
someNestedFunction();
}
};
return functionAsExplicitObjectBody.func(...arguments);
};
functionAsExplicitObject("argument1's value", "argument2's value");
I was running into the same problem even with global variables. My problem, I discovered, was global variable do Not persist between html files.
<script>
window.myVar = 'foo';
window.myVarTwo = 'bar';
</script>
<object type="text/html" data="/myDataSource.html"></object>
I tried to reference myVar and myVarTwo in the loaded HTML file, but received the undefined error.
Long story/day short, I discovered I could reference the variables using:
<!DOCTYPE html>
<html lang="en">
<!! other stuff here !!>
<script>
var myHTMLVar = this.parent.myVar
/* other stuff here */
</script>
</html>
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>
Today, I got completely surprised when I saw that a global variable has undefined value in a certain case.
Example:
var value = 10;
function test() {
//A
console.log(value);
var value = 20;
//B
console.log(value);
}
test();
Gives output as
undefined
20
Here, why is the JavaScript engine considering global value as undefined? I know that JavaScript is an interpreted language. How is it able to consider variables in the function?
Is that a pitfall from the JavaScript engine?
This phenomenon is known as: JavaScript Variable Hoisting.
At no point are you accessing the global variable in your function; you're only ever accessing the local value variable.
Your code is equivalent to the following:
var value = 10;
function test() {
var value;
console.log(value);
value = 20;
console.log(value);
}
test();
Still surprised you're getting undefined?
Explanation:
This is something that every JavaScript programmer bumps into sooner or later. Simply put, whatever variables you declare are always hoisted to the top of your local closure. So, even though you declared your variable after the first console.log call, it's still considered as if you had declared it before that.
However, only the declaration part is being hoisted; the assignment, on the other hand, is not.
So, when you first called console.log(value), you were referencing your locally declared variable, which has got nothing assigned to it yet; hence undefined.
Here's another example:
var test = 'start';
function end() {
test = 'end';
var test = 'local';
}
end();
alert(test);
What do you think this will alert? No, don't just read on, think about it. What's the value of test?
If you said anything other than start, you were wrong. The above code is equivalent to this:
var test = 'start';
function end() {
var test;
test = 'end';
test = 'local';
}
end();
alert(test);
so that the global variable is never affected.
As you can see, no matter where you put your variable declaration, it is always hoisted to the top of your local closure.
Side note:
This also applies to functions.
Consider this piece of code:
test("Won't work!");
test = function(text) { alert(text); }
which will give you a reference error:
Uncaught ReferenceError: test is not defined
This throws off a lot of developers, since this piece of code works fine:
test("Works!");
function test(text) { alert(text); }
The reason for this, as stated, is because the assignment part is not hoisted. So in the first example, when test("Won't work!") was run, the test variable has already been declared, but has yet to have the function assigned to it.
In the second example, we're not using variable assignment. Rather, we're using proper function declaration syntax, which does get the function completely hoisted.
Ben Cherry has written an excellent article on this, appropriately titled JavaScript Scoping and Hoisting.
Read it. It'll give you the whole picture in full detail.
I was somewhat disappointed that the problem here is explained, but no one proposed a solution. If you want to access a global variable in function scope without the function making an undefined local var first, reference the var as window.varName
Variables in JavaScript always have function-wide scope. Even if they were defined in the middle of the function, they are visible before. Similar phenomena may be observed with function hoisting.
That being said, the first console.log(value) sees the value variable (the inner one which shadows the outer value), but it has not yet been initialized. You can think of it as if all variable declarations were implicitly moved to the beginning of the function (not inner-most code block), while the definitions are left on the same place.
See also
Javascript function scoping and hoisting
Javascript variable declarations at the head of a function
There is a global variable value, but when control enters the test function, another value variable is declared, which shadows the global one. Since variable declarations (but not assignments) in JavaScript are hoisted to the top of scope in which they are declared:
//value == undefined (global)
var value = 10;
//value == 10 (global)
function test() {
//value == undefined (local)
var value = 20;
//value == 20 (local)
}
//value == 10 (global)
Note that the same is true of function declarations, which means you can call a function before it appears to be defined in your code:
test(); //Call the function before it appears in the source
function test() {
//Do stuff
}
It's also worth noting that when you combine the two into a function expression, the variable will be undefined until the assignment takes place, so you can't call the function until that happens:
var test = function() {
//Do stuff
};
test(); //Have to call the function after the assignment
The simplest way to keep access to outer variables (not just of global scope) is, of course, to try to not re-declare them under the same name in functions; just do not use var there. The use of proper descriptive naming rules is advised. With those, it will be hard to end up with variables named like value (this aspect is not necessarily related to the example in the question as this variable name might have been given for simplicity).
If the function might be reused elsewhere and hence there is no guarantee that the outer variable actually defined in that new context, Eval function can be used. It is slow in this operation so it is not recommended for performance-demanding functions:
if (typeof variable === "undefined")
{
eval("var variable = 'Some value';");
}
If the outer scope variable you want access to is defined in a named function, then it might be attached to the function itself in the first place and then accessed from anywhere in the code -- be it from deeply nested functions or event handlers outside of everything else. Notice that accessing properties is way slower and would require you to change the way you program, so it is not recommended unless it is really necessary: Variables as properties of functions (JSFiddle):
// (the wrapper-binder is only necessary for using variables-properties
// via "this"instead of the function's name)
var functionAsImplicitObjectBody = function()
{
function someNestedFunction()
{
var redefinableVariable = "redefinableVariable's value from someNestedFunction";
console.log('--> functionAsImplicitObjectBody.variableAsProperty: ', functionAsImplicitObjectBody.variableAsProperty);
console.log('--> redefinableVariable: ', redefinableVariable);
}
var redefinableVariable = "redefinableVariable's value from someFunctionBody";
console.log('this.variableAsProperty: ', this.variableAsProperty);
console.log('functionAsImplicitObjectBody.variableAsProperty: ', functionAsImplicitObjectBody.variableAsProperty);
console.log('redefinableVariable: ', redefinableVariable);
someNestedFunction();
},
functionAsImplicitObject = functionAsImplicitObjectBody.bind(functionAsImplicitObjectBody);
functionAsImplicitObjectBody.variableAsProperty = "variableAsProperty's value, set at time stamp: " + (new Date()).getTime();
functionAsImplicitObject();
// (spread-like operator "..." provides passing of any number of arguments to
// the target internal "func" function in as many steps as necessary)
var functionAsExplicitObject = function(...arguments)
{
var functionAsExplicitObjectBody = {
variableAsProperty: "variableAsProperty's value",
func: function(argument1, argument2)
{
function someNestedFunction()
{
console.log('--> functionAsExplicitObjectBody.variableAsProperty: ',
functionAsExplicitObjectBody.variableAsProperty);
}
console.log("argument1: ", argument1);
console.log("argument2: ", argument2);
console.log("this.variableAsProperty: ", this.variableAsProperty);
someNestedFunction();
}
};
return functionAsExplicitObjectBody.func(...arguments);
};
functionAsExplicitObject("argument1's value", "argument2's value");
I was running into the same problem even with global variables. My problem, I discovered, was global variable do Not persist between html files.
<script>
window.myVar = 'foo';
window.myVarTwo = 'bar';
</script>
<object type="text/html" data="/myDataSource.html"></object>
I tried to reference myVar and myVarTwo in the loaded HTML file, but received the undefined error.
Long story/day short, I discovered I could reference the variables using:
<!DOCTYPE html>
<html lang="en">
<!! other stuff here !!>
<script>
var myHTMLVar = this.parent.myVar
/* other stuff here */
</script>
</html>