What is the different between a parameter and a local variable? - javascript

Apologies for what must seem like a very stupid question.
I'm currently working through codecadamy, and this is throwing me off:
var greeting = function(name) {
name = "sausage";
console.log(name);
};
greeting(name);
I understand that I will get sausage
Why don't I just write var name = "sausage";? What is the difference?

The name in function(name) is a parameter. That is, it is used to pass data into the function. But, parameters are local variables. Assigning a value to name inside the function is a little strange though. I would assume you want to do something like this:
var greeting = function(name) {
console.log(name);
};
greeting("sausage");
In this version of the code you are passing the value "sausage" into the function via the parameter name. This is useful because you can call the function many times and each time the function may print a different value depending on what you pass.

In your function definition:
function(name) {
name is already being declared. It is a parameter for the function. If you want to change name, you can, but you don't need to use var to declare it as a new variable.
On the other hand, if you wanted to add, say, flavor, you should use var then since it is not already defined.
var flavor = 'savory';
In this case, flavor is a local variable and name is a parameter. A parameter is a type of local variable that is declared with the function declaration, but a local variable isn't necessarily a parameter because it may be declared elsewhere in the function.

Parameters are a general programming construct and are necessary to do anything sane in the world programming (dealing with masses of global variables is not sane.
var name would declare a new variable in the function scope that would override the value of the parameter name, so you would not be able to use the parameter anymore.
The CodeAcadamy example is a bit strange because it's rare that you want to override a parameter's value -- especially before you have used it.

Technically, there is no real difference.
Without giving you the huge background here, you have to understand that in the underlaying implementation, a special object (not a javascript object, on C/C++ level) is formed which is called Activation Object (ES3) or Lexical Environment Record (ES5).
However, this hash / object structure is used to store
variables declared by var
formal parameters
function declarations
As you can see, both var variables and parameters are stored in this structure.
This construct is most likely used to have somewhat default values for not passed in arguments. In a real world example, this would probably look more like
var greeting = function( name ) {
name = name || 'default';
console.log( name );
};
greeting('john'); // 'john'
greeting(); // 'default'

Related

How the parameters affect the variable values in a function?

I'm currently studying JavaScript and I have a question with function parameters. I have this function:
//Function 1
let from = 'Ann';
function showMessage(from, text) {
from = 'Jane';
alert(from + ' says ' + text);
}
showMessage(from, 'Hello');
alert(from);
//Function 2
let userName = 'John';
function showMessage1(){
userName = 'Bob'
alert('Hello '+ userName);
}
alert(userName);
showMessage1();
alert(userName);
I can understand that in the Function1 showMessage(from, 'Hello'); displays Jane says Hello and alert(from) displays Ann because when I pass the arguments, the function creates a local copy of the values that I passed. I had read that when you have a same-named global and local variable, local shadows global and I think that it happens in Function1 and that's why I get 'Ann' in the last line.
Then since I don't pass on any argument to the Function2, it doesn't create local copy and that's why the value of userName is equal Bob and it is displayed in the last line.
EDIT: I rephrase my question: Why do they behave differently (one does not overwrite the global variable and the other does) if the only difference that I see is that one is passed parameters and the other is not?
It's because you haven't declared a local variable userName inside showMessage1. Variables are declared with one of the keywords var, let or const (I won't go into the differences here, although they are important). If you did this, then you would get the expected result:
//Function 1
let from = 'Ann';
function showMessage(from, text) {
from = 'Jane';
alert(from + ' says ' + text);
}
showMessage(from, 'Hello');
alert(from);
//Function 2
let userName = 'John';
function showMessage1(){
let userName = 'Bob'
alert('Hello '+ userName);
}
alert(userName);
showMessage1();
alert(userName);
In your snippet, because there is no let (or var or const) before the assignment userName = 'Bob', there is no local variable called userName to assign to, so instead it assigns to the userName variable in the enclosing scope - here the global scope. This is why, in your example, the global userName is overwritten, but it isn't in the version above.
EDIT: I rephrase my question: Why do they behave differently (one does not overwrite the global variable and the other does) if the only difference that I see is that one is passed parameters and the other is not?
To answer this explicitly: the difference isn't to do with being passed parameters or not. The difference is between the assignment inside the function being to a local variable or a non-local (in this case, global) one. In your showMessage, the assignment is to from, which is by definition a local variable because it's a function parameter. In your original showMessage1, the assignment to userName was to the non-local variable from the enclosing (global) scope, since no userName is declared in the function's scope. By declaring the variable with let (or var or const), a local variable of that name is created inside the function, which is then assigned to without affecting the same-named ("shadowed") variable in the enclosing scope.
A very shorthand rule set is that JS do not decides between "byValue" and "byReference". At least not as other Programming languages do that. Everything which is a primitive type is passed by Value ( strings bools and numbers etc). Compund variables e.g. OBJECTS and ARRAYS are passed by reference. And that is it. There is no keyword to tell to act different. If you want to put a Array or Object by Value then create a copy of it. If you want to have a primitive type by reference - create a object of the primitive type. Type less languages like Javascript or REXX and some others handles such things different as languages which relay on a compiler. The compiler HAS to know whats to do exactly. In a scripting language we have a nice interpreter and he can decide in the last second whats right and whats wrong. :) .oO(and sometimes creates some gray hairs by acting like that ;)

How JavaScript assigns `name` attribute of function?

In JavaScript, when I define function like this
function aaa(){}
I can later access the name by name attribute:
aaa.name
which will return
"aaa"
However, when I define function via var, it technically should be anonymous function without name attribute:
var aaa=function(){}
But instead it assumes that aaa is function name and assigns it to name attribute:
aaa.name
will also return
"aaa"
How JavaScript decides what should be the name, especially considering the fact that assignments could use more complicated scenarios:
var aaa=bbb=function(){}
or
var aaa=arr[0]=function(){}
?
Javascript declares the name variable of the function by taking the left-hand side argument that is equal to the function, which is 'aaa' in all basic cases. In the first complex definition, you declared state above Javascript will take the variable ab and assign it to a function making the name 'ab'. In the final example, you provided it sets the function equal to a pointer in memory, which is not a defined variable, this sets the name property to an empty string because arr[0] is not a variable name but a pointer to memory.
Here is a JSFiddle displaying this.
Something like this:
Inferred function names
Variables and methods can infer the name of an anonymous function from
its syntactic position (new in ECMAScript 2015).
var f = function() {};
var object = {
someMethod: function() {}
};
console.log(f.name); // "f"
console.log(object.someMethod.name); // "someMethod"
Read the entire blog. It will clear all your queries.

Get name of instance of a class within the class

Here is what I want:
var Validator = function () {
this.do = function () {
alert(INTANCENAME); /// SHOULD BE 'FOO'
}
}
var FOO = new Validator().do();
Is it possibe to implement in Javascript?
The truth is there is no point of doing that, the only way I can hardly think is to loop all window or scope objects and check some kind of equality with the current object, something like
this.do = function () {
for(var key in window) {
if(this === window[key]) {
alert(key);
}
}
};
In order to work call it after you assign it.
var FOO = new Validator();
FOO.do();
Another issue that can come up is that an instance (a reference) can be stored in various variables so maybe will not get what you expect.
The literal answer to your question would be:
Use (new Error()).stack to get information on the line and the function where the do() method was called.
Use JS parser (e.g. Esprima) to find out what variable it was called on (if any, the method itself might be assigned to a variable).
I do not recommend doing this though.
There's no way to directly do what you're asking for here. Objects themselves are not in any defined by their matching variable name - in fact it's possible to have objects that exist that are not directly assigned to a variable, and multiple variables assigned to the same object.
The javascript interpreter uses our variable names as identifiers to help with the code execution, but once it's running the variable name makes no difference to the running javascript program, as it's probably been reduced to a memory reference by the time it's executing, completely separated from the original code that you wrote.
Edit: Answer by yannis does kind of simulate this, but it relies on working with variables available in a specific scope - what I ment was that there's no direct way to do this from within the object itself as per your example in the question.

Pass a function reference that has a variable as its name

I have the following javascript method:
function 123_test_function(){
}
The function is generated by java and sent to the client. The 123 is the id of the component so it could change. i.e I can have another function called 111_test_function()
I want to pass this function as a reference.
So I need to create the reference
var 123_test_function = function 123_test_function(){
}
In another js file inside an object I have a function that needs to use the 123_test_function reference like so:
useFunction(123_test_function);
The problem I'm having is which the 123 part of the function.
In this object I have a variable(uniqueID) which has the number at the beginning of the function.
I need the function call to be something like:
useFunction(uniqueID+"_test_function");
This doesn't seem to pass a function instead it passes a string.
Am I doing something wrong?
For one, identifiers (such as function names) cannot begin with a digit.
To solve your problem, use an object, like this:
// 1. define an object to hold all your functions
var allFunctions = {};
// 2. store any function with a unique string as the ID
allFunctions['123_test_function'] = function () {
// whatever
};
// 3. call the function
allFunctions['123_test_function']();
allFunctions[uniqueID + '_test_function']();
Objects are associative arrays. They store key/values pairs, so they do exactly what you want here.
Note that functions don't need a name in JavaScript, so I did not use on in step 2.
If the function is defined as global one, it will be a member of global object (window in case of browsers). Hence you can just do window['id_'+uniqueID+'_test_function'] to access your function
useFunction(window['id_'+uniqueID+'_test_function'])
(Identifiers cannot begin with numbers in JavaScript so I added the 'id_' prefix. You can of course change it to your liking.)
function test_function(number){
if(number == 1)
{
return function() {}
}
if(number == 2)
{
return function() {}
}
}
call the function like this
var func = test_function(1)
func();
As a couple of people have correctly pointed out, a function (or indeed variable) name cannot begin with a numeric. Also this syntax is wrong:
var 123_test_function = function 123_test_function(){
}
The correct syntax would be:
var 123_test_function = function() {
};
...although it should also be noted that the effect of this is exactly the same as a "traditional"
function 123_test_function() {
}
...declaration, in the context of the window object - since window is effectively the global scope of a JS environment in a browser, it doesn't matter how you define the functions, they will always be accessible from anywhere. Understanding exactly what each method of declaring a function means in Javascript is important - luckily, Douglas Crockford to the rescue once again...
People have suggested various methods for calling your named functions from the context of a string, which is basically attempting to use "variable variable" syntax, a subject that has been discussed on SO and elsewhere at length. The eval() approach should be avoided wherever possible - if you find yourself needing an eval() chances are you went wrong somewhere a while back. #Tomalak has the right idea with a collection of functions held in an object, but this still needs the slightly messy string approach to reference things that are actually being accessed by a numeric ID. The collection approach has the advantage of not cluttering up the window object with what are likely to be single/zero use members.
But the way I see it, all you actually need here is an indexed array of functions, where all you need is the numeric index in order to access them. I suggest you create your functions like this:
// Do this once at the top of your JS
var test_functions = [];
// Now, for each function you define:
test_functions[123] = function() {
// Do stuff here
};
// And when you need to call the functions:
var funcId = 123;
test_functions[funcId]();

Accessing variables from other functions without using global variables

I've heard from a variety of places that global variables are inherently nasty and evil, but when doing some non-object oriented Javascript, I can't see how to avoid them. Say I have a function which generates a number using a complex algorithm using random numbers and stuff, but I need to keep using that particular number in some other function which is a callback or something and so can't be part of the same function.
If the originally generated number is a local variable, it won't be accessible from, there. If the functions were object methods, I could make the number a property but they're not and it seems somewhat overcomplicated to change the whole program structure to do this. Is a global variable really so bad?
I think your best bet here may be to define a single global-scoped variable, and dumping your variables there:
var MyApp = {}; // Globally scoped object
function foo(){
MyApp.color = 'green';
}
function bar(){
alert(MyApp.color); // Alerts 'green'
}
No one should yell at you for doing something like the above.
To make a variable calculated in function A visible in function B, you have three choices:
make it a global,
make it an object property, or
pass it as a parameter when calling B from A.
If your program is fairly small then globals are not so bad. Otherwise I would consider using the third method:
function A()
{
var rand_num = calculate_random_number();
B(rand_num);
}
function B(r)
{
use_rand_num(r);
}
Consider using namespaces:
(function() {
var local_var = 'foo';
global_var = 'bar'; // this.global_var and window.global_var also work
function local_function() {}
global_function = function() {};
})();
Both local_function and global_function have access to all local and global variables.
Edit: Another common pattern:
var ns = (function() {
// local stuff
function foo() {}
function bar() {}
function baz() {} // this one stays invisible
// stuff visible in namespace object
return {
foo : foo,
bar : bar
};
})();
The returned properties can now be accessed via the namespace object, e.g. ns.foo, while still retaining access to local definitions.
What you're looking for is technically known as currying.
function getMyCallback(randomValue)
{
return function(otherParam)
{
return randomValue * otherParam //or whatever it is you are doing.
}
}
var myCallback = getMyCallBack(getRand())
alert(myCallBack(1));
alert(myCallBack(2));
The above isn't exactly a curried function but it achieves the result of maintaining an existing value without adding variables to the global namespace or requiring some other object repository for it.
I found this to be extremely helpful in relation to the original question:
Return the value you wish to use in functionOne, then call functionOne within functionTwo, then place the result into a fresh var and reference this new var within functionTwo. This should enable you to use the var declared in functionOne, within functionTwo.
function functionOne() {
var variableThree = 3;
return variableThree;
}
function functionTwo() {
var variableOne = 1;
var var3 = functionOne();
var result = var3 - variableOne;
console.log(variableOne);
console.log(var3);
console.log('functional result: ' + result);
}
functionTwo();
If another function needs to use a variable you pass it to the function as an argument.
Also global variables are not inherently nasty and evil. As long as they are used properly there is no problem with them.
If there's a chance that you will reuse this code, then I would probably make the effort to go with an object-oriented perspective. Using the global namespace can be dangerous -- you run the risk of hard to find bugs due to variable names that get reused. Typically I start by using an object-oriented approach for anything more than a simple callback so that I don't have to do the re-write thing. Any time that you have a group of related functions in javascript, I think, it's a candidate for an object-oriented approach.
Another approach is one that I picked up from a Douglas Crockford forum post(http://bytes.com/topic/javascript/answers/512361-array-objects). Here it is...
Douglas Crockford wrote:
Jul 15 '06
"If you want to retrieve objects by id, then you should use an object, not an
array. Since functions are also objects, you could store the members in the
function itself."
function objFacility(id, name, adr, city, state, zip) {
return objFacility[id] = {
id: id,
name: name,
adr: adr,
city: city,
state: state,
zip: zip
}
}
objFacility('wlevine', 'Levine', '23 Skid Row', 'Springfield', 'Il', 10010);
"The object can be obtained with"
objFacility.wlevine
The objects properties are now accessable from within any other function.
I don't know specifics of your issue, but if the function needs the value then it can be a parameter passed through the call.
Globals are considered bad because globals state and multiple modifiers can create hard to follow code and strange errors. To many actors fiddling with something can create chaos.
You can completely control the execution of javascript functions (and pass variables between them) using custom jQuery events....I was told that this wasn't possible all over these forums, but I got something working that does exactly that (even using an ajax call).
Here's the answer (IMPORTANT: it's not the checked answer but rather the answer by me "Emile"):
How to get a variable returned across multiple functions - Javascript/jQuery

Categories