Javascript


Intro
Unlike most programming languages, the JavaScript language has no concept of input or output. It is designed to run as a scripting language in a host environment, and it is up to the host environment to provide mechanisms for communicating with the outside world. The most common host environment is the browser. JavaScript is an object-oriented dynamic language with types and operators, standard built-in objects, and methods.
JavaScript
borrows most of its syntax from Java, but is also influenced by Awk, Perl and Python. It is an interpreted programming language with object-oriented capabilities. The JavaScript programming language is
not
part of the Java platform. JavaScript does not create applets or stand-alone applications. In its most common form, JavaScript resides inside HTML documents, and can provide levels of interactivity to web pages that are not achievable with simple HTML. Client-side JavaScript does not allow the reading or writing of files. This has been kept for security reason. JavaScript cannot be used for networking applications because there is no such support available. JavaScript doesn't have any multithreading or multiprocessor capabilities. JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs. JavaScript, allows you to omit this semicolon if each of your statements are placed on a separate line. JavaScript is a case-sensitive language. JavaScript's types are: Number String Boolean Symbol (new in Edition 6) Object Function Array Date RegExp null undefined
Declarations
There are three kinds of declarations in JavaScript. var Declares a variable, optionally initializing it to a value. let Declares a block scope local variable, optionally initializing it to a value. const Declares a read-only named constant.
// is comment
Text between the characters /* and */ is treated as a comment. Semicolons are optional in JavaScript. To create a value, you must merely invoke its name. The main thing to do with numbers is arithmetic. Arithmetic operations such as addition or multiplication take two number values and produce a new number from them. The + and * symbols are called operators.
Booleans
The primitive boolean type comprises the values true and false. console.log(3 > 2) // true Mostly, JavaScript runs in your web browser alongside HTML and CSS, and can be added to any web page using a script tag.
The script element
can either contain JavaScript directly (internal) or link to an external resource via a src attribute (external) SCRIPT tags are not case sensitive but Javascript very definitely is. alert("Hello World") works but Alert("Hello World") makes error. examples: alert("Hello World") confirm("OK or Cancel?") prompt("Favourite Colour?", "Red") Be sure that your JavaScript files (.js) do not include the < script > tag. They should only contain HTML commenting and JavaScript code -- nothing more. document.write("Hello World!") document.write can be used to write text, HTML, or a little of both. var x; // declaring a variable x = 3 + y; // assigning a value to the variable `x` foo(x, y); // calling function `foo` with parameters `x` and `y` obj.bar(3); // calling method `bar` of object `obj` // A conditional statement if (x === 0) { // Is `x` equal to zero? x = 123; } div class="headz">Script tag The script tag takes two important attributes - Language This attribute specifies what scripting language you are using. You may find this attribute in out dated scripts. It is obsolete and dont use it for JavaScript. Type This attribute is what is now recommended to indicate the scripting language in use and its value should be set to "text/javascript". The older HTML4 standard required this attribute to be set, but HTML5 allows it to be absent.
External scripts
Usually, most JavaScript code is put into an external file, which is attached to HTML, like this: <head> <script type="text/javascript" src=filename.js><script> </head> If src attribute is present then tag contents is ignored. Statements Versus Expressions Statements do things. A program is a sequence of statements. Here is an example of a statement, which declares (creates) a variable foo: var foo; Expressions produce values. They are function arguments, the right side of an assignment, etc. Heres an example of an expression: 3 * 7

