Overview JavaScript (JS) is a lightweight, interpreted, object- oriented language with first-class functions. It is a prototype-based, multi-paradigm scripting language that is dynamic, is type safe, and supports multiple programming styles. ● Originally released in 1995 with beta releases of Netscape Navigator. ● Usually used on the web browser but also used in other environments (ex: CouchDB, Grunt, node.js, Rhino).
Problem Since it is a small, lightweight language with a familiar syntax, it is easy to start using JavaScript. It is usually not used as a standalone language, so it is possible to get by without using more complex JavaScript. This can lead to issues because there are many times when JavaScript may not behave the way we assumed it would. Additionally, there are many features and techniques that are not obvious when looking at JavaScript.
Datatypes JS has the types Boolean, Number, String, null, and undefined. null is a special keyword denoting a null value. undefined is a top-level property whose value is undefined. null and undefined are primitive values.
Dynamic typing Because JS is a dynamically typed language, variables do not have to be specified when declared and data types are converted automatically. The code below is valid. var foo = null; foo = 12; foo = "012"; console.log(foo); >> 012
Converting a number to string JavaScript offers different ways to explicitly convert a Number to a String. var foo = 23, bar; // Calling the toString method bar = foo.toString(); // Instantiate a new String object bar = new String(foo); // Concat with an empty string bar = '' + foo; Test results: http://jsperf.com/scunliffe-number-to-string
Converting a string to a number The parseInt and parseFloat can be used to convert a String to a Number. The radix should always be supplied because it defaults to 8 in certain cases. var foo = "023.5"; var bar; // parseInt(string, radix); bar = parseInt(foo, 10); // parseFloat(string) bar = parseFloat(foo);
Variables By default, variables that are declared have the value undefined. Trying to evaluate a variable that has not been declared throws an Exception. var first; console.log("Value: " + first); >> Value: undefined console.log("Value: " + second); >> throws ReferenceError exception
Testing equality The == operator is the equality operator, while the === operator is known as the identity operator. The equality operator (==) performs type conversions before testing for equality. var first; var second = null; console.log("first: " + first + ", second: " + second); >> first: undefined, second: null console.log(first == second); >> true console.log(first === second); >> false
Testing equality Other unexpected results from type conversions. var foo = "012"; console.log(foo == 12); >> true console.log(foo === 12); >> false var bar = null; if (bar) { console.log("bar is true"); } else if (bar == false) { console.log("bar is false"); } else { console.log("????"); } >> ???? // bar evaluates to false, but is not equal to false
Testing truth The values below will evaluate to false. ● false ● undefined ● null ● 0 ● NaN ● "" All other values, including all objects evaluate to true when passed to a conditional statement.
Checking types The typeof operator returns a string indicating the type of the unevaluated operand. Type Result undefined "undefined" null "object" Boolean "boolean" Number "number" String "string" Host object (provided by the JS environment) Implementation-dependent Function object (implements [[Call]] in ECMA-262 terms) "function" E4X XML object "xml" E4X XMLList object "xml" Any other object "object"
Arrays Arrays can be created in multiple ways and can contain multiple datatypes. // these three statements are equivalent var arr = new Array(element0, element1, ..., elementN); var arr = Array(element0, element1, ..., elementN); var arr = [element0, element1, ..., elementN]; // the statements below are valid var foo = [true, 123, "word", ,new Date()]; var bar = new Array("wow", 12.34, null);
Creating arrays Arrays can be created by listing the array’s elements, but if only one integer is used, it will be considered the length of the array. var bikes = new Array("trek"); console.log(bikes.length); >> 1 var boats = new Array(13); console.log(boats.length); >> 13 // this notation can be used instead var planes = [13]; console.log(planes.length); >> 1
Arrays Elements that are not defined can be added to arrays, and the length of an array can be accessed in multiple ways. var arr = ["one", "two", ,"four"]; console.log(arr[1]); >> two console.log(arr[2]); >> undefined console.log(arr.length); >> 4 console.log(arr["length"]); >> 4
Arrays The in operator returns true if the specified property is in the specified object. var power = new Array("ls1", "rb26", "2jz"); console.log(3 in power); >> false console.log(length in power); >> true var power = new Array("ls1", "rb26", "2jz"); console.log(2 in power); >> true // the in operator works on all objects var bike = {make: "Ducati", model: "899 Panigale", year: 2013}; console.log("model" in bike); >> true
Modifying arrays Elements can be added to arrays using the index or push method. Using the concat method results in a new array. var arr = [0, 1, 2]; arr[arr.length] = 3; console.log(arr); >> [0, 1, 2, 3] arr.push(4); console.log(arr); >> [0, 1, 2, 3, 4] arr.pop(); console.log(arr); >> [0, 1, 2, 3] var newArr = arr.concat(5, 6); console.log(newArr); >> [0, 1, 2, 3, 5, 6]
Sorting arrays By default, the sort method sorts all elements alphabetically. var z = [0, 2, 10]; console.log(z.sort()); >> 0,10,2 var numeric_sort = function (a, b) { return a > b ? 1 : a < b ? -1 : 0; }; // using array.sort([compareFunction]) console.log(z.sort(numeric_sort)); >> 0,2,10
Variable scope JavaScript has global and local scopes. A variable that is declared outside of a function definition is a global variable, and its value is accessible and modifiable. A variable that is declared inside a function definition is local. JavaScript does not have block scope. if (true) { var foo = "scope"; } console.log(foo); >> scope
Variable scope In cases where a local variable has the same name as a global variable, the local variable will be used. var foo = "outside"; (function (){ var foo = "inside"; console.log(foo); })(); >> inside
Variable scope Variables are evaluated as if they were declared at the beginning of whatever scope they exist in. In the case below, foo is undefined because the scope is local. var foo = "outside"; (function main (){ console.log(foo); var foo = "inside"; })(); >> undefined
Variable scope If a variable is declared without using the var keyword, the variable is automatically made global. (function () { foobar = "hi there"; })(); console.log(foobar); >> hi there Explicitly declaring variables is a better practice because it won’t clutter the global scope.
Function scope JavaScript has function scope and will work it’s way down the chain to resolve variables. // running nested anonymous functions (function parents() { var dad = "Pop"; (function kids() { var son = "sonny"; console.log(dad + " and " + son); })(); })(); >> Pop and sonny
Sources ● Mozilla Developer Network https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide ● Wikipedia http://en.wikipedia.org/wiki/Javascript ● WebPlatform.org http://docs.webplatform.org/wiki/javascript ● Internet Explorer Dev Center http://msdn.microsoft.com/en-us/library/ie/d1et7k7c(v=vs.94).aspx ● Scope and this in JavaScript http://javascriptplayground.com/blog/2012/04/javascript-variable-scope-this/ ● JavaScript: Better and Faster http://www.bcherry.net/talks/js-better-faster ● Numerical array sorting in JavaScript http://andrew.hedges.name/blog/2008/08/26/numerical-array-sorting-in-javascript