Identify and Understand some of the Writing Style in JavaScript


Javascript Syntax something like C or Java language. Javascript is case sensitive, meaning that lowercase and uppercase letters are different.
Each line of javascript code separated the new line or it could be a semicolon (;)
Comments in javascript starting with / / or written between / * and *

Variable in javascript can be started with a letter or underscore (_) or a dollar sign ($).
Example: count_hits, _age

Declaration of variables :
  • You can declare using var, example: var x = 5, this is a local and global (can be accessed by all functions) 
  • Or immediately declared without var, x = 5
Arithmetic operators are operators for mathematical operations

OperatorDefinitionExamples
+Addition5+4=9
-Subtraction4-3=1
*Multiplication3*5=15
/Division
%Modulus (division remainder)5%2=1
++Increment
--Decrement

Examples :
<script>
var x = 4;
var y = 2;
z = x + y;
alert(z);
</script>

Operator Assignment
Like most other programming languages​​, to give value to a variable using the equals sign =
Here is the brevity of operator writing :
Shorthand OperatorMeaning
x += yx = x + y
x -= yx = x - y
x *= yx = x * y
x /= yx = x / y

Example :
<script>
 var x = 4;
 var y = 2;
 x -= y
 alert(x);
</script>

Comparison Operators :
Useful to compare the value of a variable :

OperatorDefinitionExample
==equal tovar1 == “Desrizal”
!=not equalx != y
>greater thanx > y
<less thanx < 6
>=greater than or equal tox>= y
<=less than or equal tox < 5

Example :
<html>
<head>
<script>
var x = 4;
var y = 2;
if(x > y){
alert("x greater then y");
}
</script>
</head>
<body>
</body>
</html>

Logical Operators :

OperatorDescriptionExample
&&and(x < 10 && y > 1) is true
||or(x==5 || y==5) is false
!not!(x==y) is true

Example :
<script>
var x = 76;
if(x >= 80){
alert("Value = A");
}else if(x >= 70 && x < 80){
alert("Value= B");
}else if(x >= 60 && x < 70){
alert("Value= C");
}else{
alert("Value= D");
}
</script>
Previous
Next Post »