Jump to content

how to write variables the correct way in your code? (javascript)


tastro

Recommended Posts

like this:

 

var time_now = new Date();

var time_now = time_now.getTime();

 

like this:

 

var time_now = new Date();

time_now = time_now.getTime();

 

like this:

 

time_now = new Date();

time_now = time_now.getTime();

 

or maybe like this?

 

var time_now = new Date();

var time_now = var time_now.getTime();

You only use 'var' when you initially declare the variable, not for every access to it.

 

Using a variable without declaring it w/ the var keyword does work, however it can have unintended consequences as it causes the variable to be in the global scope.

 

For example:

 

function loop10(){
   for (i=0; i<10; i++){
      alert('loop10 is on '+i);
   }
}

//main loop
for (i=0; i<5; i++){
   alert('main loop is on '+i);
   loop10();
}

 

 

vs

 

 

 

function loop10(){
   for (var i=0; i<10; i++){
      alert('loop10 is on '+i);
   }
}

//main loop
for (var i=0; i<5; i++){
   alert('main loop is on '+i);
   loop10();
}

 

one more thing... when i make a funcion.

 

is this correct?

 

function my_function_name(var t1,var t2){

 

}

 

or this one?

 

function my_function_name(t1,t2){

 

}

 

or somehow else?

 

function my_function_name(t1,t2){

var t1='';

var t2='';

}

also it should be all fine like this:

 

var time_now = new Date();

time_now = time_now.getTime();

 

Yes, that is the proper way.

 

 

or this one?

 

function my_function_name(t1,t2){

 

}

 

That is the proper way for function parameters.  You do not use var for those.  You also do not use var for object properties or array indexes, such as

var o={};
var o.abc='def'; //this is wrong.

 

You'd just do

var o={};
o.abc='def'; //this is correct

 

 

// Call Function
my_function_name(var1, var2);

//Create Variables
var var1= "Variables";
var var2 = "Joined";

// Note that the function call  can have different variable names the to the function itself ie var1 = t1 and var2 = t2 inside the called function.
function my_function_name(t1,t2){
var t3 = t1+" "+t2;
// popup will display "Variables Joined"
alert(t3);
}
</script>

 

creating t3 shows you how to join variables with the + sign and " " displays the gap between the variables or they would join together.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.