I know that function expressions resolve to a value (not to be confused with what they return [as others cleared up for me in another SO question)—all functions return undefined by default), hence the word "expression," whereas function declarations don't. But I'm not sure what exactly is causing this discrepancy. My initial guess was that it is the variable assignment (given what's to the right of the assignment operator is always an expression [I think]), but function expressions don't require variable assignment. To my knowledge the only other difference (besides resolving to a value) between them and function declarations is that you can omit the function name in a function expression. I'd appreciate any insight.
Refer :https://javascript.info/function-expressions-arrows#function-expression-vs-function-declaration
A Function Expression is created when the execution reaches it and is usable from then on.
Once the execution flow passes to the right side of the assignment let sum = function… – here we go, the function is created and can be used (assigned, called etc) from now on.
Function Declarations are different.
A Function Declaration is usable in the whole script/code block.
In other words, when JavaScript prepares to run the script or a code block, it first looks for Function Declarations in it and creates the functions. We can think of it as an “initialization stage”.
And after all of the Function Declarations are processed, the execution goes on.
As a result, a function declared as a Function Declaration can be called earlier than it is defined.
sayHi("John"); // Hello, John
function sayHi(name) {
alert( `Hello, ${name}` );
}
The Function Declaration sayHi is created when JavaScript is preparing to start the script and is visible everywhere in it.
…If it was a Function Expression, then it wouldn’t work:
sayHi("John"); // error!
let sayHi = function(name) { // (*) no magic any more
alert( `Hello, ${name}` );
};
Function Expressions are created when the execution reaches them. That would happen only in the line (*). Too late.
When a Function Declaration is made within a code block, it is visible everywhere inside that block. But not outside of it.
Sometimes that’s handy to declare a local function only needed in that block alone. But that feature may also cause problems.
For instance, let’s imagine that we need to declare a function welcome() depending on the age variable that we get during runtime. And then we plan to use it some time later.
let age = prompt("What is your age?", 18);
// conditionally declare a function
if (age < 18) {
function welcome() {
alert("Hello!");
}
} else {
function welcome() {
alert("Greetings!");
}
}
// ...use it later
welcome(); // Error: welcome is not defined
That’s because a Function Declaration is only visible inside the code block in which it resides.
Here’s another example:
let age = 16; // take 16 as an example
if (age < 18) {
welcome(); // \ (runs)
// |
function welcome() { // |
alert("Hello!"); // | Function Declaration is available
} // | everywhere in the block where it's declared
// |
welcome(); // / (runs)
} else {
function welcome() { // for age = 16, this "welcome" is never created
alert("Greetings!");
}
}
// Here we're out of curly braces,
// so we can not see Function Declarations made inside of them.
welcome(); // Error: welcome is not defined
What can we do to make welcome visible outside of if?
The correct approach would be to use a Function Expression and assign welcome to the variable that is declared outside of if and has the proper visibility.
Now it works as intended:
let age = prompt("What is your age?", 18);
let welcome;
if (age < 18) {
welcome = function() {
alert("Hello!");
};
} else {
welcome = function() {
alert("Greetings!");
};
}
welcome(); // ok now
Or we could simplify it even further using a question mark operator ?:
let age = prompt("What is your age?", 18);
let welcome = (age < 18) ?
function() { alert("Hello!"); } :
function() { alert("Greetings!"); };
welcome(); // ok now
Related
I want to know how the function has been initialized, with the expression or declaried as fuction. _ Amazon interview question
expression : var a = function (){ }
declaration: function a (){ }
You could just do a.toString() and parse out the name. Or do the same with regular expressions
a.toString().test(/^\s*function\s*\(/);
function a(){ }; // gives false
var a = function (){ }; // gives true
Of course as Grundy pointed out this fails with named functions. Something like
var a = function b() {};
or
function b() {};
var a = b;
And ES6 has .name (see the Browser table at the bottom for the current state of affairs) - https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Function/name
I don't think it's possible to do so. The only difference between:
var func = function(){ };
and:
function func() { };
Is that the first one gets assigned on runtime. The way I see it, is that both function statements return a reference to their respective function objects. In that sense they are both the same. The only thing you could argue is that one is not named and the other one is, but you could have assigned a named function to a variable too.
However, there seems to be a difference on how they get assigned. The second one seems to get assigned to a variable that its named after, right at the start of the execution context. The first one has to wait for the explicit assignment within the execution context.
So you'd be testing for when they get assigned. You might think that's is possible to do so within the global object like:
//some protected vars that can't work without same-origin
var protected = ['caches', 'localStorage', 'sessionStorage', 'frameElement'];
var definedAtInit = [];
for(prop in window){
if(!isSandboxed(prop) && typeof window[prop] === 'function'){
definedAtInit.push(prop);
}
};
function isSandboxed(prop){
return protected.indexOf(prop) !== -1;
}
function isItDefinedAtInit(funcName){
return definedAtInit.indexOf(funcName) !== -1;
}
var func = function() {
console.log('test');
}
var results = { isItDefinedAtInit : isItDefinedAtInit('isItDefinedAtInit'),
func : isItDefinedAtInit('func')
};
document.getElementById('results').innerHTML = JSON.stringify(results, '/t');
<pre id="results"></pre>
However, you could still do something like:
var isItDefinedAtInit = function() { };
//After this, isItDefinedAtInit('isItDefinedAtInit') would be wrong.
And you still have the problems with other execution contexts, I don't think functions declared within a function execution context get attached to any object.
I think these kind of checks are a bad idea to be honest.
There is only way, we can determine function has defined with function declarations not as expression.
as Grundy mentioned name property of the respective function gives require information, if it has been defined with expression name property holds undefined value, else it holds function name.
Here is the code :
var isDefinedAsFunction = function(fn){
return fn.name !== undefined
}
I have this situation
var fellowship = undefined;
fellowship = function(){
return "broken";
};
function fellowship(){
return "friends";
}
console.log(fellowship);
The function that returns "friends" is never reached, even if I call it like this:
console.log(fellowship());
Can anyone explain me how the function can be called?
Your code is interpreted as if it looked like this:
function fellowship(){
return "friends";
}
var fellowship = undefined;
fellowship = function(){
return "broken";
};
console.log(fellowship);
Thus, the declaration of a variable named "fellowship" overwrites the binding of that symbol to the function defined with the same name. You can't call it after that point.
"Can anyone explain me how the function can be called?"
It can't be called. You've overwritten it. There's no way for a single identifier to directly reference two different values.
Function declarations will always lose in a contention with an assignment expression in the same scope.
Yes here the concept of variable hoisting and function declaration hoisting is coming into picture.
In your example, you have declared
var fellowship = undefined;
already at the top.
Now the next statement:
fellowship = function() {
return "broken";
}
is an expression which is not hoisted in javascript.
And the third one is function declaration which on the line of variable hoisting is also hoisted.
So, now your structure becomes something like:
var fellowship = undefined;
// function declaration hoisted
function fellowship(){
return "friends";
}
fellowship = function(){
return "broken";
};
So, when you are calling fellowship(), it returns 'broken'.
http://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/
thi link should be useful to you
In JavaScript, function definitions are hoisted to the top of the current scope. Your example code therefore reads as:
var fellowship= function() { return 'friends' };
var fellowship= function() { return 'broken' };
if u want info about this follow this link:
http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html
Is javascript code read from the top down?
In other words if I have:
function Color(){
}
function Weather() {
}
If I wanted to incorporate some type of weather object inside the Color function would it be possible since Weather is defined afterwards?
The function Color won't know about Weather as it's being parsed, but it will once it is called. For example:
// Since variable declarations are hoisted to the top,
// myVar will be undefined (same as simply saying "var myVar;")
console.log(myVar); // <-- undefined
var myVar = 5;
console.log(myVar); // <-- 5
// test2 hasn't been defined yet, but it doesn't matter
// because test isn't being executed
var test = function() {
test2();
}
// This will throw an error: undefined is not a function
// because test2 isn't defined
test();
var test2 = function() {
alert("test2");
}
// This won't throw an error
test();
Essentially, you should execute after all functions have been defined. However, if you use the function functName() {} syntax, then it is hoisted just like a var statement.
function test() {
test2();
}
// Works!
test();
function test2() { alert("test2"); }
JavaScript is parsed "top-down" and Function Declarations are hoisted constructs - see var functionName = function() {} vs function functionName() {}. Parsing happens before the JavaScript execution itself starts; the following thus covers the evaluation semantics1.
Given the effect of function hoisting, the following code is valid, although it seems like it might not be:
function a(){
return b();
}
alert(a()); // alerts "b", even though "b comes later"
// This declaration IS hoisted
function b() {
return "b";
}
However, considering that even when using "var fn = .." (when the assignment is not hoisted) the ordering usually doesn't matter because the evaluation of the assignments happens before the usage:
var a = function () {
return b();
}
// alert(a()); <- this would fail, because b is not assigned yet
// This assignment is NOT hoisted
var b = function () {
return "b";
}
// But b is assigned before here, meaning that the order of the constructor
// functions still Just Doesn't Matter.
alert(a());
As such, in the case where there are two constructor functions (e.g. Color and Weather) which are [mutually] dependent, it doesn't matter where they are located in the same scope relative to each other.
1The thing that matters is the expression representing the dependency is resolvable when evaluated (which is relative to the evaluation code, but not related to the parsing/placement order of the functions).
so basically yeah you can implement something to a function that appears in a previous code.
hole this helps you understand it better.
var weather = function() {
if (weather === red) {
console.log("weather is represented by the color red");
}
else {
console.log("Not the right color");
}
};
weather(red);
I have read a lot about closures in Javascript
What are those braces for??
I read on mozilla.org which says closure should be defined as
(function(){...})();
but on http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html, it says the closure function is
(function(){...}());
What's the difference or the latter one is wrong?
what's the purpose of the last ()? Would you put some parameters inside?
I am looking for a good reference.
Edit:
Moreover, there is an example on Mozilla.org
var makeCounter = function() {
var privateCounter = 0;
function changeBy(val) {
privateCounter += val;
}
return {
increment: function() {
changeBy(1);
},
decrement: function() {
changeBy(-1);
},
value: function() {
return privateCounter;
}
}
};
why the semicolon is needed for this 'function'? If it needs to be invoked immediately after its declaration, a () should be put before the ending semicolon. But there is not.
The syntax
(function(){...})()
is simply an immediately invoked anonymous function. It does not matter how you use your brackets, as the underlying code is a function being declared, and invoked.
Closures are instead used to describe a situation where a function has access to variables declared outside of its scope, accessible via closures
For clarity :
If we have the following function
function hello() {
alert("Hello");
}
We can call the function with the following
hello()
Which invokes the function 'hello'. But if we do not wish to give it a name, but still invoke it, then we can do
(function hello() {
alert("Hello");
})()
Which will do the exact same as the previous example of calling hello
However, in this scenario there is no point in giving the function the name 'hello', so we can simply remove it:
(function() {
alert("Hello");
})()
Which is the notation used in your original question.
Your example shows an Immediately Invoked Function Expression, or IIFE. It says to the interpreter:
here is a function
it has no name
keep it away from the global scope ie 'window'
call it now
Yes, you can put parameters inside the last (). For example:
(
function(username){
alert("Hello " + username);
}
)("John Smith")
Closures are a feature of javascript that allows us to implement data hiding which is roughly equivalent to private variables in languages like C++ or Java.
function getBmiCalculator(height, weight) {
// These are private vars
var height = height;
var weight = weight;
function calculateBmi(){
return weight / (height * height);
}
return calculateBmi;
}
var calc = getBmiCalculator(1.85, 90);
// calc still has access to the scope where height and weight live.
var bmi = calc();
alert(bmi);
In this example, height & weight cannot be garbage-collected until calc is destroyed. The section of memory or "scope" where height & weight exist are "Closed Over"
There is no difference. You can also do so:
true && function(){ /* code */ }();
0,function(){ /* code */ }();
!function(){ /* code */ }(); // Facebook style
~function(){ /* code */ }();
-function(){ /* code */ }();
+function(){ /* code */ }();
// with new
new function(){ /* code */ }
new function(){ /* code */ }() // if you need arguments then use brackets
the grouping operator can surround the function description as without call parentheses, and also including call parentheses. I.e. both expressions below are correct FE:
(function () {})();
(function () {}());
Function Expression
Ben Cherry's excellent article explains hoisting in JavaScript adequately. My problem, however, is that I cannot conceive a use case for this notorious perpetrator of confusion. Please explain if there is a design pattern that actually takes advantage of this language feature.
Secondly, is scope hoisting unique to JavaScript?
UPDATE --- I'm adding a bounty for an answer that satisfies my curiosity: Which design pattern(s) actually take advantage of JavaScript's hoisting behavior? I understand why JavaScript supports hoisting, but I want to know how I can take advantage of this feature.
Variable hoisting
One of the simplest uses of hoisting is variable hoisting. If we didn't have variable hoisting, this would throw a ReferenceError:
var bar = foo;
var foo;
That doesn't seem immediately useful, but it allows us to do things like this:
var myCoolJS = myCoolJS || {};
This basically means what it looks like: myCoolJS is myCoolJS if it exists, or a new object if it doesn't. The second myCoolJS doesn't throw a ReferenceError if myCoolJS didn't already exist, because this variable declaration is hoisted.
This saves us from doing an awkward typeof myCoolJS != 'undefined' check.
Function hoisting
Function hoisting can be especially useful when combining multiple scripts into one. For example, I've created a lightweight build-time implementation of CommonJS modules. This provides the same module, require, and exports features that are found in node.js. I built the tool to allow required modules to be composed of multiple files. For example, require('/foo') could result in a module composed of two files, foo.js (the "body file") and foo.h.js (the "header file").
This allows the "body file" to have no knowledge of the free variables provided by the CommonJS modules environment; all of that is handled in the header. This makes code reusable and easy to test without building. However, since the headers are prepended to the body, we leverage function hoisting in the body file to allow exports in the headers. For example:
// dom.h.js
var util = require('util').util;
exports.css = css; // we can do this because "css" is hoisted from below
// ... other exports ...
...
// dom.js
function css(){}; // this would normally just be an object.
css.hasClass = function(element) { ... };
css.addClass = function(element) { ... };
// ...other code...
Here's a use for hoisting:
(function() {
var factorial = function(n) {
if(n == 0)
return 1;
return n * factorial(n - 1);
};
})();
Without hoisting, that wouldn't compile because factorial wouldn't exist yet inside the function literal. You'd have to declare the variable separately or use a named function.
JavaScript also allows code like the following:
var test = function(b) {
if(b) {
var value = 2;
} else {
var value = 5;
}
console.log(value);
};
With block scoping, you'd have to add another line to declare value before the if.
To be fair, this code works because of function scope, not hoisting. And JavaScript could have had function scope without hoisting. Ruby handles this better: Ruby has method scope for variables, but the variables don't exist until you set them:
def test(b)
# unlike JavaScript, value is not accessible here
if b
value = 2
else
value = 5
end
puts value
end
JavaScript does not have block scope (let's forget about let for now) and thus any variable declaration is declaring for the entire function, of which JavaScript does have scope.
If you think about it that way, JavaScript hoisting may make more sense.
If you remember about hoisting, it shouldn't be a source of bugs and confusion. It's simply one of those quirks you must understand and remember.
I'm not sure if hoisting is limited to JavaScript. I've never heard of it elsewhere, but that doesn't necessarily mean it doesn't exist in other languages.
The first two examples in that article are just badly written. Bad code obviously leads to bugs and confusion. Let me give you the refactored versions of these examples. You will see that there is no confusion here...
Example 1 - Original code
var foo = 1;
function bar() {
if (!foo) {
var foo = 10;
}
alert(foo);
}
bar();
Example 1 - Refactored code (removed confusion)
var foo = 1;
function bar() {
var foo;
if ( !foo ) {
foo = 10;
}
alert( foo );
}
bar();
The alert displays "10", and it's clear why. No confusion here.
Example 2 - Original code
var a = 1;
function b() {
a = 10;
return;
function a() {}
}
b();
alert(a);
Example 2 - Refactored code (removed confusion)
var a = 1;
function b() {
var a = function () {};
a = 10;
return;
}
b();
alert( a );
The alert displays "1". Obviously. No confusion here, too.
"hoisting" is not part of the ECMAScript Standard, but it does say that variable inside a function are declared at the begin of the function regardless of where in the function it is place in the code.
Example
(function() {
alert(myvar); // undefined
var myvar = 'local value';
})();
Internally Javascript would declare myvar before the alert, show the alert, then it would assign myvar to 'local value'.
So Javascript would interpet that code as:
(function() {
var myvar;
alert(myvar); // undefined
myvar = 'local value';
})();
That is why "Java the Good parts" has a guideline that say you should declare variable at the top of your function.
Source: http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-javascript-hoisting-explained/
"Please explain if there is a design pattern that actually takes advantage of this language feature." "hoisting" is not a feature but rather a consequence how the Javascript interpreter structure the code since the language uses function-scoping.
"Which design pattern(s) actually take advantage of JavaScript's hoisting behavior? "
Answer: None.
I think one area where hoisting is useful is due to the fact that functions are treated as first class objects. For example:
function foo()
{
function a()
{
//...
}
function b()
{
//...
}
}
can also be written as:
function foo()
{
var a = function ()
{
//...
}
var b = function ()
{
//...
}
}
Without hoisting, the following would result in an error:
function foo()
{
var a = function ()
{
b();
}
a(); //Error in function since b is not yet defined
var b = function ()
{
//...
}
}
I suppose they could have only hoisted function objects, but I believe that would be inconsistent with the philosophy that functions should be treated as first class citizens in the language.
Here's a real use case (albeit reduced to pseudo-code) for you, from someone who would actually want to use the benefits of hoisting in the wild.
I recently wrote this script for handling simple form validation and submission. As far as possible, each function declaration invokes the following. This has 2 chief benefits for readability:
Logical sequence: there is a sequential flow to the code, which means functions will always be invoked before they are declared. This is a benefit in that, when used with low complexity functions, it keeps things relatively flat and gives you an idea of the calling context of a function shortly before its source. You will only ever have to scroll down (never up) to follow code, and — as far as possible — scroll not at all or very little.
Low reference overhead: I like to keep all my variable declarations at the top of each scope so readers are aware of all the moving parts the function requires before reading through its body, but nobody wants to read every invoked function's source code to get an idea of what the current scope does. Using this method, you'll never run into a function reference before its declaration. It sounds stupid at first, but it actually reduces cognitive overhead: you're never given a function's source with the implicit remember this — we'll be using it later — instead you only ever read function source once you know the context it was called in.
$( function emailHandler(){
var $form = …
var $email = …
var $feedback = …
var value = …
var validation = …
// All initialisation is right here. Executes immediately.
// Therefore, all future code will only ever be invoked
// by call stacks passing through here.
void function bindEvents(){
$email.on( 'input', filterInput );
$form.on( 'submit', preSubmit );
}();
function filterInput( inputEvent ){
if( inputEvent && inputEvent.which === '13' ){
return presubmit( inputEvent );
}
return validate();
}
function validate(){
var presentValue = $email.val();
if( validation.done || presentValue === value ){
return;
}
else if( presentValue === placeholder || presentValue === '' ){
validation.message = 'You must enter an email address to sign up';
validation.valid = false;
}
else if( !validation.pattern.test( presentValue ) ){
validation.message = 'Please enter a valid email address';
validation.valid = false;
}
else {
validation.message = '';
validation.valid = true;
}
validation.ever = true;
clearFeedback();
}
function preSubmit( inputEvent ){
if( inputEvent instanceof $.Event ){
inputEvent.preventDefault();
}
if( !validation.ever ){
validate();
}
if( validation.pending || validation.done ){
return;
}
else if( validation.valid ){
return submit();
}
else {
return feedback();
}
}
function submit(){
$form.addClass( 'pending' );
// Create an XHR base on form attributes
$.ajax( {
cache : false,
url : $form.attr( 'action' ),
data : $form.serialize(),
type : $form.attr( 'method' ).toUpperCase()
} )
.done( success )
.fail( failure )
.always( feedback );
}
function success( response ){
validation.message = response.message;
validation.valid = response.valid;
}
function failure(){
validation.message = 'Our server couldn\'t sign you up. Please try again later.';
validation.error = true;
}
function feedback(){
clearFeedback();
if( validation.message ){
$feedback
.html( validation.message )
.appendTo( $placeholder );
}
if( !validation.valid || validation.error ){
$form.addClass( 'invalid' );
$email.trigger( 'focus' );
}
else {
$form.addClass( 'done' );
validation.done = true;
}
validation.pending = false;
}
function clearFeedback(){
$form.removeClass( 'invalid pending done' );
}
} );
I like the style of question, based on curiosity about the language. Obviously no one should actually use hoisting as a feature, unless they're absolutely certain that their home address cannot be discovered by those who may use it later.
I can only imagine a few trivial cases. The basic property to exploit is that the variable can be declared (but undefined) and then assigned in only one line of code, but with the events interpreted at two different distinct point.
With the declaration at the end of a loop (not .forEach as that of course sets scope) you could use this to detect the first iteration.
var notfirst = true; // this is actually never referenced.
(function () {
var number, stack = [1, 2, 3, 4, 5];
while (number = stack.pop()) {
if (notfirst) console.log(number);
var notfirst = true;
}
})();
The output from emptying the stack is 4, 3, 2, 1. 5 is rejected.
Again. Don't do this!
If you consider the way other languages are written (C++/Java) and how their Class patterns are used, hoisting could be taken advantage of to write a similar pattern to build prototypes .