Desqeh
Developer
Basic JavaScript code everyone should know.
The = and == and === operators
The = operator assigns a value to something, either a interger or string
The other operators: !=, !==, &&, ||, ++, --
!= is used when you want to values NOT to equal each others values
The loops, While and For
The While loop keeps executing until a condition is false
Although I have never seen it used before this is a code snippet I found in a book
The = and == and === operators
The = operator assigns a value to something, either a interger or string
- Code:
function var() {
var x=0; //Assaigns x to the interger 0
var y="0"; //Assiagns y to the string "0"
//the above 2 are very different, don't be fooled by the same number in both
}
- Code:
function var() {
if (x==0) { //Tests if x EQUALS 0
if (y=="0") { //Tests if y EQUALS 0
document.write("Both Variable Are Correct");
}
}
}
- Code:
function var() {
if (x===y) {
document.write("The variables are wrong!");
}
}
The other operators: !=, !==, &&, ||, ++, --
!= is used when you want to values NOT to equal each others values
- Code:
function var() {
if (x!=y) { //Tests if x DOESN'T equal y
document.write("The 2 values don't equal each other's values");
}
}
- Code:
function var() {
if (x==0 && y=="0") { //Test if x==0 AND y=="0"
document.write("The Variables are correct");
}
}
- Code:
function var() {
if (x==0 || y=="0") { //Tests wether x==0 OR y=="0"
document.write("At Least one variable is correct");
}
}
- Code:
function var() {
x++; //x+1
}
- Code:
function var() {
x--; //x-1
}
The loops, While and For
The While loop keeps executing until a condition is false
- Code:
while (x<10) {
x++;
}
- Code:
for (x==0;x<10;x++;) {
document.write("x equals " + x);
}
- Code:
<html>
<body>
<script type="text/javascript">
function change() {
document.getElementById("p").innerHTML="Hello"; //This gets the elements name then innerHTML changes it
}
</script>
<p id="p" onclick="change()">Click me to change the message</p>
</body>
</html>
Although I have never seen it used before this is a code snippet I found in a book
- Code:
<html>
<head>
<style id="normal">
background-color:#B0E0E6;
</style>
<style id="green">
background-color:#008000;
</style>
</head>
<body>
<input type="button" onclick="setStyle('green')" value="Green Background">
</body>
</html>