Javascript variables

Javascript variables

Learn how to declare variables, assign them values and make use of them in your script


Variables in Javascript are used to store certain values that can later be used and modified.


Declaration


To use variables one must first declare it with a unique identifier such as "variable1" or "num1". This can be done in 2 different ways in javascript:


var variable1;      
num1;      

You can either declare a variable using "var" if you wish for its scope to remain local, meaning it can only be used within the current block of code, or "var" can be omitted if you wish for it to be accessible throughout your script.


var num1=1;      
num2=2;      
function(){      
 var num1=2; //num1 is equal to 2 at this point, but will still be equal to 1 outside this function  
 num2=1; //num2 is equal to 1 both inside and outside this function  
}      


Assignment


In Javascript there is no need to declare the data type of the variable, you can simply declare it with any value and it will recognize the data type, as long as it is valid.


var num1=45;      
var string1="test string";      
var double1=34.1;      
var bool1=false;      

Variables in Javascript can also be declared using ternary operators, these are essentially similar to if else statements. Based on a boolean input, they assign one of 2 values to a variable.


var num1;      
var decide=true;      
if(decide){      
 num1=1;      
}      
else{      
 num1=2;      
}      
num1 = (decide) ? 1:2; // this will result in the same value as the if else statement  



Variables in Javascript can be used in a number of ways. They can be combined to form another variable, they can be used to set HTML elements, they can store data about the interface for future use and much more, here are some examples of how to use Javascript variables.


var name="John";  
alert(name); // displays an alert box with the value of "name"      
document.getElementById("name_span").innerHTML=name; //changes the inner HTML of an element with the ID "name_span" to the value of name  
var fullName=name + " Doe"; // appends " Doe" on to the end of name and assigns it to an new variables "fullName"  



Christopher Thornton@Instructobit 4 years ago
or