JavaScript
Operator | Operation | Expression | Result |
+ | Add | 2 + a | 4 |
- | Substract | 2 - a | 0 |
* | Multiply | 3 * a | 6 |
/ | Divide | 3 / a | 1.5 |
% | Modulus - division remainder | 7 % a | 1 |
++ | Increment - increase by 1 | a++ | 3 |
-- | Decrement - decrease by 1 | a-- | 1 |
Comparison Operators
Operator | Operation | Expression | Result |
== | Equal to | a == b | false |
!= | Not equal to | a != b | true |
<= | Less than equal to | a <= b | true |
>= | Greater than or equal to | a >= b | false |
< | Less than | a < b | true |
> | Greater than | a > b | False |
Assignment Operators
a = 1, b = 2, and c = 3.
Operator | Operation | Result |
= | a = b + c; | a = 5 |
+= | a += b; // equivalent to a = a + b | a = 3 |
-= | a -= b; // equivalent to a = a – b | a = -1 |
/= | a /= b; // equivalent to a = a / b | a = 0.5 |
%= | c %= b; // equivalent to c = c % b | c = 1 |
*= | a *= b; // equivalent to a = a * b | a = 2 |
Logical or Boolean Operators
In the table below the variables have the following values: a = 1 and b = 2.
Operator | Operation | Expression | Result |
&& | Logical and. Returns true only if both its first and second operands are evaluated to true. | a < 3 && b > 5 | returns false as b > 5 is false |
|| | Logical or. Returns true if one of the two operands are evaluated to true, returns false if both are evaluated to true. | a < 3 || b > 5 | returns true as a < 3 is true |
! | Logical not. Unary operator that simply inverts the Boolean value of its operand. | !(b>5) | returns true |
Bitwise operators in JavaScript
The table below summarizes the bitwise operators in JavaScript:
Operator | Usage | Result |
Bitwise AND | a & b | Returns 1 for each bit position where both operands are 1 |
Bitwise OR | a | b | Returns 1 for each bit position where either operand is 1 |
Bitwise XOR | a ^ b | Returns 1 for each bit position where either but not both are 1 |
Left shift | a << b | Shifts in binary fashion all bits one position to the left; discarding the left bit and filling the right bit with 0. |
Right shift | a >> b | Shifts in binary fashion all bits one position to the right, discarding the right bit. This operations maintains the original sign (+ or -). |
0-fill right shift | a >>> b | Shifts in binary fashion all bits one position to the right, discarding the right bit and filling the left bit with 0. |
JavaScript does not support an integer type,All numbers in JavaScript are stored in 64-bit floating point format i.e. double precision floating point.
for loop
var count =0;
for (vari = 0;i < 10;i++) {
count +=i;
}
alert("count = "+ count); // => count = 45
while loop
var i =0;
count = 100;
while (i < count){
i++;
}
alert("i = " +i); // => i = 100
switch statement
// switch statement
var day =new Date().getDay();
switch(day){
case0:
alert("Today is Sunday.");
break;
case1:
alert("Today is Monday.");
break;
case2:
alert("Today is Tuesday.");
break;
case3:
alert("Today is Wednesday.");
break;
case4:
alert("Today is Thursday.");
break;
case5:
alert("Today is Friday.");
break;
case6:
alert("Today is Saturday.");
break;
default:
alert("Today is a strange day.");
}
if-then-else
var value =9;
if (value < 0){
alert("Negative value.");
} elseif (value < 10){
alert("Between 0 and 9, inclusive.");
} else{
alert("Greater than or equal to 10.");
}
var value =9;
if (value < 0){
alert("Negative value.");
} elseif (value < 10){
alert("Between 0 and 9, inclusive.");
} else{
alert("Greater than or equal to 10.");
}
break and continue
for (vari = 0;i < 100;i++) {
if(i <5) {
continue;
}else if(i >7) {
break;
}
alert(i); // => 5, 6, 7
}
try, catch
try {
doesNotExist();
}
catch (ex){
alert("Error: " + ex.message); // => Error details
}
// JavaScript
function calculate (){
varcount = 0; // function level scope
...
}
function calculate (){
varcount = 0; // function level scope
...
}
// JavaScript
var accept =true; // global scope
if (accept === true){
varcount = 0;
}
var accept =true; // global scope
if (accept === true){
varcount = 0;
}
// global scope
varsay = function(){
alert("Hello");
};
say(); // => Hello
alert("Hello");
};
say(); // => Hello
Next is an example of a function that is passed as an argument to another function:
var say =function() {
alert("Hello");
};
function execute(callback){
callback();
}
execute(say); // => Hello
var say =function() {
alert("Hello");
};
function execute(callback){
callback();
}
execute(say); // => Hello
And here is an example of a function that is returned by another function:
function go(){
returnfunction() {
alert("I was returned");
};
}
var result =go();
result(); // => I was returned
function go(){
returnfunction() {
alert("I was returned");
};
}
var result =go();
result(); // => I was returned
JavaScript is object-oriented, but class-less:
vartext = "excellent";
alert(text.substring(0,5)); // => excel
var count =20.1045;
alert(count.toFixed(2)); // => 20.10
alert(text.substring(0,5)); // => excel
var count =20.1045;
alert(count.toFixed(2)); // => 20.10
Objects:
// Note: the use of new Object() is generally discouraged
var o =new Object();
o.firstName ="Joan";
o.lastName ="Holland";
o.age =31;
alert(o.firstName + " "+ o.lastName); // => Joan Holland
alert(typeof o.age); // => number
delete o.firstName;
alert(o.firstName + " "+ o.lastName); // => undefined Holland
for (varprop in o)
{
// name: firstName, value: Joan, type: string
// name: age, value: 31, type: number
alert("name: " + prop +" ,value: " +o[prop]+
" ,type: " + typeofo[prop]);
}
var o =new Object();
o.firstName ="Joan";
o.lastName ="Holland";
o.age =31;
alert(o.firstName + " "+ o.lastName); // => Joan Holland
alert(typeof o.age); // => number
delete o.firstName;
alert(o.firstName + " "+ o.lastName); // => undefined Holland
for (varprop in o)
{
// name: firstName, value: Joan, type: string
// name: age, value: 31, type: number
alert("name: " + prop +" ,value: " +o[prop]+
" ,type: " + typeofo[prop]);
}
Functions
The code below confirms that functions are indeed objects in JavaScript
function say(name){
alert("Hello " + name);
}
alert(typeof say); // => function
alert(say instanceofObject); // => true
say.volume ="high";
alert(say.volume); // => high
function say(name){
alert("Hello " + name);
}
alert(typeof say); // => function
alert(say instanceofObject); // => true
say.volume ="high";
alert(say.volume); // => high
one method to this:
function Book(title,author) {
this.title = title; // book properties
this.author = author;
this.details = function(){ // book method
returnthis.title +" by " +this.author;
}
}
function Book(title,author) {
this.title = title; // book properties
this.author = author;
this.details = function(){ // book method
returnthis.title +" by " +this.author;
}
}
In the code below a new Book instance is created and we invoke its detailsmethod:
varbook = newBook("Ulysses","James Joyce");
alert(book.details()); // => Ulysses by James Joyce
JavaScript is a prototype-based language:
alert(book.details()); // => Ulysses by James Joyce
JavaScript is a prototype-based language:
varBook =function(author){
this.author = author;
};
this.author = author;
};
alert(Book.prototype); // => [object Object], so there is something
Here is an example:
function Rectangle(width,height) {
this.width = width;
this.height = height;
}
Rectangle.prototype.area = function() {
returnthis.width *this.height;
};
var r1 =new Rectangle(4,5);
var r2 =new Rectangle(3,4);
alert(r1.area()); // => 20
alert(r2.area()); // => 12
The number variable type
The implication of this is that in JavaScript the values 10, 10.0, and 1e1 are all the same.
var a =10;
var b =10.0;
var c =1e1;
alert(a ===b); // => true
alert(a ===c); // => true
alert(b ===c); // => true
var a =10;
var b =10.0;
var c =1e1;
alert(a ===b); // => true
alert(a ===c); // => true
alert(b ===c); // => true
The string variable type
you can easily use a single character string, such, as "a", or "Y". Here are some string examples:
var s = "Hello World";
var t =s.substr(6); // new string
alert(t); // => World
The Boolean variable type
var s = "Hello World";
var t =s.substr(6); // new string
alert(t); // => World
The Boolean variable type
Like in other languages, JavaScript's Boolean has two possible values: true and false. Note that true and false are language keywords and they are distinct from 1 and 0.
var b =false;
alert(b); // => false (i.e. not 0)
var b =false;
alert(b); // => false (i.e. not 0)
null and undefined
When your function has no return value, it returns undefined. If you declare a variable and don't initialize it, it returns the undefined value. If you query a non-existent array element or object property, again an undefined is returned. Here is an example.
var book;
alert(book); // => undefined
alert(typeof book); // => undefined
var book;
alert(book); // => undefined
alert(typeof book); // => undefined
If you want to indicate the 'lack of value' in your code, you typically use null rather than undefined.
var book =null;
alert(book); // => null
alert(typeof book); // => object (although null is not a true object)
var book =null;
alert(book); // => null
alert(typeof book); // => object (although null is not a true object)
if statement
Here is a simple example:
var person ={ age:33 };
if (person.age >= 18){
alert ("Adult"); // => Adult
alert ("Allowed to vote"); // => Allowed to vote
}
They are separated by an || (or) operator:
vara = 4;
var b =5;
if (a <= 7|| b >10) { // true
alert("yes"); // => yes
}
var b =5;
if (a <= 7|| b >10) { // true
alert("yes"); // => yes
}
if…else statement
The if-statement may contain an optional else clause that specifies an alternative course of action. The else clause is executed if the expression in the if-statement is evaluated to false.
var password ="secret";
if (password.length >= 7){
alert("okay");
} else{
alert("Number of characters in your password must be at least 7.");
returnfalse;
}
var password ="secret";
if (password.length >= 7){
alert("okay");
} else{
alert("Number of characters in your password must be at least 7.");
returnfalse;
}
If no else-if condition is evaluated to true, the statements inside the else block are executed.
var age =34;
if (age < 13){
alert("child"); // => child
} elseif (age < 19){
alert("adolescent"); // => adolescent
} else{
alert("adult"); // => adult
}
var age =34;
if (age < 13){
alert("child"); // => child
} elseif (age < 19){
alert("adolescent"); // => adolescent
} else{
alert("adult"); // => adult
}
switch statement
Here is an example:
var account =3;
switch (account){
case1:
alert("Checking account"); // => Checking account
break;
case2:
alert("Savings account"); // => Savings account
break;
case3 :
alert("Business account"); // => Business account
break;
default:
alert("Invalid account code");
break;
}
var account =3;
switch (account){
case1:
alert("Checking account"); // => Checking account
break;
case2:
alert("Savings account"); // => Savings account
break;
case3 :
alert("Business account"); // => Business account
break;
default:
alert("Invalid account code");
break;
}
Avoid switch fall-through
You should end each case with an explicit break statement. If a break is absent, case statements 'fall through' meaning that the control will flow sequentially through subsequent case statement.
var account =3;
switch (account){
case1:
alert("Checking account"); // => Checking account
break;
case2:
alert("Savings account"); // => Savings account
break;
case3:
alert("Business account"); // => Business account (falls through)
default:
alert("Invalid account code");
break;
}
var account =3;
switch (account){
case1:
alert("Checking account"); // => Checking account
break;
case2:
alert("Savings account"); // => Savings account
break;
case3:
alert("Business account"); // => Business account (falls through)
default:
alert("Invalid account code");
break;
}
while loop
Here is an example of a JavaScript while loop:
var sum =0;
var number =1;
while (number <= 50){ // -- condition
sum +=number; // -- body
number++; // -- updater
}
alert("Sum = " +sum); // => Sum = 1275
var sum =0;
var number =1;
while (number <= 50){ // -- condition
sum +=number; // -- body
number++; // -- updater
}
alert("Sum = " +sum); // => Sum = 1275
do-while loop
Here is an example of a JavaScript do-while loop:
var sum =0;
var number =1;
do {
sum +=number; // -- body
number++; // -- updater
} while(number <=50); // -- condition
alert("Sum = " +sum); // => Sum = 1275
var sum =0;
var number =1;
do {
sum +=number; // -- body
number++; // -- updater
} while(number <=50); // -- condition
alert("Sum = " +sum); // => Sum = 1275
for loop
The most frequently used loop in JavaScript is the for-loop. Here is an example:
var sum =0;
for (vari = 1;i <= 50;i++) {
sum =sum + i;
}
alert("Sum = " +sum); // => Sum = 1275
var sum =0;
for (vari = 1;i <= 50;i++) {
sum =sum + i;
}
alert("Sum = " +sum); // => Sum = 1275
for-in loop
A for-in loop iterates through the properties of an object and executes the loop's body once for each enumerable property of the object. Here is an example:
var student ={ name:"Bill",age: 25,degree: "Masters"};
for (varitem in student){
alert(student[item]); // => "Bill", then 25, then "Masters"
}
var student ={ name:"Bill",age: 25,degree: "Masters"};
for (varitem in student){
alert(student[item]); // => "Bill", then 25, then "Masters"
}
An easy way to skip properties and functions that are not part of the object itself use the built-in hasOwnProperty method.
var Student= function(name){
this.name = name;
}
Student.prototype.age = 38;
var student =new Student("Carl");
for (varitem in student){
if(student.hasOwnProperty(item)){
alert (student[item]); // => Carl. age is not displayed
}
}
var Student= function(name){
this.name = name;
}
Student.prototype.age = 38;
var student =new Student("Carl");
for (varitem in student){
if(student.hasOwnProperty(item)){
alert (student[item]); // => Carl. age is not displayed
}
}
break statement
When JavaScript encounters a break statement in a loop it immediately exits the loop without executing any other statements in the loop. Control is immediately transferred to the statement following the loop body. Here is an example:
var sum =0;
for (vari = 1;i <= 10000;i++) {
sum +=i;
if(i ===50) {
break; // immediately transfers control outside the for block
}
}
alert("Sum = " +sum); // => Sum = 1275
var sum =0;
for (vari = 1;i <= 10000;i++) {
sum +=i;
if(i ===50) {
break; // immediately transfers control outside the for block
}
}
alert("Sum = " +sum); // => Sum = 1275
When an infinite loop is created intentionally, you can use a break statement to controls termination of the loop, like so:
var number =1;
var sum =0;
while (true) // equivalent to for ( ; ; ), called 'forever' loop
{
sum +=number;
if(number ===50) {
break; // immediately transfers control outside while block
}
number++;
}
alert("Sum = " +sum); // => Sum = 1275
var number =1;
var sum =0;
while (true) // equivalent to for ( ; ; ), called 'forever' loop
{
sum +=number;
if(number ===50) {
break; // immediately transfers control outside while block
}
number++;
}
alert("Sum = " +sum); // => Sum = 1275
The number++;statement won't be executed when the loop is entered for the 50th time.
continue statement
When JavaScript encounters a continue statement in a loop it stops the execution of the current iteration and goes back to the beginning of the loop to begin the next iteration. The example below displays only even numbers.
for (vari = 1;i <= 10;i++)
{
if((i %2) !=0) {
continue;
}
alert(i); // => 2, 4, 6, 8, 10
}
for (vari = 1;i <= 10;i++)
{
if((i %2) !=0) {
continue;
}
alert(i); // => 2, 4, 6, 8, 10
}
The continue statement can also be used in other loops. However, in a for-loop it behaves differently from when used in a while loop. In the example above, the for-loop first evaluates the i++ expression and then tests the i <= 50 condition. Now, consider the while loop:
var number =0;
while (number <= 10){
number++;
if((number %2) !=0) {
continue;
}
alert(number); // => 2, 4, 6, 8, 10
}
var number =0;
while (number <= 10){
number++;
if((number %2) !=0) {
continue;
}
alert(number); // => 2, 4, 6, 8, 10
}
value types and reference types:
var x = 1;
var y = x;
alert(x == y); // => true
alert(x === y); // => true
x = 6;
alert(x); // => 6
alert(y); // => 1
alert(x == y); // => false
alert(x === y); // => false
var y = x;
alert(x == y); // => true
alert(x === y); // => true
x = 6;
alert(x); // => 6
alert(y); // => 1
alert(x == y); // => false
alert(x === y); // => false
When variable y is assigned to x it copies its value and following the assignment any relationship between x and y is severed. So, changing the value of x has no impact on the value of y.Consider this example where a reference type is copied:
var x ={ make:"Toyota" };
var y =x;
alert(x ==y); // => true
alert(x ===y); // => true
x.make ="Ford";
alert(x.make); // => Ford
alert(y.make); // => Ford
alert(x ==y); // => true
alert(x ===y); // => true
var x ={ make:"Toyota" };
var y =x;
alert(x ==y); // => true
alert(x ===y); // => true
x.make ="Ford";
alert(x.make); // => Ford
alert(y.make); // => Ford
alert(x ==y); // => true
alert(x ===y); // => true
Here are some examples of string literals:
var s1 ="Don't ignore Peter's feedback";
var s2 ='Don\'t ignore Peter\'s feedback';
var s3 ='Andrew Fuller\n Bob Springsteen';
var s4 ="Andrew Fuller, \
Bob Springsteen, \
Helena Williams";
alert(s1);
alert(s2);
alert(s3);
alert(s4);
Note that using the continuation character is generally not recommended.
Here are some other string members you frequently use: length, and charAt.
var s ="Paris, London, Amsterdam";
alert(s.length); // => 24
alert(s.charAt(0)); // => P. First character
alert(s.charAt(s.length-1)); // => m. Last character
And here are some additional frequently used string methods: indexOf, lastIndexOf, toLowerCase, substring, replace, and split.
var s ="Paris, London, Amsterdam";
// Gets position of first 'a', returns 1
alert(s.indexOf("a"));
// Gets position of first 'a' starting at 3, returns 22
alert(s.indexOf("a",3));
// Gets position of last 'o', returns 11
alert(s.lastIndexOf("o"));
// Converts string to lower-case
alert(s.toLowerCase());
// Gets substring starting from the 15th character to the last,
alert(s.substring(14,s.length));
// Replaces "London" with "Berlin"
alert(s.replace("London","Berlin"));
// splits into an array of substrings using ", " separator
alert("Array: " +s.split(", "));
var s ="Paris, London, Amsterdam";
// Gets position of first 'a', returns 1
alert(s.indexOf("a"));
// Gets position of first 'a' starting at 3, returns 22
alert(s.indexOf("a",3));
// Gets position of last 'o', returns 11
alert(s.lastIndexOf("o"));
// Converts string to lower-case
alert(s.toLowerCase());
// Gets substring starting from the 15th character to the last,
alert(s.substring(14,s.length));
// Replaces "London" with "Berlin"
alert(s.replace("London","Berlin"));
// splits into an array of substrings using ", " separator
alert("Array: " +s.split(", "));
When comparing two strings they are considered equal when they have the same length and the same sequence of characters in corresponding positions.
var str1 ="Hello World";
var str2 ="Hello" +" World";
alert(str1 ==str2); // => true
alert(str1 ===str2); // => true
var str1 ="Hello World";
var str2 ="Hello" +" World";
alert(str1 ==str2); // => true
alert(str1 ===str2); // => true
Here are some examples of string literals:
var s1 ="Don't ignore Peter's feedback";
var s2 ='Don\'t ignore Peter\'s feedback';
var s3 ='Andrew Fuller\n Bob Springsteen';
var s4 ="Andrew Fuller, \
Bob Springsteen, \
Helena Williams";
alert(s1);
alert(s2);
alert(s3);
alert(s4);
Note that using the continuation character is generally not recommended.
Here are some other string members you frequently use: length, and charAt.
var s ="Paris, London, Amsterdam";
alert(s.length); // => 24
alert(s.charAt(0)); // => P. First character
alert(s.charAt(s.length-1)); // => m. Last character
And here are some additional frequently used string methods: indexOf, lastIndexOf, toLowerCase, substring, replace, and split.
var s ="Paris, London, Amsterdam";
// Gets position of first 'a', returns 1
alert(s.indexOf("a"));
// Gets position of first 'a' starting at 3, returns 22
alert(s.indexOf("a",3));
// Gets position of last 'o', returns 11
alert(s.lastIndexOf("o"));
// Converts string to lower-case
alert(s.toLowerCase());
// Gets substring starting from the 15th character to the last,
alert(s.substring(14,s.length));
// Replaces "London" with "Berlin"
alert(s.replace("London","Berlin"));
// splits into an array of substrings using ", " separator
alert("Array: " +s.split(", "));
When comparing two strings they are considered equal when they have the same length and the same sequence of characters in corresponding positions.
var str1 ="Hello World";
var str2 ="Hello" +" World";
alert(str1 ==str2); // => true
alert(str1 ===str2); // => true
var str1 ="Hello World";
var str2 ="Hello" +" World";
alert(str1 ==str2); // => true
alert(str1 ===str2); // => true
The Boolean type has two literal values: true and false:
varempty = "";
alert(Boolean(empty)); // => false
var nonEmpty ="JavaScript is cool!";
alert(Boolean(nonEmpty)); // => true
alert(Boolean(empty)); // => false
var nonEmpty ="JavaScript is cool!";
alert(Boolean(nonEmpty)); // => true
Automatic conversions to Boolean equivalents are common in conditional statements.
var car ={ make:"Toyota" };
var display =true;
if (car && display){ // => true
alert(car.make);
}
car = null;
if (car){ // => false
alert("drive my car");
}
var car ={ make:"Toyota" };
var display =true;
if (car && display){ // => true
alert(car.make);
}
car = null;
if (car){ // => false
alert("drive my car");
}
No comments:
Post a Comment