When writing a Javascript function I have always made the first assignment to a variable with var as in
var x = 1;
Later x may be something else. Should I write
if (something ) {
x = 2;}
or
if (something) {
var x = 2;}
If you could say why that would help.
You shouldn't use the var keyword if you're changing the value of a variable that's already been declared.
So:
var x = 1;
if(something) x = 2;
If the test was that simple, you could also write it like this:
var x = something ? 2 : 1;
It's also got to do with scoping. A new scope is created within functions.
For example:
var x = 1;
function myFunction(){
var x = 2;
}
myFunction();
console.log(x); // 1
Whereas, if you omitted the var keyword within the function, you would be altering the value of the x variable in the outer scope and the console.log(x) would show 2.
In code that simple, it actually makes no difference whatsoever to the JS interpreter.
For the sake of all who have to read the code, however, it is best to declare variables once at the top of the scope in which they are needed. This helps make it very clear to all who work with the code where a variable is scoped. It also helps you avoid running into confusing issues caused by the JavaScript hoisting mechanism (which mechanism is actually the very reason it doesn't matter in your code).
Related
if i write something like this:
var a = 1;
function lol(){
console.log(a);
}
lol();
it outputs 1 as intended, as i initialized a=1 in global scope. So i thought in function it initialized its value as well.
But when i write something like this:
var a = 1;
function lol(){
var a = a + a;
console.log(a);
}
lol();
it outputs NaN, which confuses me, cuz i thought the variable has already been initialized in global scope.
Here's my thoughts, don't know if it's correct or not, so i'm asking: i think the keywords like var/let/const, each time it's mentioned, it kind of re-initialize the variable or what? and since the second var is in block scope, so when mentioned with var, the variable a goes initialized again and thus becomes undefined, outputs NaN.
am i correct? plz help.
You initialize the variable then just use the same variable
var a = 1;
function lol(){
a = a + a;
console.log(a);
}
lol();
at statement var a = a + a; you are defining altogether different variable which was not initialize before arithmetic operation so it is resulting NaN compiler declared another variable with same name a
Maybe it's happening because of hoisting. Please refer https://developer.mozilla.org/en-US/docs/Glossary/Hoisting#var_hoisting
As per MDN,
JavaScript Hoisting refers to the process whereby the interpreter appears to move the declaration of functions, variables or classes to the top of their scope, prior to execution of the code.
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.
I am learning JavaScript. I understood that variables created by 'let' are hoisted (as variables created by 'var') but those are not available to use until control hits the initialization statement because of temporal dead zone. If we can't use the variables, what is the need of hoisting those variables?
There is no need to hoist it, it is just something to be aware of.
If you had, as a ridiculous example:
var x = 10;
function if_x_is_10() {
if (x === 10) {
console.log('It was 10!');
}
let x = 10;
console.log('Now it is 10!');
}
if_x_is_10(); // Uncaught ReferenceError: x is not defined
You just need to be able to realize, "oh, even though there is an x outside the function, since there is a let x inside the function, I can't access x until I am past that line, and I can't access the outer x inside of the function".
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.
I am new to JavaScript.
<html>
<body>
<script type="text/javascript">
var x=5;
document.write(x);
document.write("<br />");
var x;
document.write(x);
</script>
</body>
</html>
Result is:
5
5
When x is declared the second time it should be undefined, but it keeps the previous value. Please explain whether this redeclaration has any special purpose.
You aren't really re-declaring the variable.
The variable statement in JavaScript, is subject to hoisting, that means that they are evaluated at parse-time and later in runtime the assignments are made.
Your code at the end of the parse phase, before the execution looks something like this:
var x;
x = 5;
document.write(x);
document.write("<br />");
document.write(x);
var alone does not perform an assignment. It only flags that when you use the variable name throughout the scope in which the var occurs, you are talking about a local variable and not global (the controversial default). The var is spotted when the function is parsed and holds throughout that scope, so where you put it is irrelevant:
var a= 0;
function foo() {
a= 1;
return a;
var a;
}
var b= foo();
alert('global a='+a+', local a='+b);
Results in global a= 0, local a= 1: even though the var statement is never reached in the course of execution of foo(), it is still effective in making a a local variable.
So declaring var x a second time in the same scope is completely redundant. However you might sometimes still do it, typically when you re-use a local variable name for a second independent use within the same function. Most commonly:
for (var i= 0; i<onething.length; i++) {
...do some trivial loop...
}
for (var i= 0; i<anotherthing.length; i++) {
...do another trivial loop...
}
Whilst you could certainly omit the second var, and tools like jslint would demand you do so, it might not actually be a good idea.
Imagine you later change or remove the first loop so that it no longer declares i to be var. Now the remaining second loop suddenly changes meaning from a local to a global variable. If you fail to notice when updating the first loop that the second loop has a hidden dependency on it (and you might very well fail to notice that given how the eyes elide the pattern for(...=0 ; ...<...; ...++) into “oh, that's just a standard iterator”), you've got a subtle and annoying-to-debug problem.
so when the second time when its declared x should be undefined
What part of the specification says this?
"Undefined behaviour" does not mean "the variable will be undefined".
As far as my understanding of javascript goes, the use of the var keyword is completely optional in the global scope. It's a different story for functions.
When inside a function, use the var keyword to indicate that the variable is local to the function (as opposed to being global by default).
I personally use var in the global scope to show that a variable is being declared and/or utilized for the first time.
You can reference http://www.w3schools.com/js/js_variables.asp for more info.
That second var x is totally superfluous.
Within the same scope, it is totally unnecessary to "redeclare" a variable.
Also, a programmer might want to use var to localize a variable:
<script>
var x= 'this is global x';
function my_x() {
var x= 'localized x';
alert(x);
}
my_x();
alert(x);
</script>
You should never redeclare a variable within the same scope, if you really want to change this then assign to it. Redeclaration is not required to create a different object in this dynamic language, if you want x to be a string just assign:
x = "hello";
It is not required that you set it back to undefined or redeclare first.
Please note that changing the variable type is not very good practice in most situations, simply stating that it is a possibility if that's what you require.
I recently wrote code like:
var obj1 = get_an_object();
var v = obj1.get_velocity();
v += changes_in_velocity();
obj1.set_velocity(v);
var obj2 = get_an_object();
var v = obj2.get_velocity();
v += changes_in_velocity();
obj2.set_velocity(v);
(The actual code was more complicated and less repetitive)
So far as the browser is concerned, the second var v statement was redundant and pointless. To me, it served two purposes. It said to forget everything I knew about the old v, because this was a new usage. And it meant I could re-order the code, or comment out the first half, without breaking things.