Saturday, 15 April 2017

Variable and Operator


JavaScript Comments

  • Single line comments start with //.
  • Multi line comments start with /* and end with */.

JavaScript Variables

Rules for JavaScript variable names:
  • Variable names are case sensitive (y and Y are two different variables)
  • Variable names must begin with a letter or the underscore character
Note: Because JavaScript is case-sensitive, variable names are case-sensitive.You can declare JavaScript variables with the var statement:
x=5;
carname="Volvo";
have the same effect as:
var x=5;
var carname="Volvo";

JavaScript Operators

Operator
Description
Example
Result
+
Addition
x=y+2
x=7
-
Subtraction
x=y-2
x=3
*
Multiplication
x=y*2
x=10
/
Division
x=y/2
x=2.5
%
Modulus (division remainder)
x=y%2
x=1
++
Increment
x=++y
x=6
--
Decrement
x=--y
x=4

JavaScript Assignment Operators

Operator
Example
Same As
Result
=
x=y

x=5
+=
x+=y
x=x+y
x=15
-=
x-=y
x=x-y
x=5
*=
x*=y
x=x*y
x=50
/=
x/=y
x=x/y
x=2
%=
x%=y
x=x%y
x=0

The + Operator Used on Strings

The + operator can also be used to add string variables or text values together.
To add two or more string variables together, use the + operator.
txt1="What a very";
txt2="nice day";
txt3=txt1+txt2;
After the execution of the statements above, the variable txt3 contains "What a verynice day".
To add a space between the two strings, insert a space into one of the strings:
txt1="What a very ";
txt2="nice day";
txt3=txt1+txt2;
or insert a space into the expression:
txt1="What a very";
txt2="nice day";
txt3=txt1+" "+txt2;
After the execution of the statements above, the variable txt3 contains:
"What a very nice day"

Adding Strings and Numbers

The rule is: If you add a number and a string, the result will be a string!

Example

x=5+5;
document.write(x);

x="5"+"5";
document.write(x);

x=5+"5";
document.write(x);

x="5"+5;
document.write(x);

Comparison Operators

Operator
Description
Example
==
is equal to
x==8 is false
===
is exactly equal to (value and type)
x===5 is true
x==="5" is false
!=
is not equal
x!=8 is true
is greater than
x>8 is false
is less than
x<8 is true
>=
is greater than or equal to
x>=8 is false
<=
is less than or equal to
x<=8 is true

Logical Operators

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

Conditional Operator

Syntax

variablename=(condition)?value1:value2 

Example

greeting=(visitor=="PRES")?"Dear President ":"Dear ";
If the variable visitor has the value of "PRES", then the variable greeting will be assigned the value "Dear President " else it will be assigned "Dear".

No comments:

Post a Comment

Please write your view and suggestion....