bdalina
bdalina

Reputation: 523

How to change a variable declare inside a function in javascript

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

Upvotes: 1

Views: 106

Answers (4)

Bhargav Chudasama
Bhargav Chudasama

Reputation: 7165

try this one

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

Upvotes: 1

AlienHoboken
AlienHoboken

Reputation: 2800

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.

Upvotes: 2

mattn
mattn

Reputation: 7723

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

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

Upvotes: 2

Suresh Atta
Suresh Atta

Reputation: 121998

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"

Upvotes: 1

Related Questions