Java script basics


Published on

A basic introduction into some foundational syntax and types within JavaScript.

Published in: Technology
1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Java script basics

  1. 1. JavaScript Basics Shrivardhan R. Limbkar Front end developer, Pune, India
  2. 2. IntroductionJavaScript was originally developed by Brendan Eich atNetscape sometime in 1995–1996. Back then, the languagewas called LiveScript. That was a great name for a newlanguage— and the story could have ended there. However,in an unfortunate decision, the folks in marketing had theirway, and the language was renamed to JavaScript.JavaScript is a text-based language that does not need anyconversion before being executed.
  3. 3. Other languages like Java and C++ need to be compiled to beexecutable but JavaScript is executed instantly by a type ofprogram that interprets the code called a parser (pretty much allweb browsers contain a JavaScript parser).JavaScript Versions and supported Browsers1.0 Mar 19961.1 Aug 19961.2 Jun 19971.3 Oct 19981.5 Nov 2000 IE5.5,6,7,8, FF1.0, Opera7.0,Safari3.0-51.6 Nov 20051.7 Oct 20061.8 Jun 20081.8.2 Jun 20091.8.5 Jul 2010 IE9, FF4+, Opera11.60, Safari 5, Chrome 5+
  4. 4. What Can JavaScript do?• Gives HTML designers a programming tool.• React to events.• Manipulate HTML elements.• Validate data.• Detect the visitors browser.• Create cookies.• The arithmetic calculations of table fields, variables etc.• Moving and rolling messages.• Animation effects with pictures or graphics.
  5. 5. Advantages & Limitations of JavaScriptAdvantages of JavaScript:• Less server interaction• Immediate feedback to the visitors• Increased interactivity• Richer interfacesLimitations with JavaScript• Client-side JavaScript does not allow the reading or writing of files. This has been kept for security reason.• JavaScript can not be used for Networking applications because there is no such support available.• JavaScript doesnt have any multithreading or multiprocess capabilities.
  6. 6. To execute JavaScript in a browser youhave two options.1. Including your JavaScript inside your HTML document. Put it inside a script element anywhere inside an HTML document.<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" ""><html lang="en-en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <script type="text/javascript"> var z = 10; alert(‘Hello worrld, z is +z); </script> </head> <body> <!-- lots of HTML here --> </body></html>
  7. 7. 2. Linking to an external JavaScript file - Put it inside an external JavaScriptfile (with a .js extension) and then reference that file inside the HTMLdocument using an empty script element with a src attribute.<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"""><html lang="en-en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <script type="text/javascript" src="myscript.js"></script> </head> <body> <!-- lots of HTML here --> </body></html>** Performance specialists have more recently started toadvocate placing your JavaScript at the end of the body instead.
  8. 8. JavaScript Syntax and Statements• Case Sensitivity - JavaScript is case sensitive. You must be aware of this when naming variables and using the language keywords. A variable named glass is not the same as a variable named Glass or one named GLASS. Similarly, the loop control keyword while is perfectly valid, but naming it WHILE or While will result in an error. Keywords are lowercase, but variables can be any mix of case that you’d like.• White Space - For the most part, JavaScript ignores white space, which is the space between statements in JavaScript. You can use spaces, indenting, or whatever coding standards you prefer to make the JavaScript more readable.• Comments - Comments can be placed into JavaScript code in two ways: multiline and single-line.
  9. 9. // slashslash line comment /* slashstar block comment */• Semicolons - Javascript statements are separated by a semicolon (;)• Line Breaks - Related closely to white space and even to semicolons in JavaScript are line breaks, sometimes called carriage returns.
  10. 10. Data Types in JavaScript• Numbers• Strings• Booleans• Null• Undefined• Objects
  11. 11. NumbersOnly one number type No integers64-bit floating pointIEEE-754 (aka “Double”)Does not map well to common understanding of arithmetic:0.1 + 0.2 = 0.30000000000000004 NaN• Special number: Not a Number• Result of undefined or erroneous operations• Toxic: any arithmetic operation with NaN as an input will have NaN as a result• NaN is not equal to anything, including NaN
  12. 12. Number function Number(value)• Converts the value into a number.• It produces NaN if it has a problem.• Similar to + prefix operator. parseInt function parseInt(value, 33)• Converts the value into a number.• It stops at the first non-digit character.• The radix (10) should be required. parseInt("04") === 0 parseInt("04", 22) === 4
  13. 13. Strings• Sequence of 0 or more 16-bit characters • UCS-2, not quite UTF-16 • No awareness of surrogate pairs• No separate character type • Characters are represented as strings with a length of 1• Strings are immutable• Similar strings are equal ( == )• String literals can use single or double quotes
  14. 14. String Methods and Properties• JavaScript defines several properties and methods for working with strings. These properties and methods are accessed using dot notation (“.”) String function - Converts value to a string String(value)• String Methods • charAt concat • indexOf lastIndexOf • Match replace • Search slice • Split substring • toLowerCase toUpperCase
  15. 15. Other Escape CharactersEscape Character Sequence Value• b Backspace• t Tab• n Newline• v Vertical tab• f Form feed• r Carriage return• Literal backslash
  16. 16. BooleansThe Boolean represents two values either "true" or "false".If value parameter is omitted or is 0, -0, null, false, NaN, undefined, orthe empty string (""), the object has an initial value of false.• Boolean function • Boolean(value)• returns true if value is truthy• returns false if value is falsy• Similar to !! prefix operator
  17. 17. • Null • A value that isnt anything• Undefined • A value that isnt even that • The default value for variables and parameters • The value of missing members in objects• Falsy values • false • null • undefined • "" (empty string) • 0 • NaN• All other values (including all objects) are truthy. "0" "false"
  18. 18. JavaScript Variables• Like many other programming languages, JavaScript has variables. Variables can be thought of as named containers. You can place data into these containers and then refer to the data simply by naming the container.• Before you use a variable in a JavaScript program, you must declare it. Variables are declared with the var keyword as follows: <script type="text/javascript"> <!-- var glass; var firstName; //--> </script>
  19. 19. JavaScript Variable ScopeThe scope of a variable is the region of your program in which it isdefined. JavaScript variable will have only two scopes.• Global Variables - A global variable has global scope which means it is defined everywhere in your JavaScript code.• Local Variables - A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.Within the body of a function, a local variable takes precedence over aglobal variable with the same name. If you declare a local variable orfunction parameter with the same name as a global variable, youeffectively hide the global variable. Following example explains it:
  20. 20. <script type="text/javascript"><!-- var myVar = "global"; // Declare a global variable function checkscope( ) { var myVar = "local"; // Declare a local variable document.write(myVar); }//--></script>JavaScript Variable NamesWhile naming your variables in JavaScript keep following rules in mind.• You should not use any of the JavaScript reserved keyword as variable name. These keywords are mentioned in the next section. For example, break or boolean variable names are not valid.• JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or the underscore character. For example, 123test is an invalid variable name but _123test is a valid one.• JavaScript variable names are case sensitive. For example, Name and name are two different variables.
  21. 21. Var statement• Defines variables within a function.• Types are not specified.• Initial values are optional. var name; var nrErrors = 0; var a, b, c;
  22. 22. Operators• Arithmetic + - * / %• Comparison == != < > <= >=• Logical && || !• Bitwise & | ^ >> >>> <<• Ternary ?:
  23. 23. + Addition• Addition and concatenation• If both operands are numbers, • then • add them • else convert them both to strings concatenate them $ + 3 + 4 = $34• Unary operator can convert strings to numbers +"42" = 42
  24. 24. • Also Number("42") = 42• Also parseInt("42", 10) = 42 +"3" + (+"4") = 7
  25. 25. / Division• Division of two integers can produce a non-integer result 10 / 3 = 3.3333333333333335
  26. 26. == != equal or not equal== :- Checks if the value of two operands are equal or not, if yes thencondition becomes true. (A == B)!= :- Checks if the value of two operands are equal or not, if values arenot equal then condition becomes true. (A != B)1. Equal and not equal2. These operators can do type coercionIt is better to use === and !==, which do not do type coercion.
  27. 27. && - AND OperatorCalled Logical AND operator. If both the operands are non zero thenthen condition becomes true. (A && B) is true• The guard operator, aka logical and• If first operand is truthy • then result is second operand • else result is first operand• It can be used to avoid null references if (a) { return a.member; } else { return a; }• can be written as • return a && a.member;
  28. 28. || - OR OperatorCalled Logical OR Operator. If any of the two operands are non zero thenthen condition becomes true. (A || B) is true.• The default operator, aka logical or• If first operand is truthy • then result is first operand • else result is second operand• It can be used to fill in default values. • var last = input || nr_items;• (If input is truthy, then last is input, otherwise set last to nr_items.)
  29. 29. ! - NOT OperatorCalled Logical NOT Operator. Use to reverses the logical state of itsoperand. If a condition is true then Logical NOT operator will make false. !(A && B) is false.• Prefix logical not operator.• If the operand is truthy, the result is false. Otherwise, the result is true.• !! produces booleans.
  30. 30. Bitwise & | ^ >> >>> <<• The bitwise operators convert the operand to a 32-bit signed integer, and turn the result back into 64-bit floating point.
  31. 31. Statements• expression• if• switch• while• do..while• For•• break• continue• try/throw
  32. 32. If…Else statementJavaScript supports conditional statements which are used to performdifferent actions based on different conditions. Here we will explainif..else statement.JavaScript supports following forms of if..else statement.• if statement• if...else statement• if...else if... statement.
  33. 33. If…Else statement• if statement - The if statement is the fundamental control statement that allows JavaScript to make decisions and execute statements conditionally.• if...else statement - The if...else statement is the next form of control statement that allows JavaScript to execute statements in more controlled way.• if...else if... statement:• The if...else if... statement is the one level advance form of control statement that allows JavaScript to make correct decision out of several conditions.
  34. 34. If…Else statement if satement if…else if statement<script type="text/javascript"> <script type="text/javascript"> <!-- <!-- var age = 20; var book = "maths"; if( age > 18 ){ if( book == "history" ){ document.write("<b>Eligible for voting</b>"); document.write("<b>History Book</b>"); } }else if( book == "maths" ){ //--> document.write("<b>Maths Book</b>");</script> }else if( book == "economics" ){----------------------------------------------------------------------- document.write("<b>Economics Book</b>"); if…else statement }else{<script type="text/javascript"> document.write("<b>Unknown Book</b>"); <!-- } var age = 15; //--> if( age > 18 ){ </script> document.write("< b>Eligible for voting </b>"); }else{ if Shorthand: document.write("<b>Does not eligible for voting </b>"); } var big = (x > 10) ? true : false; //--></script>
  35. 35. Switch statement• Multiway branch <script type="text/javascript">• The switch value does not need to a <!-- var grade=A; number. It can be a string. document.write("Entering switch block<br />");• The case values can be expressions. switch (grade) { switch (expression) { case A: document.write("Good job<br />"); case ;: break; case ,: case B: document.write("Pretty good<br />"); case .: break; punctuation(); case C: document.write("Passed<br />"); break; break; default: case D: document.write("Not so good<br />"); noneOfTheAbove(); break; } case F: document.write("Failed<br />"); break; default: document.write("Unknown grade<br />") } document.write("Exiting switch block"); //--> </script>
  36. 36. While statementThe purpose of a while loop is to execute a statement or code blockrepeatedly as long as expression is true. Once expression becomes false,the loop will be exited. while (expression){ Statement(s) to be executed if expression is true } <script type="text/javascript"> <!-- var count = 0; document.write("Starting Loop" + "<br />"); while (count < 10){ document.write("Current Count : " + count + "<br />"); count++; } document.write("Loop stopped!"); //--> </script>
  37. 37. Do..While statementThe do...while loop is similar to the while loop except that the conditioncheck happens at the end of the loop. This means that the loop willalways be executed at least once, even if the condition is false. do{ Statement(s) to be executed; } while (expression); <script type="text/javascript"> <!-- var count = 0; document.write("Starting Loop" + "<br />"); do{ document.write("Current Count : " + count + "<br />"); count++; }while (count < 0); document.write("Loop stopped!"); //--> </script>
  38. 38. For statementIterate through all of the elements of an array: for (var i = 0; i < array.length; i += 1) { // within the loop, // i is the index of the current member // array[i] is the current element } <script type="text/javascript"> <!-- var count; document.write("Starting Loop" + "<br />"); for(count = 0; count < 10; count++){ document.write("Current Count : " + count ); document.write("<br />"); } document.write("Loop stopped!"); //--> </script>
  39. 39. For…in statementThere is one more loop supported by JavaScript. It is called loop.This loop is used to loop through an objects properties. once you willhave understanding on JavaScript objects then you will find this loopvery useful. for (variablename in object){ statement or block to execute }In each iteration one property from object is assigned to variablename and this loop continues till allthe properties of the object are exhausted.<script type="text/javascript"> <!-- var aProperty; document.write("Navigator Object Properties<br /> "); for (aProperty in navigator) { document.write(aProperty); document.write("<br />"); } document.write("Exiting from the loop!"); //--></script>
  40. 40. Break statementJavaScript provides break and continue statements. These statementsare used to immediately come out of any loop or to start the nextiteration of any loop respectively.The break statement will break the loop and continue executing thecode that follows after the loop (if any).Statements can have labels.Break statements can refer to those labels. <script type="text/javascript"> <!-- var x = 1; document.write("Entering the loop<br /> "); while (x < 20) { if (x == 5){ break; // breaks out of loop completely } x = x + 1; document.write( x + "<br />"); } document.write("Exiting the loop!<br /> "); //--> </script>
  41. 41. Continue statementThe continue statement will break the current loop and continue withthe next value. for (i=0;i<=10;i++) { if (i==5) { continue; } x=x + "The number is " + i + "<br />"; }
  42. 42. Throw statement <script type="text/javascript"> var x=prompt("Enter a number between 5 and 10:",""); tryThe throw statement allows you { if(x>10)to create an exception. If you { throw "Err1";use this statement together with }the try...catch statement, you else if(x<5) {can control program flow and throw "Err2"; }generate accurate error else if(isNaN(x)) {messages. throw "Err3"; } } throw exception catch(err) { if(err=="Err1") { document.write("Error! The value is too high."); } if(err=="Err2") { document.write("Error! The value is too low."); } if(err=="Err3") { document.write("Error! The value is not a number."); } } </script>
  43. 43. Try statementThe try...catch statement allows you to test a block of code for errors.The try block contains the code to be run, and the catch block containsthe code to be executed if an error occurs. • Error • EvalError • RangeError • SyntaxError • TypeError • URIError
  44. 44. Try statement try { <script type="text/javascript"> some code var txt=""; } catch (e) { function message() switch ( { { case Error: try ... { break; adddlert("Welcome guest!"); default: } throw e; catch(err) } { } txt="There was an error on this page.nn"; txt+="Error description: " + err.message + "nn"; txt+="Click OK to continue.nn"; alert(txt); } } </script>
  45. 45. Function statementA function is a group of reusable code which can be called anywhere in yourprogram. This eliminates the need of writing same code again and again. Thiswill help programmers to write modular code. You can divide your big programin a number of small and manageable functions.A function in JavaScript is by using the function keyword, followed by a uniquefunction name, a list of parameters (that might be empty), and a statementblock surrounded by curly braces.<script type="text/javascript"> <script type="text/javascript"> <!-- <!-- function functionname(parameter-list) function sayHello() { { statements alert("Hello there"); } } //--> sayHello();</script> //--> </script>
  46. 46. Function statementFunction Parameters - Till now we have seen function without aparameters. But there is a facility to pass different parameters whilecalling a function. These passed parameters can be captured inside thefunction and any manipulation can be done over those parameters.A function can take multiple parameters separated by comma. <script type="text/javascript"> <!-- function sayHello(name, age) { alert( name + " is " + age + " years old."); } sayHello(Sam, 7 ); //--> </script>
  47. 47. Return statementA JavaScript function can have an optional return statement. This isrequired if you want to return a value from a function. This statementshould be the last statement in a function. Return is used in a function for two reasons. 1. You want the script to stop executing if something happens. 2. You want the function to return a value to the calling function. return expression; or return;• If there is no expression, then the return value is undefined.• Except for constructors, whose default return value is this.
  48. 48. EventsJavaScripts interaction with HTML is handled through events that occurwhen the user or browser manipulates a page.When the page loads, that is an event. When the user clicks a button,that click, too, is an event. Another example of events are like pressingany key, closing window, resizing window etc.Developers can use these events to execute JavaScript coded responses,which cause buttons to close windows, messages to be displayed tousers, data to be validated, and virtually any other type of responseimaginable to occur.Events are a part of the Document Object Model (DOM) Level 3 andevery HTML element have a certain set of events which can triggerJavaScript Code.
  49. 49. Eventsonclick Event -This is the most frequently used event type which occurs when a user clicksmouse left button. You can put your validation, warning etc. against thisevent type.<html><head><script type="text/javascript"> <!-- function sayHello() { alert("Hello World") } //--></script></head><body><input type="button" onclick="sayHello()" value="Say Hello" /></body></html>
  50. 50. Cookies• What are Cookies ?Web Browser and Server use HTTP protocol to communicate and HTTP is astateless protocol. But for a commercial website it is required to maintainsession information among different pages. For example one user registrationends after completing many pages. But how to maintain users sessioninformation across all the web pages.In many situations, using cookies is the most efficient method of rememberingand tracking preferences, purchases, commissions, and other informationrequired for better visitor experience or site statistics.• How It Works ?Your server sends some data to the visitors browser in the form of a cookie. Thebrowser may accept the cookie. If it does, it is stored as a plain text record onthe visitors hard drive. Now, when the visitor arrives at another page on yoursite, the browser sends the same cookie to the server for retrieval. Onceretrieved, your server knows/remembers what was stored earlier.
  51. 51. CookiesCookies are a plain text data record of 5 variable-length fields:• Expires : The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser.• Domain : The domain name of your site.• Path : The path to the directory or web page that set the cookie. This may be blank if you want to retrieve the cookie from any directory or page.• Secure : If this field contains the word "secure" then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists.• Name=Value : Cookies are set and retrieved in the form of key and value pairs.JavaScript can also manipulate cookies using the cookie property of the Document object.JavaScript can read, create, modify, and delete the cookie or cookies that apply to thecurrent web page.• Storing Cookies.• Reading Cookies.• Setting the Cookies Expiration Date.• Deleting a Cookie.
  52. 52. Dialog BoxesAlert Dialog Box - An alert dialog box is mostly used to give a warningmessage to the users. <script type="text/javascript"> <!-- alert("Warning Message"); //--> </script>Confirmation Dialog Box - A confirmation dialog box is mostly used totake users consent on any option. It displays a dialog box with twobuttons: OK and Cancel.If the user clicks on OK button the window method confirm() will returntrue. If the user clicks on the Cancel button confirm() returns false.
  53. 53. Dialog Boxes<script type="text/javascript"> <!-- var retVal = confirm("Do you want to continue ?"); if( retVal == true ){ alert("User wants to continue!"); return true; }else{ alert("User does not want to continue!"); return false; } //--></script>Prompt Dialog Box - The prompt dialog box is very useful when you want topop-up a text box to get user input. Thus it enable you to interact with the user.The user needs to fill in the field and then click OK.This dialog box is displayed using a method called prompt() which takes twoparameters (i) A label which you want to display in the text box (ii) A defaultstring to display in the text box.<script type="text/javascript"> <!-- var retVal = prompt("Enter your name : ", "your name here"); alert("You have entered : " + retVal ); //--></script>
  54. 54. Void keywordThe void is an important keyword in JavaScript which can be used as a unaryoperator that appears before its single operand, which may be of any type.This operator specifies an expression to be evaluated without returning avalue.<script type="text/javascript"> <!-- //--> </script></head><body><a href="javascript:void(alert(Warning!!!))">Click me!</a>Another example the following link does nothing because the expression"0" has no effect in JavaScript. Here the expression "0" is evaluated butit is not loaded back into the current document:<script type="text/javascript"> <!-- //--></script></head><body><a href="javascript:void(0))">Click me!</a></body>
  55. 55. Printing pageMany times you would like to give a button at your webpage to print outthe content of that web page via an actual printer.JavaScript helps you to implement this functionality using print functionof window object.The JavaScript print function window.print() will print the current webpage when executed. You can call this function directly using onclickevent as follows: <form> <input type="button" value="Print" onclick="window.print()" /> </form>
  56. 56. Thank you.