In a script (or program) we use constants and variables datas. The variables can change their values during program execution. These data are called 'variables
'.
- A variable is a name of a location in computer memory, used to store data.
In a script (or program) we use variables and constants datas. The variables can change their values The simplest way to use and refer to a variable is to write it. The name of the variable permits the access at its value and also can change the value if necessary.
var
or let
declarations:
var name ='Value'; //Sau let name ='Value';- Example:
<h4>Example JS variable</h4> <script> let str ='Some text'; document.write(str); </script>
The difference between var
and let
is scoping.
var
statement is known throughout whole scope or the function it is defined in, from the start of the function.var
you can define a variable globally, that can be called and modified in functions.let
statement is only known in the block it is defined in, from the moment it is defined onward.let
variable is not added to the global window object.<script> let xn = 1; if(xn ==1){ let xn =2; } document.write(xn); // 1 </script>
<script> var xn = 1; if(xn ==1){ var xn =2; } document.write(xn); // 2 </script>
There are several types of data that can be assigned to variables. The type of the value it determines the type of the variable.
var x = 8; var y = 7.95;
true
or false
.
var x = true; var y = false;
let x = ['ab', 78, 'xy']; alert(x[1]); // 78
var fun = function(){ return 'Value'; };
<script> var x; //now is undefined x = 5; //now is a number document.write(x); x = '<h4>MarPlo</h4>'; //now is a string document.write(x); </script>
Notice that the 'string' values (consisting of letters) are written between quotation marks (simples or doubles), and the 'number' can be written without quotation marks.
<script> //a function function f(){ var x ='val'; } document.write(x); //Error: x is not defined </script>
Constants are defined with the const
declaration.
Unlike variables, the value of a constant can not be changed and can not be redefined, its value remains the same, fixed.
const X = 'MarPlo'; //trying to change the value it results error in browser console X ='abc'; //redefining, it results error in browser console const X = 123;Like variables, constants are used by specifying their names, and it results its value.
<script> const TJC = 'JavaScript Tutorial - Constants'; document.write(TJC); </script>
<ul> <li>http://coursesweb.net/html/</li> <li>http://coursesweb.net/css/</li> </ul>
.some_class { display: list-item; }
var obj = { "courses": ["php", "javascript", "ajax"] }; var jsonstr = JSON.stringify(obj); alert(jsonstr); // {"courses":["php","javascript","ajax"]}
$strhtml = '<body><div id="dv1">CoursesWeb.net</div></body>'; $dochtml = new DOMDocument(); $dochtml->loadHTML($strhtml); $elm = $dochtml->getElementById("dv1"); echo $elm->nodeValue; // CoursesWeb.net