Parameters pass by value vs parameters as local variables in Javascript [duplicate] - javascript

This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
Closed 6 years ago.
Say for example you have a function like below
var value = 1;
function test(myVar) {
myVar = 2
}
test(value)
console.log(value)
//prints out 1
Now, I have read that there are two things that happen in JS functions.
1) Javascript passes primitives by value. When "value" is passed as an argument to test(), a copy is created that is separate from the global variable "value". Therefore the "myVar" is a separate variable from "value"
2) Parameters in JS functions are really just local variables to the function. So, the "myVar" parameter has scope only inside of the test() function.
I know both statements are true, but which one of these statements causes console.log(value) to print out 1

Both of those statements are true. The reason why it prints out 1 is that, as you mentioned, parameters are passed by value. As such, the value of your variable value is never altered.
Although point #2 is also true, it doesn't really have much to do with this behaviour. it is more related to doing something like using myVar outside of that function's scope.

Both of the statements are correct
Please check this URL from Mozilla Variable Scope in Javascript

Related

Hoisted JavaScript variables undefined or not? [duplicate]

This question already has answers here:
Using Javascript hoisting concept , I tried the following. I am not sure why the name variable has been picked up but not the age [duplicate]
(1 answer)
What is the global variable called 'name' in javascript? [duplicate]
(2 answers)
Closed last month.
I am trying to understand in a more deep way hoisting, creation phase and execution phase in JavaScript. To the best of my knowledge variables declared with var keyword are hoisted to the top of their scope. But I am running into this problem.
console.log(name); // Output -> 'any name'
console.log(age); // Output -> undefined
var name = 'any name';
var age = 30
I know at the moment when console.log statements are executed bot variables should be undefined because they are declared but values have not been assigned to them (they got undefined in the creation phase). However browsers keep giving me one of the values as undefined (as I expect it to be), but with name variable it is reading the string. Any ideas as to why is this happening?

Javascript -What happens if a variable and a function have the same name? [duplicate]

This question already has answers here:
Function and variable with the same name
(2 answers)
Closed 5 years ago.
Might be a kind of easy question, but I have a question on the issue of having the same name for a variable and a function.
If there's a variable,
var add = 1;
and a function,
function add(x,y) {return x+y;}
and there're two console.log,
console.log(add)
console.log(add(1,2))
I've expected those 2 console.log would work properly since add contains the Number and add() is classified as a Function, but the second one prints an error. So they aren't considered the same.
But the result says I'm wrong.
Can anyone explain what's going on in my code?
Variables and function definitions(not expressions) are hoisted to up, it means that wherever in scope you wrote your function or variable they will be moved to the start of the scope. First goes functions definitions then variables. So it means that functions will be overwritten by variables.
var add = 1;
function add(x,y) {return x+y;}
console.log(add);
The order doesn't matter. Later will be the variable and will overwrite
function add(x,y) {return x+y;}
var add = 1;
console.log(add);

In Java Script Global Variable is not clear [duplicate]

This question already has answers here:
How can I unset a JavaScript variable?
(12 answers)
Closed 7 years ago.
I have declare global variable in java script, i try to clear with following code but it not clear.
As i defined global variable.
var usno;
then before set value i tried following code
delete window.usno;
usno = undefined;
usno=null;
but no success.
Please help on this
Thanks
Basit.
In short, you cannot delete variables defined with var. If you set the variable using window.usno then it can be. See Understanding delete and the answers to How to unset a JavaScript variable? for more details.
Do you really need to delete the variable though? Instead of making a global variable, restrict the scope of your variable to a function so that it will be garbage collected after the scope of the function ends.
Your first solution is the correct one.
delete window.usno;
That deletes the property usno from the global window object. But here is where the confusion lies, when we test it:
window.usno; // -> undefined
So, a deleted or non-existent property returns undefined. Thus, in effect, the following two statements achieve much the same thing:
delete window.usno;
window.usno = undefined;
They are not exactly the same thing. In the second case, the usno property still exists, as you will find if your iterated through all of the properties of window.
Short answer:
delete window.usno;

Global variable is defined within function and also expires in function javascript [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 8 years ago.
I am creating a chrome extension and to my surprise my content script is acting very odd. I have defined a global variable keyword but when it goes through the function that gives it it's value, the value expires when the function ends. I've spent hours troubleshooting and can't seem to find the problem.
var keyword;
chrome.extension.sendMessage({localStorage: "yo"}, function(response) {
var localStorage = response.localStorage;
keyword = localStorage["keyword"];
console.log(keyword);
});
console.log(keyword);
The log within the function returns my desired value, but the log after the function returns undefined, even though as far as I can tell, it should also return the value that was given to it within the function. I did not declare it within the function, so why does it's value expire after the function?
The value to "keyword" is assigned in some kind of callback function as it seems in your example. So if you run your code, the callback function will not be executed immediately, so no value is assigned to "keyword". It will be executed later, when your chrome extensions fires the callback function, you passed to "sendMessage".
But your console.log will be executed immediately and "keyword" is like it was initialized - undefined.

Javascript variable declaration, why is this legal? [duplicate]

This question already has answers here:
What is the (function() { } )() construct in JavaScript?
(28 answers)
Closed 8 years ago.
I just encountered this variable declaration syntax for the first time.
var myVar = (function() {
return 1;
})();
My 2 main questions are..
What is it called, and why is it legal?
Forgive me if this question has been asked before, I tried searching around but I have no idea what this notation is called so I wasn't able to find anything.
Also, I should add, what is the function of the 2 sets of parentheses? The first of which encloses the function, the second of which is empty.
Self executing functions are typically used to encapsulate context and avoid name collusions. Any variable that you define inside the (function(){..})() are not global.
The following code:
var same_name = 1;
var myVar = (function() {
var same_name = 2;
console.log(same_name);
})();
console.log(same_name);
produces this output:
1
2
By using this syntax you avoid colliding with global variables declared elsewhere in you javascript code.
I am not sure what this is called, other than defining an anonymous function and immediately invoking it.
It is perfectly legal, because
Defining an anonymous function is legal.
Invoking it and assigning the return value is also legal.
The end result is that myVar = 1.
This is an anonymous function (also called lambda function) that is being executed immediately with its return value (1) being assigned to a variable (myVar). It's legal because the specification says it is. It is a very common feature in many languages.

Categories