1

i have a function and a local variable declared inside it, i don't want to declare it as global because some functions are also using its default value

 function default()
 {
      var val="me";
      //others.....
 }

is there a way aside from this using prototyping

 function default(value)
 {
     var val=value;
     //others.....
 }

something like,

 default.prototype.val = "you";

re-constracting

4 Answers 4

2

No. It is not possible to declare a variable inside the function (var myVar) and then access it once the function has ended. This is because the variable is created within the function's lexical scope and is undefined outside of it. Here is some more info on how scoping works: https://scotch.io/tutorials/understanding-scope-in-javascript

As for your proposed solution default.prototype.val this does not work because default is a function and does not have properties or a prototype. This is something an object would have.

As others have indicated, you may pass in a variable or use default values, but it seemed your were asking about accessing a variable created inside the function and that is not doable. You need to return the value or pass in a variable which is modified by the function.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the links, i see a json object that might helps.
your link is very helpful!
2

function name(s) {
	return s || "me"
}

console.log(name())
console.log(name("you"))

Comments

1

You can use the default values to the arguments

function default(value ="you")
 {
     var val=value;
     //others.....
 }

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Default_parameters

usage will be something like this

default(); // value will be "you"
default("me"); value will be "me"

3 Comments

This is nice and it solves the current issue, but its not capable for a deeper purpose. like function default() { var val="me"; var childfunction= function() { var something= ''; } }
@bdalina What will be the problem ? I don't see any issue there
the function look like this function test(value, value2, value3, value4), the answer was to use object function test(value={}) where value {'val1':'asd', 'val2':'asfas',etc..}
1

try this one

function defaultfun (value="") {
  var val = "me";
  alert("new value:"+value+"\n old value:"+val);
}
defaultfun();
defaultfun("you");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.