Why can I reference a variable not yet defined in Javascript? - javascript

When creating the function foo here, I reference a variable fromTheFuture the hasn't been declared yet. This actually works as expected, but why? Is it considered dangerous or bad practice?
var foo = function(x) {
return fromTheFuture * x;
};
var fromTheFuture = 5;
console.log(foo(10));
I can see this being very convenient though, if you have several functions that wants use each other in a cycle fashion - without having to declare them all with var in the beginning of the method.

By the time foo is called, fromTheFuture is defined. More accurately, due to hoisting, your code is essentially:
var foo, fromTheFuture;
foo = function(x) {return fromTheFuture*x;};
fromTheFuture = 5;
console.log(foo(10));
If you were to call foo(10) before fromTheFuture=5, you would get NaN.

Yes, the entire script is processed first, the variables added to the "data store" and only then the execution is performed.
However, this is not encouraged as it makes the code hard to read. If you want to know more about javascript code quality, check out jslint. It's a sort of FxCop for js. Try copy-pasting your code in there.

the reasone behined it in javascript it define all varible first and then start initializing and then after if somewhere it need its intialization point it try intializized called one first

Related

Difference between IIFE and regular function (example)

Learning about IIFEs i understand that using them does:
not pollute the global scope
shields your code from others.
Could someone please help me understand it better and give a real example of when i could get in trouble when using regular function statement (instead od IIFE?)
Let's say you have a decent sized codebase (a few thousand lines or more). Putting every function on the top level won't be a good idea, because then it'll be pretty easy to accidentally write a function name twice, which will cause bugs due to the name collision. For example:
// code around validating user registration
function validate(username) {
return /someValidationRegex/.test(username);
}
// do stuff with validate
// And then, far elsewhere in the code,
// you need to validate an input for sending to the server:
function validate(input) {
return /someOtherValidationRegex/.test(input);
}
// do stuff with validate
This will not work, because the last validate function will overwrite the first validate function, and the code won't work as expected.
Put each segment of code into an IIFE instead, to avoid the possibility of name collisions:
(() => {
// code around validating user registration
function validate(username) {
return /someValidationRegex/.test(username);
}
// do stuff with validate
})();
(() => {
// code around validating an input for sending to the server:
function validate(input) {
return /someOtherValidationRegex/.test(input);
}
// do stuff with validate
})();
This is the technique that Stack Overflow's Javascript uses (at least in some parts).
Another reason to use IIFEs even if you're careful not to duplicate function names is that you may accidentally duplicate a window property. For example, the following is a somewhat common bug people run into:
// name is defined to be a number...
var name = 5;
// but it's actually a string???
console.log(typeof name);
The problem here is that you're accidentally referring to / overwriting the window.name property on the top level, and window.name may only be a string. There are a whole bunch of functions and variables defined on the top level. To avoid name collisions, put everything into an IIFE instead:
(() => {
// name is defined to be a number...
var name = 5;
// And it's still a number, good
console.log(typeof name);
})();
Still, if your codebase is large enough that name collisions are a decent possibility, rather than manually writing IIFEs, I'd highly recommend using a module system instead, like with Webpack. This will allow you to write modules inside their own encapsulated scope, without leakage or name collisions, and will be more maintainable, when each module only contains exactly the code it needs to run, and nothing more. This makes identifying bugs and extending features much easier than one huge long <script> that you have to navigate through manually.
The common advantage of IIFE is that any "Function or Variable" defined inside IIFE, cannot be accessed outside the IIFE block, thus preventing global scope from getting polluted.
IIFE's are used to define and execute functions on fly and use them on the spot without extra line of Code.
(function(){
var firstName = 'Jhon';
console.log(firstName);
})(); // will be executed on the fly
function test(){
var firstName = 'Jhon';
console.log(firstName);
}
test(); // has to call manually
The IIFE will actually run (immediately-invoked function expression), they don't need a trigger or function call to initiate them, so the variable will be set to its response.
Here's a Fiddle to demonstrate this:
var iffe = (function() {
return 'foo';
})();
var func = function() {
return 'bar';
};
console.log('iife = ' + iffe);
console.log('non-iife = ' + func);
In your JS console you'll see something similar to:
iife = foo and
non-iife = function () {
return 'bar'; }
Also in case we need to pass something in the IFFE scope from the outer scope we need to pass them as a parameter and receive this inside the function defined in the IFFE wrap, something like this -:
var iffe = (function(doc) {
return 'foo';
})(document);
This is a link for some more reference - http://benalman.com/news/2010/11/immediately-invoked-function-expression/

