when to use var? [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Javascript: is using ‘var’ to declare variables optional?
how come in this code example below when i put var before the variables it does not work, however if i remove the var it works? i thought you had to use var when you were creating new variables.
function myfunction () {
if (document.getElementById('ramyes').checked) {
var itischecked = "yes"
} else if (document.getElementById('ramno').checked) {
var itischecked = "no"
}
}
function display () {
myfunction()
if (itischecked == "yes") {
alert ("it sure is");
} else if (itischecked == "no") {
alert ("it is not");
}
}

If you use var, the variable is only visible inside the current function (it's a local variable). If you don't use var when first setting the variable, it creates a global variable, which is visible to all functions.
Defining global variables by just setting them is usually frowned upon because most of the time you want local variables (in your case you should return your "itischecked" value from the function, instead of storing it in a global variable), and setting a variable without var looks like a mistake. It is also an error in strict mode (which everybody should use, always). To explicitly define a global variable in (browser) JS, use window.variableName, or var in the global scope (outside any functions).
But before you do that, think carefully whether that's a good idea. The more global variables you have, the higher the chance you will get a name collision when multiple scripts use the same variable name.

You should use var when you create a variable, but if you want to use the same variable in two functions, the variable has to be created in a scope outside both functions:
var itischecked;
function myfunction () {
if(document.getElementById('ramyes').checked) {
itischecked = "yes"
} else if(document.getElementById('ramno').checked) {
itischecked = "no"
}
}
function display () {
myfunction();
if (itischecked == "yes") {
alert ("it sure is");
} else if (itischecked == "no") {
alert ("it is not");
}
}
If you create a variable inside a function, that becomes a local variable. It is only visible inside that function, and goes away when you return from the function.
In your case you should rather use the return value of the function instead of putting a value in a variable. That way it is easier to follow how the data flows in the program, and you don't need to create a global variable:
function myfunction () {
if(document.getElementById('ramyes').checked) {
return "yes"
} else if(document.getElementById('ramno').checked) {
return "no"
}
}
function display () {
var itischecked = myfunction();
if (itischecked == "yes") {
alert ("it sure is");
} else if (itischecked == "no") {
alert ("it is not");
}
}

Just to add to the previous answer that suggests you shouldn't create global variables: to avoid doing so, you need in some way to make a larger scope so that variables can be shared between your two functions. That's where the var comes. For instance:
function myProgramme() {
var itischecked;
function myfunction() {
if (document.getElementById('ramyes').checked) {
itischecked = "yes"
}
else if (document.getElementById('ramno').checked) {
itischecked = "no"
}
}
function display() {
myfunction()
if (itischecked == "yes") {
alert("it sure is");
}
else if (itischecked == "no") {
alert("it is not");
}
}
}​
(Although in your specific example you could more simply have myfunction pass itischecked to display as a return value.)

Related

can't set variable to a outer function [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 6 years ago.
I can't seem to be able to set this.chkOK inside my ajax function. I'm sorta clueless how I go about doing this so I thought maybe calling validateFields.call(this) should of fixed my problem but I found out that wasn't the case. So I'm sorta lost what to do for my next step. I don't want to set this to a global variable unless I have to. I'm trying to set this.chkOK = true
function validateFields() {
this.chkOK = null;
this.username = function() {
if(FS.gID('username').value.length >= 2) {
var user = FS.gID('username').value;
//Make sure that the username doesn't already exist
FS.ajax('/server/chkUser.php?user='+user,'GET',function(){
validateFields.call(this);
if(xmlText == 0) {
this.chkOK = true;
alert("This user doesn't exist.");
}
else if(xmlText == 1) {
alert("Theres already a user with this username");
this.chkOK = false;
}
});
}
else {
alert("empty");
this.chkOK = false;
}
alert(this.chkOK);
}
}
The value of this in your example is NOT the function inside which it's declared, like you assume in your code.
If you simply use var chkOK = null; instead of this.chkOK = null; it should start to work.
It is because this inside the FS.ajax is not the same with this you intended to work with. this in FS.ajax means this of FS
You may assign this into another variable and use it inside FS.ajax. For example,
Note: Unless you know the reason why you put this.chkOk inside the function (such as expected validateFields be invoked by call or
apply) this is global object (which you don't want to) or
undefined in strict mode which will cause the code to fail
function validateFields() {
this.chkOK = null;
// ** assign this to that. So you can reference it inside FS.ajax **
var that = this;
this.username = function() {
if(FS.gID('username').value.length >= 2) {
var user = FS.gID('username').value;
//Make sure that the username doesn't already exist
FS.ajax('/server/chkUser.php?user='+user,'GET',function(){
validateFields.call(this);
if(xmlText == 0) {
that.chkOK = true; // use `that` instead of `this`.
alert("This user doesn't exist.");
} else if(xmlText == 1) {
alert("Theres already a user with this username");
that.chkOK = false; // use `that` instead of `this`
}
});
} else {
alert("empty");
this.chkOK = false;
}
alert(this.chkOK);
}
}

Calling a variable variable as a function in jquery

Just like in the PHP I need a variable variable.
I`m getting a data-type from the html and that variable is actually a function in the js code.
And I get it I need to call it.
Every time its different, so I don`t know which one exactly is.
if (e.which == 114 || e.which == 116) {
var action = $('.active').data("action");
action();
}
function testing() {
alert('yes');
}
Here the function name is testing.And the variable action is holding it.
How I`m suppose to call it ?!
I remember that there was a easy syntax for that,but I cant find it.
Thanks
You could extract the value and use eval().
<div id="something" data-action="alert('test')">SOME DIV</div>
$(document).ready(function() {
var $myObject = $("#something");
var action = $myObject.data('action');
$myObject.click(function() {
eval(action);
});
});
Try it yourself on jsfiddle
However, eval is evil
It depends on the object which holds the function. For the global scope use : window[action](). Otherwise, replace window with the name of your object : myObject[action](). However, this solution is not suitable for functions declared inside a private scope :
function f(fnName) {
function a() { alert('a') };
function b() { alert('b') };
fnName(); // error
}
In this case, you could use eval like this (⚠ keep control over inputs ⚠) :
function f(fnName) {
function a() { alert('a') };
function b() { alert('b') };
eval(fnName)();
}
Otherwise you could wrap them inside an object like so :
function f(fnName) {
var wrapper = {};
wrapper.a = function () { alert('a') };
wrapper.b = function () { alert('b') };
wrapper[fnName]();
}
f('a'); // alerts "a"
f('b'); // alerts "b"

best way to toggle between functions in javascript?

I see different topics about the toggle function in jquery, but what is now really the best way to toggle between functions?
Is there maybe some way to do it so i don't have to garbage collect all my toggle scripts?
Some of the examples are:
var first=true;
function toggle() {
if(first) {
first= false;
// function 1
}
else {
first=true;
// function 2
}
}
And
var first=true;
function toggle() {
if(first) {
// function 1
}
else {
// function 2
}
first = !first;
}
And
var first=true;
function toggle() {
(first) ? function_1() : function_2();
first != first;
}
function function_1(){}
function function_2(){}
return an new function
var foo = (function(){
var condition
, body
body = function () {
if(condition){
//thing here
} else {
//other things here
}
}
return body
}())`
Best really depends on the criteria your application demands. This might not be the best way to this is certainly a cute way to do it:
function toggler(a, b) {
var current;
return function() {
current = current === a ? b : a;
current();
}
}
var myToggle = toggler(function_1, function_2);
myToggle(); // executes function_1
myToggle(); // executes function_2
myToggle(); // executes function_1
It's an old question but i'd like to contribute too..
Sometimes in large project i have allot of toggle scripts and use global variables to determine if it is toggled or not. So those variables needs to garbage collect for organizing variables, like if i maybe use the same variable name somehow or things like that
You could try something like this..: (using your first example)
function toggle() {
var self = arguments.callee;
if (self.first === true) {
self.first = false;
// function 1
}
else {
self.first = true;
// function 2
}
}
Without a global variable. I just added the property first to the function scope.
This way can be used the same property name for other toggle functions too.
Warning: arguments.callee is forbidden in 'strict mode'
Otherwise you may directly assign the first property to the function using directly the function name
function toggle() {
if (toggle.first === true) {
toggle.first = false;
// function 1
}
else {
toggle.first = true;
// function 2
}
}

How do I pass variables into a JavaScript function?

Is it possible to pass variables into a js function? See code:
function checkStartPrice (){
if ($('#StartingPrice')[0].value.length == 0){
alert("The 'Starting Price' cannot be left empty!");
return false;
} else {
var BuyItNowPrice = parseFloat($('#BuyItNowPrice').val());
var StartingPrice = parseFloat($('#StartingPrice').val());
var Reserve = parseFloat($('#Reserve').val());
if((BuyItNowPrice <= StartingPrice) && (StartingPrice > 0)){
alert("The 'Buy It Now' price must be higher...");
return false;
}
if((Reserve <= StartingPrice) && (StartingPrice > 0)){
alert("Your 'Reserve Price' must be higher...");
return false;
}
return true;
}
}
I'd like to take the var BuyItNowPrice = parseFloat($('#BuyItNowPrice').val()); etc and place them outside the function, then call them in.
The reason is I have 3 of these functions so these 3 variables (BuyItNowPrice, StartingPrice, Reserve) are repeated 9 times, 3 in each function.
Is there a way of doing this?
Any help would be Greatly Appreciated, Thanks
A simple example of passing variables into a function is below. When you declare a function, you can also declare some arguments for the function by putting them inside the function() brackets. You can use whatever letter/name you like to represent the arguments - when you CALL the function, you pass through the variables.
// put arguments into the function declaration - a,b,c
function myfunction(a, b, c) {
// use these arguments within the function
return (a+b+c);
}
// declare the variables outside the function
var first_variable = 1;
var second_variable = 2;
var third_variable = 3;
// returns '6'
myfunction(first_variable, second_variable, third_variable);
You can make these variables global by taking it out of the fn
BuyItNowPrice = parseFloat($('#BuyItNowPrice').val());
StartingPrice = parseFloat($('#StartingPrice').val());
Reserve = parseFloat($('#Reserve').val());
fn1(){}
fn2(){}
fn3(){}
Now you can use these variables in all the three functions.
Make those three variables global. To make them global you just need to have those variables outside any function. In javascript if any variable which doesnot appear in any functions, then its scope is global.
To answer your first question, Yes it is possible to pass variables to functions in javascript. you can just send the variables as arguments to the function.
sample: function myfucn(a, b) { //you implementation here.}

Break out of function within enumarable.each iteration

I have a Prototype class - within the class i call a function and within this function i do en enumerable.each iteration. If an element within this iteration fails a check i then call another function which then re-calls this same function later. Can i break within this iteration so not only the iteration is ended but nothing else within the function is called.
Say with this code i wouldnt want the console.log to be called if elm.something == 'whatever'. Obviously i could set a variable and then check for this after the function but is there something else that i should be doing?
myFunction: function(el){
el.each(function(elm){
if(elm.something == 'whatever'){
this.someOtherFunction(elm);
}
},this);
console.log("i dont want this called if elm.something == 'whatever'");
}
Just to be clear, in this case the console.log is just placeholder code for the beginnings of some additional logic that would get executed after this loop
You answered it yourself
"Obviously i could set a variable and then check for this after the function"
In this case, you're basically looking to not call the console.log even if elm.something == 'whatever' for a single 'elm'
myFunction: function(el){
var logIt = true;
el.each(function(elm){
if(elm.something == 'whatever'){
logIt = false;
this.someOtherFunction(elm);
}
},this);
logIt && console.log("i dont want this called if elm.something == 'whatever'");
}
The simplest way would be to avoid using each() and instead rewrite using a for loop:
myFunction: function(el){
for(var i in el) {
var elm = el[i];
if(elm.something == 'whatever'){
return this.someOtherFunction(elm);
}
}
console.log("i dont want this called if elm.something == 'whatever'");
}

Categories