JavaScript Keith Neer CSC 415: Programming Languages William F. Lyle III, PhD. 14 November 2013 Neer 2 History of JavaScript Development In the mid-1990s, the use of the Internet was becoming increasingly popular; however, the user interaction needed adjustments. Brendan Eich, an employee of Netscape at the time, developed a scripting language in ten days that became known as Mocha. This original name was given by the founder of Netscape. Shortly after, the name was evaluated and renamed as LiveScript. Later that year in December, Netscape received a trademark license from Sun. This time, the name changed to JavaScript, not because of the Java programming language, but to support Sun Microsystems. At this time, Sun Microsystems developed a language called Java to compete with the programming language C++. JavaScript is an interpreted language that can be utilized over multiple platforms and is strongly object oriented. JavaScript is not a standalone language, but can be easily embedded and executed in Hypertext Markup Language (HTML) files. JavaScript can support client-side or server-side depending on the needs of the application. The need for JavaScript was to have a lightweight interpreted language that would complement other programming languages such as Java and Microsoft Visual Basic. To this day, JavaScript is the most popular programming language on the web. Its trademark is currently under the Oracle Corporation with Mozilla as one of their entities. Overview of JavaScript Design, Syntax, Semantics Names, Binding, and Scopes JavaScript is very similar to the C-Based languages in terms of naming variables. In JavaScript, the variable names are case sensitive and must start with a letter, dollar sign ($), or an underscore (_). Therefore, the variable names ‘count,’ ‘COUNT,’ and ‘Count’ are each different by these rules. As in most languages, reserved words may not be used as variable names. JavaScript currently reserves 26 key words and potentially 15 additional key words that cannot be used as variable names. There is not a Neer 3 maximum length declared for variable names in JavaScript, however, some environments may dictate the length of the variable. There has been documentation that on some applications, the scripts run slower with abnormally long variable names. JavaScript supports static scoping which is also known as lexical scoping. This type of scoping is used for both variables and functions in JavaScript. For a better understanding, JavaScript has a global scope which is declared at the outer most level. Global scope variables can be used anywhere they are called on in the script. The function scope is where the variable is declared within a function and only lives in that specific function. Once the function is completed, the function-scoped variable is terminated. Data Types JavaScript uses dynamic typing. Dynamic typing means that the same variable can be used for different data types. For example, we declare a variable called ‘test’ to demonstrate dynamic types in JavaScript: Line 1: var test; Line 2: var test = 5; Line 3: var test = “Hello”; In line 1, test is an undefined data type. In line 2, test becomes a number type. In line 3, test becomes a string type. JavaScript supports primitive, composite and special data types. The primitive data types consist of string, number, and Boolean types. A string will handle anything that involves a series of characters or even just a single character. A string in JavaScript can be represented with any text in double quotation marks (“”) or single quotation marks (' '). The string indexes are zero-based, which means the first value is 0, then the next is 1, and to the nth index. The escape character (\) is used in order to display special characters, such as a single quotation mark in a string. For example, “don\'t” would display “don't”, but without the escape character you will receive an error message. The number Neer 4 data type is capable of handling integers, doubles, floats, decimals and other numerical types. JavaScript stores all numbers as a double precision-floating type number. JavaScript stores the numbers in 64-bits. Bits 0 through 51 hold the numbers. The exponent numbers are stored in bit 52 to 62 and the sign bit is stored in bit 63. The Boolean data type is similar to most other languages. It is either true or false. When a Boolean variable is first initialized there is no value. If the value assigned to the Boolean variable is 0, -0, “”, NULL, false, undefined, or Not a Number (NaN) then the Boolean variable is set to false. All other assignments will set the variable to true. Even when the assigned variable is “false”, when written as string it will be true. The composite data types include objects and arrays. JavaScript treats everything as an object; in addition, it allows the programmer to define their own objects. The only data types that JavaScript does not treat as objects are undefined and null. Objects are special in the fact that they have properties and methods that the programmer can use to manipulate them. JavaScript offers different ways to implement user-defined objects. JavaScript supports arrays which allow a variable to hold more than one value at a time. The indexing of the array starts at zero and increases in increments of one. The special data types include undefined and null. Undefined acts more like a property when a variable is declared, but not assigned a value. Basically, undefined means that there is no notion of the variable having any data type and it has never been referenced in that scope. A null is where the variable exists and has a type, but no value assigned to it. Expressions and Assignment Statements In JavaScript there are two types of expressions. There are expressions that assign a value to a variable and there are expressions that only have a value. For example, var x = 3 is an example of assigning a value to a variable, whereas 4 + 8 is an example of only having a value. In the first example there is an example of an assignment operator. It is taking the value of 3 and assigning it to variable x. The second example demonstrates the use of the addition (+) operator without storing the value to any Neer 5 variable. JavaScript provides the following four types of expressions: arithmetic, string, logical, and object. Arithmetic operators take numerical values as parameters and return a single numeric value. JavaScript supports the standard operators that most languages support. They are: addition (+), subtraction (-), division (/), multiplication (*), modular division (%), increment (++), decrement (– –) and unary negation (-). JavaScript provides very little support for string operators, which are the comparison operator and concatenation operator. The comparison operator (==) compares two strings. If the strings do not match, then the operator will return false. This operator is case sensitive. For example, “Name” does not equal “name”. The concatenation operator (+) takes two strings and returns a single string with the two strings appended. Like most languages, logical operators are used with Boolean values; however, in JavaScript they are not limited to Boolean values. JavaScript uses the three main and simple logic operators. They are and (&&), or (||) and not (!). Statement-Level Control Structures Often when writing code, the programmer may want the application to perform a task based off of the outcome of specific actions. For this, the programmer would need to implement a conditional statement. JavaScript provides the user with two main conditional statements, which are switch and if statements. If statements may be used with an else and it may also be nested. If statements and switch statements in JavaScript work like they do in the C-based languages. The programmer will start with the common if <expression> and followed by the condition. If the condition is true, then it will execute the code structure. If it is false, then the application will continue to the next statement. If the application hits an else statement, then the program will execute the code block for when the if statement is false. If the programmer wants to add another condition, then they may add an if statement Neer 6 after the else. This may be repeated until the desired outcome is reached. If the programmer is going to use several if else statements, they should reconsider their design and consider using a switch statement. A switch statement in JavaScript works like it would in other programming languages. The switch statement is used when you are checking the value of a variable with many options, but only one selection can be made. JavaScript offers four ways to implement iterations. There are while, for loop, for/in loop and do while. Each type of loop that JavaScript offers can be modified to do same thing, but each is implemented in a different way. The while loop requires a Boolean expression, and as long as that expression is true, the application will continue to execute that block of code. For the while loop, it is possible that the block of code never gets executed. The following example shows how to implement a basic while loop. While (condition) { //Code block to execute if true }//end while loop This is true for the for loop, but the for loop is set up differently. The for loop has three parameters which can be omitted. The first parameter can be used to declare a variable, but is mainly used to assign an initial value to a variable. The second parameter is the conditional parameter. As long as this parameter is true, the code block will continue to execute. The third parameter is the increment/decrement parameter. This is used to create the value that will eventually create a false condition. This is so it will stop looping when the desired condition is met. The for/in loop is a special type of loop. It is used to iterate through user created objects and arrays. The do while is very similar to a while loop, but the code block is always executed at least once. The condition statement of the while is placed after the code block. Methods and Functions A function is a block of code that can be called by the programmer. Functions are typically used Neer 7 more than once or to simplify written code for better readability. Functions can be called anywhere in the code and can be called when an event occurs. Variables that are going to be used in the function from an outside source may be passed to the function by using parameters or arguments. The programmer may pass as many parameters that they need, but they will need to be separated by using a comma. Functions in JavaScript also allow the programmer to return values if necessary. JavaScript does not require the programmer to declare the return type at the beginning; all they need to do is add a return statement. Usually the return statement is located at the end because the application will leave the function after it hits the return statement. In JavaScript, methods are basically the same thing as a function, but methods are tied with an object. Exception and Event Handling “Event handling plays a large role in JavaScript applications. JavaScript’s interaction with HTML is handled through events that occur when the user or browser manipulates a page” (JavaScript Events). Everything that happens on a web page is an event. This ranges from loading a page, to browsing products, to purchasing products. In JavaScript, events are part of the Document Object Model (DOM) Level 3. With the DOM, every HTML element has the ability to trigger various codes written in JavaScript. JavaScript provides various levels of event handling to make ease of handling events. Event handling can be used to trigger a variety of events to occur. For example, change the text or color of a button with the mouse by hovering over the button, open a new page when the button is clicked, and download a file with a button click. Due to the nature of the environment that JavaScript will be used in, there is a high likelihood that errors will occur. There could be errors for invalid inputs, unable to access server, or even lack of internet access. Errors are unforeseeable in JavaScript because of its operating environment. JavaScript does provide try catch statements and also allows programmers to throw errors. The try catch statements as well as the throw statements work very similarly as they do in the C-based languages. In Neer 8 the try block, the programmer will be able to define a block of code to be tested for errors and typos. The catch block will allow the programmer to write a block of code that is to be executed if an error occurs. The programmer can use multiple catch blocks per a try statement. This is so they will be able to catch a variety of errors and be able to handle them in unique ways. The throw statement allows the programmer to create custom errors or to throw an exception. JavaScript also allows the programmer to rethrow exceptions. Concurrency JavaScript provides concurrency based off of an event loop. Concurrency in JavaScript is unique compared to the C-based languages. Concurrency will allow the programmer to move expensive computations to other threads; this will permit responsive programs and open the doors to true parallel programming. The ideal frame per second in JavaScript is 16ms per frame. Responsive programming is when the programmer has an expensive computation and does not want to block or slow down the User Interaction. Parallel Programming is when the programmer wants to use multiple CPU cores by having computations running concurrently to solve a specific task. Responsive programming can be used in rendering PDFs, compressing an image to custom a file format, compute A* algorithm in a game and so on. Parallelization is not a common practice for web applications, but is currently being used on desktop and mobile applications. The idea of using parallelization for webpages is currently being worked on. The idea is to use multiple Web Workers to run in parallel and work on the same task but at a faster rate than a single Web Worker. Concurrency is a very powerful model to implement in JavaScript applications. Some of the computation will appear sluggish when 16 frames per second are exceeded. Concurrency will allow the programmer to decrease the frames per second. Evaluation of JavaScript Readability is an important evaluation aspect when it comes to evaluating programming languages. Being able to read the code affects how easily it will be to maintain and ease for other Neer 9 programmers to use the script. JavaScript overall is relatively easy to read and understand to an experienced programmer; however, to a beginner programmer, it may take some time to read and understand JavaScript. The main issue with readability in JavaScript is understanding that you may be using more than one language. As I was learning JavaScript, I was writing the code with HTML and CSS. HTML was used to implement the scripts. For majority of my applications, I was putting the script directly into HTML. Writability in JavaScript was relatively easy for me. JavaScript’s purpose was to be an easy and quick scripting language to better the experience of web users. The biggest problem with writing JavaScript is finding a good Integrated Development Environment (IDE) to catch some of the syntax errors. Writing JavaScript in Notepad++ was not ideal. I was unfamiliar with IDEs for JavaScript, so I started in Notepad++ and tried to run the scripts. My first reel scripts did not run or did run properly because of some of the errors I did not see. Other than that JavaScript was pretty easy. Reliability of JavaScript is not at its best. Since JavaScript can be used over a multitude of web browsers and platforms, there is a tendency to have issues with compatibility. JavaScript and the numerous web browsers are working to solve these issues, but it would be a lot easier if developers followed the rule “write once, run anywhere.” Many developers test their applications on very few browsers, but users will be utilizing a multitude of browsers for their everyday use. This can become costly when it comes to keeping customers and users. Overall, JavaScript is a powerful and useful language to create a better web browsing experience. JavaScript is now starting to play more roles in operating systems, especially with the recent release of Microsoft Windows 8. JavaScript is a quick and easy language to learn if you have any prior experience with C-based languages. I highly recommend using JavaScript to create better interactions for web page users. Neer 10 Bibliography Annotated ES5. (n.d.). Annotated ES5. Retrieved September 23, 2013, from http://es5.github.io/#x10.23.2013 Efficient Encapsulation of JavaScript Objects. (n.d.) About Code. Retrieved September 18, 2013, from http://aboutcode.net/2011/10/04/efficient-encapsulation-of-javascript-objects.html Expressions and Operators. (n.d.). Mozilla Developer Network. Retrieved September 10, 2013, from https://developer.mozillaorg/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators JavaScript Closure. (n.d.). Jibbering. Retrieved September 8, 2013, from jabbering.com/faq/notes/closures JavaScript Data Types. (n.d.). W3Schools Online Web Tutorials. Retrieved September 13, 2013, from http://w3schools.com/js/js_datatypes.asp JavaScript Events (n.d.). TutorialsPoint. Retrieved October 28, 2013, from http://www.tutorialspoint.com/javascript/javascript_events.htm JavaScript Scoping and Hoisting. (n.d.). Adequately Good – by Ben Cherry. Retrieved September 20, 2013 from http://adequatelygood.com/JavaScript-Scoping-and-Hositing.html JavaScript/Control Structures – WikiBooks,(n.d.). Wikibooks. Retrieved September 22, 2013 from http://en.wikibooks.org/wiki/JavaScript/Control_Structures JavaScript Language. (n.d.). Scope (Computer Science) – Wikipedia. Retrieved September 9, 2013, from http://en.wikipedia.org/wiki/Scope_%28computer_science%29#JavaScript Osmani, Addy. (2012). Learning JavaScript Design Patterns. Cambridge: O’Reilly. Simpson, Kyle. (2012). JavaScript and HTML5 Now. Cambridge: O’Reilly. Wright, Tim. (2013). Learning JavaScript: A Hands on Guide to the Fundamentals of Modern JavaScript. Boston: Addison-Wesley. Writing Object-Oriented JavaScript Part 1. (n.d.). Code Project. Retrieved September 10, 2013, from http://www.codeproject.com/Articles/5608/Writing-Object-Oriented-JavaScript-Part-1