Intro2
Constants
Same as for a variable identifier: it must start with a letter, underscore or dollar sign and can contain alphabetic, numeric, or underscore characters. const prefix = '212';
Events in javascript
The building blocks of an interactive web page is the JavaScript event system. An event in JavaScript is something that happens with or on the webpage. A few example of events: A mouse click The webpage loading Mousing over a hot spot on the webpage, also known as hovering Selecting an input box in an HTML form A keystroke
Numbers and dates
Decimal numbers 0888 // 888 parsed as decimal Binary numbers Octal numbers Hexadecimal numbers The built-in Math object has properties and methods for mathematical constants and functions. Math.PI Math.sin(1.56)
Text formatting
JavaScript's String type is used to represent textual data 'foo' "bar" The String object is a wrapper around the string primitive data type. var s = new String("foo"); // Creates a String object console.log(s); // Displays: { '0': 'f', '1': 'o', '2': 'o'} typeof s; // Returns 'object'
Internationalization
The DateTimeFormat object is useful for formatting date and time. var msPerDay = 24 * 60 * 60 * 1000;
Regular Expressions
Regular expressions are patterns used to match character combinations in strings. In JavaScript, regular expressions are also objects. These patterns are used with the exec and test methods of RegExp, and with the match, replace, search, and split methods of String. This chapter describes JavaScript regular expressions.
Indexed collections
An array is anrdered set of values that you refer to with a name and an index. var arr = new Array(element0, element1, ..., elementN); An array is a variable that can store many variables within it. Creating an array is slightly different from creating a normal variable. Because JavaScript has variables and properties associated with arrays, you have to use a special function to create a new array. var myArray = new Array(); myArray[0] = "Football"; myArray[1] = "Baseball"; myArray[2] = "Cricket";
Keyed collections
Map and Set objects contain elements which are iterable in the order of insertion.
Working with objects
An object is a collection of properties, and a property is an association between a name (or key) and a value
Iterators and generators
An object is an iterator when it knows how to access items from a collection one at a time, while keeping track of its current position within that sequence.
Exception Handling
Strict mode enables more warnings and makes JavaScript a cleaner language (nonstrict mode is sometimes called sloppy mode). Variable Scoping and Closures In JavaScript, you declare variables via var before using them. Variables Are Hoisted Each variable declaration is hoisted: the declaration is moved to the beginning of the function, but assignments that it makes stay put. Objects JavaScript objects can be thought of as simple collections of name-value pairs. As such, they are similar to dictionaries in Python and hash tables in C and C++
JavaScript Display Possibilities
JavaScript can "display" data in different ways: Writing into an alert box, using window.alert(). Writing into the HTML output using document.write(). Writing into an HTML element, using innerHTML. Writing into the browser console, using console.log(). Using document.write() after an HTML document is fully loaded, will delete all existing HTML. A JavaScript library is a library of pre-written JavaScript which allows for easier development of JavaScript-based applications, especially for AJAX and other web-centric technologies.
JavaScript Reserved Words
Words with a special meaning, such as var, are keywords, and they may not be used as variable names. break case catch class const continue debugger default delete do else enum export extends false finally for function if implements import in instanceof interface let new null package private protected public return static super switch this throw true try typeof var void while with The following three identifiers are not reserved words, but you should treat them as if they were: Infinity NaN undefined
Variables
...are case-sensitive, must begin with a letter or an underscore character and contain no spaces... The variable should contain only letters, numbers, a dollar sign or underscore. number1 moms_phone_number $firstName _123test Not: 1number moms phone number "firstName"
Declaring variables
With the keyword var: var x = 42 (local or global variables). With the keyword let: let y = 13. (local variable). JavaScript Variable Scope Global Variables - A global variable has global scope which means it can be defined anywhere in your JavaScript code. Local Variables - A local variable will be visible only within a function where it is defined. After a variable has been defined, its name can be used as an expression. The value of such an expression is the value the variable currently holds. Here is an example: var ten = 10; console.log(ten * ten); // ? 100
Data structures and types
Data types Boolean. true and false. null. A special keyword denoting a null value. Because JavaScript is case-sensitive, null is not the same as Null, NULL, or any other variant. undefined. A top-level property whose value is undefined. Number. 42 or 3.14159. String. "Howdy" Symbol (new in ECMAScript 6). A data type whose instances are unique and immutable. Object Data type conversion JavaScript is a dynamically typed language. That means you don't have to specify the data type of a variable when you declare it. Converting strings to numbers In the case that a value representing a number is in memory as a string, there are methods for conversion. parseInt() parseFloat()
Timing Events
The window object allows execution of code at specified time intervals. These time intervals are called timing events. The two key methods to use with JavaScript are: setTimeout(function, milliseconds) Executes a function, after waiting a specified number of milliseconds. setInterval(function, milliseconds) Same as setTimeout(), but repeats the execution of the function continuously. window.setTimeout(function, milliseconds); The window.setTimeout() method can be written without the window prefix. The first parameter is a function to be executed. The second parameter indicates the number of milliseconds before execution. <button onclick="myVar = setTimeout(myFunction, 3000)">Try it</button> <button onclick="clearTimeout(myVar)">Stop it</button> The setInterval() method repeats a given function at every given time-interval. window.setInterval(function, milliseconds) var myVar = setInterval(myTimer, 1000); function myTimer() { <!DOCTYPE html> <html> <body> <p>A script on this page starts this clock:</p> <p id="demo"></p> <button onclick="clearInterval(myVar)">Stop time< /button> <script> var myVar = setInterval(myTimer ,1000); function myTimer() { var d = new Date(); document.getElementById("demo").innerHTML = d.toLocaleTimeString(); } </script> </body> </html>
Javascript Arrays

var my_array = [10, "ten", true]; This sets up an array to hold three values all under the single variable name we called my_array. Notice that you can store numbers, strings of text, and Boolean values in an array. Each value needs to be separated by a comma. The values need to go between two square brackets and after an equal sign. To get at the values in your array you use index value. my_array[0] my_array[1] my_array[2] my_array[0] will hold the value 10 my_array[1] will hold the text "ten" my_array[2] will hold the Boolean value true. To write the values to a web page: document.write( my_array[0] + "<BR>"); document.write( my_array[1] + "<BR>"); document.write( my_array[2] + "<BR>");