declaring local variables inside document ready or inside function in different scope

I need to know which is the better way of declaring some local variables. Which is better in terms of practice, performance? Since, local variables declared inside the function gets removed as soon as the function is executed, does declaring as many local variables (eg: a,b in example below) inside various functions compared to declaring only once inside document.ready() makes any difference?
Method 1:
<script type="text/javascript">
$(function() {
getItem1();
getItem2();
}
function getItem1() {
var a = 100;
var b = 1000;
//do something with a,b
return item1;
}
function getItem2(){
var a = 100;
var b = 1000;
//do something with a,b
return item2;
}
</script>
Method 2:
<script>
$(function() {
var a = 100;
var b = 1000;
getItem1(a,b);
getItem2(a,b);
}
function getItem1(a,b) {
//do something with a,b
return item1;
}
function getItem2(a,b) {
//do something with a,b
return item2;
}
</script>
It's really an idea of why i am using these functions and what are my purposes because it may vary, in Method 1 you are declaring the variable inside a function which those variable will be saved in memory as soon as the function is being executed and they will be deleted when it finish , so if the function contain too many variables and too many lines of code it will not be a good idea if you r looking for performance so it is better using Method 2 ,but if your function is easy and having few lines of code with easy execution method 1 is better of course
It's all a matter of what you need, really.
Will you be reusing your functions on multiple instances? Will it be true that if a and b will be supplied on all possible scenarios, the code inside getItem will process the values correctly? If so, then passing the values will be a good choice since you have the free will to pass whatever you want to. If a and b are just constant and will never change at all, then having the values constant would be a great idea as well.
The second choice gives a lot of flexibility and you can change the values anytime you want, this makes the code more 'generic' and 'reusable' - provided you're going to use the same process.
Performance wise, they make a little difference. With the first option allocating a bit more memory since you have to instantiate a and b twice.

this versus function property in javascript

I want to create a static variable in my js. From what I know with my little js knowledge is, I can do it using this two ways.
function foo (){
if (this.counter==undefined){this.counter=1}
else {this.counter++ } ;
}
function foo (){
if (foo.counter==undefined){foo.counter=1}
else {foo.counter++ } ;
}
Are these two things essentially the same or I need to to careful in selecting one versus other.
Another question I have is: why var is not needed when doing these?
No, they are not equivalent. In your first example, you are using this. this can actually change depending on how the function is being called.
function showThis(){
console.log(this);
}
var obj = { };
obj.showThis = showThis;
showThis(); // gives 'window', or the top-most scope of your page
obj.showThis(); // gives obj as 'this'
If you are always calling the function the same way, then this would just mean the value counter is tracked as a property on window.counter. This is bad, because you may accidentally have an actual variable named counter in that scope, that you are now using in a different way somewhere else. If you are not calling it the same way everytime, then this will be different and probably not giving you your desired behavior.
If you are trying to keep a count on the number of times foo is being called, independent of how/who is calling it, then your second approach is more appropriate. For the sake of code clarify/convention, I would write it this way:
function foo (){
// If counter does not exist, create it and initialize it to 0.
foo.counter = foo.counter || 0;
foo.counter++;
}
foo.counter; // undefined, since foo has never been called yet
foo();
foo.counter; // is now 1
var is used to create a variable in the current scope.
Both the approaches you are taking are setting a property on an object that exists in a wider scope.

Why single var is good in javascript?

Can anyone tell me why use one var declaration for multiple variables and declare each variable on a newline consider is a good programming behavior?
// bad
var items = getItems();
var goSportsTeam = true;
var dragonball = 'z';
// good
var items = getItems(),
goSportsTeam = true,
dragonball = 'z';
It is not considered 'good' or 'bad'. It's a matter of preference.
The guy who built the code quality tool JSLint, Douglas Crockford likes it.
One 'advantage' it might have is that it avoids the possibility of variable hoisting. In JavaScript all var declarations move to the top of their scope automatically.
Here is why Crockford thinks the second option is better:
In languages with block scope, it is usually recommended that variables be declared at the site of first use. But because JavaScript does not have block scope, it is wiser to declare all of a function's variables at the top of the function. It is recommended that a single var statement be used per function. This can be declined with the vars option.
It's a preference, I wouldn't say good or bad. Yes JSLint complains about it, I don't really like how it complains about for loop variables being inline as well. The reason that it was put in JSLint was to prevent possible hoisting confusions.
Also in some cases declaring all of your variables at the top will lead to a slightly smaller file. Consider the following:
var a = 10;
a++;
var b = 20;
After Google Closure being run over it
var a=10;a++;var b=20;
As opposed to this if we pull b's declaration to the top.
var a=10,b;a++;b=20;
The main benefit (aside from style preference, I guess) is that it will prevent you from writing code that suffers from unintended variable hoisting consequences.
Take this example:
var foo = function(){alert('foo');}
function bar(){
foo();
var foo = function(){alert('foobar')};
foo();
}
bar();
By reading this code, the intent of bar appears to be as follows:
Call the outer foo function to alert the string 'foo'.
Create a local variable, foo.
Call the local foo function to alert the string 'foobar'.
In reality, what happens is this:
The local variable foo is hoisted to the top of the bar function.
foo now actually refers to the local variable instead of the outer variable of the same name. But since the local hasn't been assigned yet, its value is undefined. Hence, when you try to invoke foo, you'll get a TypeError.
Nothing. Because you threw an error. That's it. Your code broke.
The arguments for Crockfords preference have been well made and are valid. I am just beginning to return to the first format now however, as I believe that for experienced developers who understand variable hoisting and are not likely to fall foul to it, there are 2 advantages that I can think of:
When new variables are added to the list of definitions, diffing is made easier. This means you are likely to experience fewer merge conflicts (simple though they may be to resolve) and less cognitive load when analysing diffs. For similar reasons I have also been converted to dangling commas, which I would never have expected xD
As #ldsenow identified, it can make searching for variable definitions more simple. You will always be able to search for var <name> and get the result you want and nothing else.

use this.argu to store arguments a good practice?

i am new to front-end developing,and now i am reading a lot of js code written by other in my company and find they will use this syntax to store the arguments :
function func1(argu1,argu2){
this.argu1 = argu1;
this.argu2 = argu2;
// other code run here....
}
for me i usually skip this and use the argument directly in my code or get a variable for the n,like this:
function func2(argu1,argu2){
alert(argu1);
alert(argu2);
var arguOne = argu1,arguSec = argu2;
// other code run here...
}
so i want want to ask why use this syntax to store an arguments?
is this a good practice ?and why?
Have i ever miss some concepts that i should know?
see the fiddle, written by the my co-worker who has been no longer a front-ender....
In your first example, func1 can be used to create objects. It is effectively a class definition (constructor). It can be used as follows:
function func1(argu1,argu2)
{
this.argu1 = argu1;
this.argu2 = argu2;
}
var instance = new func1('a', 'b');
alert(instance.argu1);
alert(instance.argu2);
Lordy lord: Instead of defining the function, and calling it at the end, try using a closure. Just keep the function definition as is, but put it in brackets:
(function new_slider (arguments)
{
//your code here
})('#new_slider',1500,150,10);
This way, the function is declared, and invoked at the same time, all functions defined within the main new_slider function will have access to the arguments. There is absolutely no reason to use this.argu1 to store these values. If anything, it creates global variables, which is considered bad practice.
Please google closures in JavaScript, they're extremely powerful

Categories

Resources