Archive for tag Javascript
July 08, 2008 at 10:47 AM · Posted under learning, programming, quicklinks
From Cut and paste one line of code to make any website editable:
javascript:document.body.contentEditable='true';
document.designMode='on'; void 0
What’s that you ask? That is an awesome small chunk of JavaScript that allows you to make the text of any website editable within the browser window. Just:
- Copy the code to the clipboard
- Browse to the site you want to edit
- Paste the code into the address bar and press return
- Edit the site’s text however you like
Let the pranking begin.
Comment
May 26, 2008 at 11:33 AM · Posted under learning, programming
Notes I took while watching the second video of Douglas Crockford’s JavaScript lecture
Statements
JavaScript has all the statements that you’d expect to find in any of the other C langauges. e.g. if, switch, while, do, for, break, continue, return, try/throw; but there are some differences in how they are used.
You can label loops and then break out of them by label. Handy if you want to break out of a nest of loops.
The for statement can loop through an array and through the members of objects.
Unfortunately for looping through an object will take you through all the kys of all the objects that the object inherits from. To prevent this you have to test that the object being looped through itself has that property. This is highly recommended to avoid strange behavior.
Switch values don’t need to be numbers, can be strings
Case values can be expressions – handy
You have to explicitly terminate case clauses, as usual.
Switch statements allow a default case.
Throwing exceptions behaves typically, as does try/catch.
You can generate exception objects by calling its new constructor, or use with object literal
JavaScript comes with the following exceptions:
- Error
- EvalError
- RangeError
- SyntaxError
- TypeError
- URIError
You can, of course, make up your own exceptions.
Avoid using the with statement. It was designed to be a convience for dealing with objects, but there is an error in its design leading to ambiguous statements.
There is a function statement used for declaring functions.
The var statement defines variables within functions. JavaScript is loosely typed so you just declare the variable and optionally initialize.
Without initialization variables are undefined.
Unless you limit the variable scope with var they are assumed to be global. :-/
Unlike most C languages, blocks do not have scope. There is only function scope.
Return can return an expression or just return;
return; doesn’t return nothing, it returns undef
When used in constructors they will return the new object.
Objects
Objects contain data and methods.
Objects only inherit from other objects, there is no concept of a Class.
Objects in JavaScript are an unordered collection of name/value pairs. Names are strings, values are anything including other objects or expressions.
Every object is essentially a tiny database
Object Literals
Object Literals are an easy way of creating a new object. The are data wrapped in { }. ”:” separates names and values. ”,” separates pairs. An object literal can be used anywhere a value can appear.
Object Literal Example: var myObject = {firstName: “Stephen”, ‘lastName’:’Ball’, middleInitial:’A’, age: 29};
// These syntaxes are interchangable
var theName = myObject.firstName;
var destination = myObject['firstName'];
Maker functions can be used to build objects. Pass material to maker function and it will make an object and return it
Object Literals can have nested objects, or object literals, as values.
If we pass an object literal to a function, the function doesn’t know if the object already existed or was a literal declared with the call.
Rather than define a function that takes a lot of parameters (e.g. more than two or three), think about passing an object instead.
Objects in JavaScript can be augmented at anytime with new methods and data. There is no class, so obviously no need to define a new one. Just modify the object you want to expand directly.
// to add data to an object simply set it
existingObject[newKey] = newValue;
existingObject.newKey = newValue;
Object Linkage
When objects are created they have a secret link to another object. This is how inheritance is achived.
If a member is requested from an object and the object doesn’t have it, JavaScript silently follows the link to the secret object and sees if it has the member and, if so, returns it. The child object now has the data member locally. Odd side effect: if you delete a data member of a child object that is set in the parent object then the child object’s data isn’t really deleted. If requested the “deleted” data will be fetched from the parent object again without notice.
The secret link is not used for storing new values in the parent object. Data is only retreived.
Obviously this means that there is only single inheritence in JavaScript. Also that there is truly no Class equivalent in JavaScript. Objects only inhereit from objects.
We can use the object function to make a new empty object that has that linkage to an existing object. ex: var myNewObject = object(myOldObject);
Some languages have classes, methods, constructors, modules: JavaScript has functions, and functions do the work of all of those. This allows greater expressive power, but requires a different way of thinking.
There is garbage collection in JavaScript.
All objects are linked directly or indirectly to Object.prototype that has some basic methods, but no copy method and no comparison method.
You can see if two objects are, in fact, the same object; but not tell whether they are equivilent.
Object Construction
There are three ways to create a new, empty object:
- new Object{}
- {}
- object(Object.prototype)
All three return exactly the same object, {} is recommended for conciseness.
Objects can be passed to functions as arguments and returned from fucntions.
Objects are always are passed by reference.
=== between objects will only return true if both objects are the same object.
The delete operator will remove members from objects, delete myObj[key] by changing the value to undefined.
Arrays
Arrays are unusual:
- array inherits from object
- array indexes are converted into strings and then used as names for retrieving values
- very efficient for sparse arrays, but not for everything else
- arrays aren’t typed
- arrays have length member, it is always 1 larger than the highest integer subscript which may not be its actual length (!)
- it does allow a for loop to go through the array easily by just saying less than array.length
- do not use for…in with arrays
Array Literals
- uses []
- can contain any number of expressions
- new items can be appended, arr[arr.length] = value
- can’t use dot notation with arrays, subscript notation instead
- [] is the preferred method to create a new array, not the new array construct
Array Methods
- concat
- join
- pop
- push
- slice
- sort
- splice
Deleting from array: delete array[number] removes element but leaves a “hole” in the array as an undefined value. To completely delete a value and index you need to splice it out.
Use Object or Array?
Since objects and arrays are so similar, when do you use which?
Use objects when names are arbitrary strings, e.g. associative array.
Use arrays when names need to be sequential.
Arrays all inherit from array.prototype.
If you get a value, there are two methods to tell whether it is an array or an object:
- value.constructor === Array
- value instanceof Array
BUT neither of those methods work when value comes from a different frame, a bug in the language.
You can’t inherit from an array because the value produced will be an object, not an array. You can augment an individual array by adding methods to it. You can also assign methods directly to Array.prototype to change all arrays in the program.
Comment
May 26, 2008 at 11:26 AM · Posted under learning, programming
Notes I took while watching the first video of Douglas Crockford’s JavaScript lecture
Language Outline
“script” suggests that JavaScript isn’t a real programming language, Douglas posits that not only is it a real programming language, but a pretty good one.
The language does contain some design errors.
Early bad implementations resulted in JavaScript getting a bad reputation. The implementation are now good.
Programming for the browser and DOM is extremely difficult. A lot of people think that the problem is javacsript itself, but it’s more the environment.
Books on JavaScript are almost (as of 2007) universally bad. The Definitive Guide from O’Reilly is the “least bad” book.
JavaScript standard defined by ECMA, but the standard is not very good. Very difficult to read which led to the bad book problem – no good authoritive source to reference.
JavaScript is a functional language like lisp and scheme.
JavaScript’s History
1992: Jim Gosling started working on a language he called C++ then changed to Oak. Gosling go into a new startup, Oak was used in applications. Company fail. Moved back to Sun. What to do with Oak? Needed new name, Java. Application to demo new language would be web browser, HotJava.
Meanwhile at Netscape. They looked at Java but decided that it was too heavy for browsers. Brendan Ike had idea to do dialect of scheme in the browser, but management said to make a scripting language that looked like Java. That became Livescript. First scripting language to be put into a browser, and first to be put on a server.
Reason Netscape and Java so exciting at the time was that they were envisioned as a way to escape from Microsoft: applications on the net. They decided to ally. Sticky part: what to do with Livescript. A divide between those that wanted Java to be the language of the web, Netscape refused for above reasons. So Livescript name changed to JavaScript and then Sun took naming control of the language.
Microsoft didn’t like this so they reverse engineered the language into JScript.
Netscape didn’t care for this at all. To prevent Microsoft from assuming control of the language they decided to make JavaScript a standard. They took it to the European Computer Manufactors Association (ECMA) because they thought that their language standard would just be rubber stamped there. Unfortunately Microsoft was a member of ECMA, so from the first day Microsoft dictated the standardization. Microsoft had made some errors while reverse-engineering JavaScript into JScript, and they insisted that those errors become part of the standard. It was very important to Microsoft at that time to never do anything to cause anyone’s programs to break. ECMA agreed.
What is JavaScript?
JavaScript is not a web toy language, it is real, useful, and sophisticated. Also very effective.
JavaScript’s key set of ideas:
- load and go delivery: programs are delivered to the execution site as source code. Reasoning is that it was intended to be embedded in webpages, which are text. This is, of course, no longer the preferred way to getting programs to browsers but the legacy remains.
- Loose Typing
- Objects are general containers: unification of objects and hash tables
- Prototypal inheritance: much different than Class inheritance. Objects can only inherit from other objects. There are no Classes.
- Lambda: functions are first class objects.
- Linkage through global variables. Because of “load and go” JavaScript doesn’t have any kind of linker. Separate compilation units are combined into a global namespace, which is a really bad idea.
JavaScript has a small set of possible values
- Numbers
- Strings
- Booleans
- Objects
- null
- undefined
JavaScript doesn’t have multiple number types (e.g. Integer, Float). There are, in fact, no integers. All numbers are represented as 64-bit floating point (i.e. doubles). This means that common arithmetic can act strangely: .1 + .2 != .3
If dealing with decimals need to multiply by 100 for the operations, then scale back.
NaN is a value that is “not a number”. It is returned as the result of undefined or erroneous mathematical statements, e.g. 0/0. It is toxic: any arithmetic operation with NaN as an input will return NaN. NaN is not equal to anything, even itself. NaN === NaN is false. NaN is also not less than NaN or greater than NaN. But if you get typeof NaN it is Number.
Number function converts string into a number. Produces NaN if it has a problem. Similar to + operator.
parseInt function parses integers from a string. Generally you should include radix argument to specify the base we are parsing.
Like Java, JavaScript has a separate Math object. This is an unfortunate idea. The Math object contains a number of useful functions e.g. abs, floor, log, random, round, sqrt.
JavaScript has Strings. They are a sequence of 0 or more 16-bit characters encoded in UCS-2 (not UTF-16 as it has no awareness of pairs for extended character range). The extra characters of UTF-16 are very rarely used, but it is something to be aware of.
No character type in JavaScript. A “character” is a string of one character.
Strings are immutable.
Similar strings are equal with
String literals can be written with single or double quotes, they are the same.
All Strings have a "length" method that returns the number of 16-bit "characters" in the string. This won't necessarily be the number of unicode characters in the string.
String function converts a number into a string.
Strings are objects and so have methods, e.g.:
- charAt
- concat
- indexOf
- lastIndexOf
- match
- replace
- search
- slice
- split
- substring
- toLowerCase
- toUpperCase
Two boolean values in JavaScript: true and false.
Boolean function will take a value and returns its boolean value.
Null is the value that isn't anything.
Undefined is the value that isn't even null. It is the default value for variables. This is confusing because if you define a variable without initializing it it will have the value "undefined".
Undefined is the value you get when you extract a member from an object that doesn't have that member. It is the "missing value" value.
Values that evaluate as false, everything else evaluates as true:
- false
- null
- undefined
- empty string
- 0
- NaN
After these simple values, everything else in JavaScript is Objects. JavaScript is actually an object-oriented language.
Dynamic Objects
- unification of Object and Hashtable
- new Object() produces an empty container of name/value pairs
- Name can be any string, value can be any value except undefined.
- Object members can be access with dot notation or subscript notation: myObj.key or myObj['key']
- Although they are hases, no hash nature is visible: no hash methods
JavaScript is loosely typed, which means that any variable is capable of receiving any value. The values do have a type (so the language isn't "untyped"), but variables aren't bound to them.
JavaScript is syntactically a C family language. Differs from C with its type system which allows functions (which are objects) to be values.
Identifiers follow same rules as most C languages.
Variable names match: /^[A-Za-z_$]*$/
By convention everything is lowercase except for constructors.
Using the initial _ should be reserved for implementations, but are very popular. Initial $ should be reserved for machines: macro processors, etc. Ajax programmers use $ variables a lot for some reason.
JavaScript has a LOT of reserved words, but only a few are used.
Two comment styles: // or /*
Common operators that you’d expect for a C language.
+"42" = 42, just like Number("42")
Division of two integers can produce a non integer result
and != do type coercion, so always use === and !== which confirm variables are same value and type.
&& is the guard operator or “logical and”. If first operand is truthy then the result is the second operard, otherwise result is first operand. Can be used to avoid null references.
return a && a.member;
does the same as:
if (a) {
return a.member;
} else {
return a;
}
|| is default or “logical or” operator. If first operand is truthy then result is first operand, otherwise second operand. Can be used to fill in default values.
// if formField is true, then userInput = formFieldValue
var userInput = formFieldValue || default_value;
! is “logical not” operator. If operand is truthy the result is false and vice versa. From this if you do !!value you will get its boolean representation.
JavsScript has Bitwise Operators
& | ^ >> >>> <<
The bitwise operators convert the operand into a 32-bit signed integer, do the operation, then convert the result back into a 64-bit floating point. Unlike normal bitwise operation, this isn’t faster. So unless you really need a bitwise operation don’t use them.
Comments (2)
May 15, 2008 at 03:32 PM · Posted under learning, programming, quicklinks, techtips
Javascript Video Lectures
The videos are extremely well done. I rank them right up there with the videos of Knuth lecturing about TeX for clarity and flow.
Comment