9866550012
JAVASCRIPT FOR BEGGINERS
JavaScript is primarily used as a client-side scripting language used for creating dynamic web pages. The scripts are embedded into HTML pages you upload to your web host that are then executed on the client’s system when they view those web pages. Despite its name JavaScript is a completely different language than Java. JavaScript is an interpreted language, meaning that scripts execute without preliminary compilation.
To embed a JavaScript into a web page the HTML <script> element is used with the type attribute set to “text/javascript”.
<script type="text/javascript"> </script>
Printing output
The first script to learn is the document.write method for dynamically outputting HTML onto the page.
<script type="text/javascript"> document.write("Hello World!"); </script>
Statements in JavaScript end with a semicolon, but a newline also functions as the end of a statement. Therefore, semicolons are not required unless there are several statements on the same line.
<script type="text/javascript"> document.write("Hello World"); document.write("!") </script>
Comments and whitespace
JavaScript uses the standard C++ comment notation, with both single-line and multi-line comments. As in HTML, whitespace is ignored in JavaScript, so extra spaces can be used to make the scripts more readable.
<script type="text/javascript"> // single-line comment /* multi-line comment */ </script>
Hello World
The HTML document below contains a Hello World JavaScript.
<html> <head><title>Learning JavaScript</title></head> <body> <script type="text/javascript">document.write("Hello World");</script> </body> <html>
When this document is viewed in a browser the script is executed as soon as the page loads and the text is displayed. Note that the script runs on the client-side. Therefore, there is less load on the server compared to server-side scripts. However, this also means that it’s up to the client whether the script is executed or not. The client may have disabled JavaScript or use an old browser that doesn’t support it.
Compatibility
If the browser doesn’t support JavaScript the script will be displayed as normal HTML. To prevent this it can be surrounded with the HTML comment tag, which effectively hides the script.
<script type="text/javascript"> <!-- //--> </script>
There’s also the <noscript> HTML element. This element presents an alternative message that can only be seen by browsers that don’t support scripts. However, since JavaScript is the most popular scripting language it works with all major browsers today.
<noscript> Your browser doesn't support JavaScript. </noscript>
External script file
Another way to include JavaScript is by saving the script in a file with a .js file extension. This external script can then be embedded in a page by pointing to the file with the src attribute of the script tag. This way several pages can use the same scripts without having to duplicate them on every page.
<script type="text/javascript" src="MyJS.js"></script>
Declaring and Assigning variables
Variables are used to store values so that they can be accessed several times in a document. To create a variable the var keyword is used followed by the variable’s name. The variable can then be assigned a value with the assignment operator.
var myVar; myVar = "Hello World";
The declaration and assignment of a variable can also be combined into one statement.
var myVar = "Hello World";
A variable’s name can include underscores characters and numbers, but it cannot start with a number. As for data types, JavaScript is an untyped language so any variable can hold any data type.
Integers
Integers can be represented with decimal, octal, or hexadecimal notation.
var a = 10; // 10 with decimal notation var b = 012; // 10 with octal notation (base 8) var c = 0xA; // 10 with hexadecimal notation (base 16)
Floats
Floating-point numbers can be represented with either decimal or exponential notation. Note that all numbers in JavaScript are stored as floating-point numbers behind the scenes.
var d = 10.1; var e = 0.1e2; // 10 with exponential notation (0.1*10^2)
Strings
Strings can be specified using either double or single quotes.
var a = "Hello World"; var b = 'Hello World';
To break a line within a string a backslash must be added. This character escapes the newline character which in JavaScript normally means the end of a statement.
var c = "Hello \ World";
Escape characters
Backslash is used to add special characters to a string, such as newlines or quotes.
var a = "\' Single quote \ \" Double quote \ \\ Backslash \ \b Backspace \ \f Form feed \ \n New line \ \r Carriage return \ \t Tab \ \& Ampersand";
Boolean
For storing boolean values the keywords true and false can be used.
var a = true; // Boolean (true or false)
Null
For storing no value there is the null keyword, which is different from leaving out the assignment. When a variable is assigned to null it becomes undefined. This is equal to NotANumber for numbers, undefined for strings, and false when the variable is evaluated as a boolean.
var b = null; // No value var c; /* Undefined (NaN for numbers, "undefined" for strings, false for boolean) */
Variable scope
The scope of a variable depends on where it is declared. A variable that is declared outside of a function becomes a global variable and can be used anywhere on the page after where it’s been declared, even inside another script.
<script type="text/javascript"> var a = 1; // global variable a </script> <script type="text/javascript"> document.write(a); // 1 </script>
The lifetime of these variables starts when they are declared and ends when the web page is closed. On the other hand a variable declared inside a function becomes a local variable. It can only be used inside that function after where it has been declared and it will be destroyed when the function is finished. A local variable can use the same name as a global variable and thereby overshadow it for the duration of the function.
var a = 1; // global variable a function f() { var a = 2; // local variable a (overshaddows global a) }
There is also a second way of declaring variables by leaving out the var keyword and thereby declaring them implicitly. A variable declared like this will always become a global variable, even if it’s declared within a function.
function f() { b = 5; // global variable b }
JavaScript basically has five kinds of numerical operators.
Arithmetic operators
First, there are the four basic arithmetic operations, together with modulus to gets the division remainder.
x = 4+2; // 6 // additionx = 4-2; // 2 // subtractionx = 4*2; // 8 // multiplicationx = 4/2; // 2 // divisionx = 4%2; // 0 // modulus (division remainder)
Assignment operators
Second, there are the assignment operators. Most importantly, the equal sign itself which assigns a value to a variable.
Combined assignment operators
The combined assignment operators perform arithmetic operations on the same variable that they assign to.
x += 5; // add and assignx -= 5; // subtract and assignx *= 5; // multiply and assignx /= 5; // divide and assignx %= 5; // modulus and assign
Increment and decrement operators
The increment and decrement operators increase or decrease a variable by one.
x++; // x += 1;x--; // x -= 1;
They can be used either before or after a variable.
++x; // pre-increment--x; // pre-decrementx++; // post-incrementx--; // post-decrement
The post and pre versions of the operators have the same effect on the variable. The difference is that the post-operator returns the original value before it changes the variable, while the pre-operator changes the variable first and then returns it.
x = 5; y = x++; // y=5, x=6x = 5; y = ++x; // y=6, x=6
Comparison operators
The third group is the comparison operators, which compares two values and return either true or false. They are mostly used for creating conditions in flow control statements. Notice the “identical” and “not identical” operators for comparing both type and value. These are necessary because with the regular “equal to” operator will automatically perform a type conversion before it compares.
x = (2==3); // false // equal tox = (2===3); // false // identical (same type and value)x = (2!==3); // true // not identicalx = (2!=3); // true // not equal tox = (2>3); // false // greater thanx = (2<3); // true // less thanx = (2>=3); // false // greater than or equal tox = (2<=3); // true // less than or equal to
Logical operators
The fourth group is the logical or boolean operators. These are usually used together with the comparison operators. Logical and returns true if the expressions on both sides are true. Logical or returns true if the left or right sides are true. Logical not simply inverts a boolean value. Note that logical and/or will not evaluate what is on the right side if the result is already decided by the left side.
x = (true && false); // false // logical andx = (true || false); // true // logical orx = !(true); // false // logical not
Bitwise operators
The fifth and last group is the bitwise operators which work on the binary representation of numbers. Notice that there are two right shift operators. The first one (>>) leaves the sign bit untouched, while the second one (>>>) shifts is to the right as with the other bits. Both operators evaluate the same for positive numbers.
x = 5 & 4; // 4 (101 & 100 = 100) // andx = 5 | 4; // 5 (101 | 100 = 101) // orx = 5 ^ 4; // 1 (101 ^ 100 = 001) // xor (exclusive or)x = 4 << 1; // 8 (100 << 1 =1000) // shift leftx = 4 >> 1; // 2 (100 >> 1 = 010) // shift right (!sign)x = 4 >>> 1;// 2 (100 >>> 1 = 010) // shift rightx = ~4; //-5 (~00000100 = 11111011) // invert
The bitwise operators also have their own combined assignment operators.
x &= 5; // AND and assignx |= 5; // OR and assignx ^= 5; // XOR and assignx <<= 5; // left shift and assignx >>= 5; // right shift and assign (keeps sign bit)x>>>= 5; // right shift and assign
String operators
There are only two operators that work on strings. First, the addition operator which can combine two strings together. Second, the combined assignment operator for addition can append one string to the end of a string variable.
x = "Hello"; // assignmentx = x + " World"; // concatenationx += " World"; // concatenate and assign
Another usage for the addition operator is to convert strings into numbers. This is done by putting the addition sign just before the string.
document.write( "5" + 5); // 55document.write(+"5" + 5); // 10
Operator precedence
In JavaScript, expressions are normally evaluated from left to right. However, different operators have different precedents. For example, multiplication binds harder than addition and is therefore evaluated first.
x = 2 + 1 * 2; // 4
To avoid ambiguous expressions, like the one above, parenthesis can be used to decide the order of evaluation. The parenthesis has the highest precedence of all operators.
x = (2 + 1) * 2; // 6