Interesting bits of javascript


// JavaScript - Miscellaneous

// Useful sites for front-end development:

// People that inspire me:
Douglas Crockford
John Resig
Nicholas C. Zakas
Christian Heilmann
Joe Hewitt
Addy Osmani

// Debugging tools:
Ethereal / Wireshark
Microsoft Developer Tools
IE Inspector

BOM: Browser Object Model. It provides interaction with the browser. 
  The default object of browser is window.
DOM: Document Object Model.  A document object represent the html document. 
  It can be used to access and change the content of html.

// There are 3 ways to create object in JavaScript:
1. By object literal: emp = {};
2. By creating instance of Object
3. By using Object constructor

// The value of !'bang' is false.

// The value of of parseFloat('12.3.4') is 12.3

// The value of Math.max([2,3,4,5]) is NaN

// To implement chaining:
    first: function() { console.log('first');   return obj; },
    second: function() { console.log('second'); return obj; },
    third: function() { console.log('third');   return obj; }

// Animation:
function moveLeft(elem, distance) {
  var left = 0;
  function frame() {
    left++; = left + 'px';

    if (left == distance)
  var timeId = setInterval(frame, 10); // draw every 10ms

// Building blocks of HTML5:
1. Better support for video and audio
2. Canvas and SVG
3. New communication API
4. Geolocation API
5. Web-worker API

The purpose of wrapping the entire content of a JavaScript source file in a 
function block is to make sure that particular block has access to the variables
that it needs without interference from outside.  This technique creates a 
closure around the entire contents of the file which, perhaps most importantly, 
creates a private namespace and thereby helps avoid potential name clashes 
between different JavaScript modules and libraries.  This also allow for an 
easily referenceable (presumably shorter) alias for a global variable. This is 
often used, for example, in jQuery plugins. jQuery allows you to guarantee that 
the $ refer to the jQuery global variable.

JavaScript is a multi-paradigm language, supporting imperative/procedural 
programming along with OOP (Object-Oriented Programming) and functional 
programming. JavaScript supports OOP with prototypal inheritance.

// Functional Programming:
Functional programming produces programs by composing mathematical functions 
and avoids shared state & mutable data.  Functional programming was heavily
inspired by lambda calculus.
F Sharp, OCaml, etc…

// Two-way data binding:


side-effects which are harder to follow and understand.

data flow.  Angular is a popular framework which uses two-way binding.

JavaScript is a lightweight, cross-browser, interpreted programming language with 
object-oriented capabilities that allows you to build interactivity into 
otherwise static HTML pages.  Advantages of using JavaScript:

1. Less server interaction − You can validate user input before sending the page 
2. Immediate feedback to the visitors − They don't have to wait for a page 
   reload to see if they have forgotten to enter something.
3. Increased interactivity − You can create interfaces that react when the user 
4. Richer interfaces − You can use JavaScript to include such items as 

Disadvantages of using JavaScript:

1. Client-side JavaScript does not allow the reading or writing of files. This 
   has been kept for security reason.  On the server-side, such as Node, this
   is not an issue.
2. JavaScript doesn't have any multithreading or multiprocess capabilities.

javascript:void(0) when used as the value of the href attribute prevent the 
page from being loaded.

// Falsy values: false, null, undefined, '', 0, NaN

What is 'use strict';?

'use strict'; is a JavaScript statement (just like any regular JavaScript statement) however, it put the JavaScript interpreter / engine into strict mode, which check for common programming errors. Strict mode requires you to explicitly reference to the global scope if this was the intended behavior.

What is the effect of assigning top to self?

var top = self;

I don't know the answer to this question yet. It probably will cause some error.

How can we cause JavaScript to sleep for x seconds?

Make a script tag, point its src attribute at a server, and tells the server not to response until x seconds had passed.

Can we use SQL with javascript?

With modern browsers allowing localStorage, we can store data on the browser. Is there a SQL-like way to access this data? ExtJS has a concept of a data store. It probably has a filter() function that can be used like a WHERE clause in SQL. Does jQuery has a plugin for accessing localStorage via SQL?

What can I do with window.external? Which browser support window.external?

Need research.

What is executeScript=false?

Need research

What is contenteditable?

Need research

What are the bad parts of JavaScript?

  1. global variables

What are the good parts of JavaScript?

  1. functions are first-class objects
  2. loose typing
  3. dynamic objects
  4. expressive object literal notation

What are the controversial part of JavaScript?

  1. Prototypal inheritance

What are some of the things that we might want to know about JavaScript?

  1. JavaScript is not related to Java.
  2. JavaScript is the first lambda language to go mainstream. Deep down, JavaScript has more in common with Lisp and Scheme than with Java. It is Lisp in C's clothing.

Why is 'loose typing' considered as a good part of JavaScript?

The fashion in most programming languages today demands strong typing. The theory is that strong typing allows a compiler to detect a large class of errors at compile time. The sooner we can detect and repair errors, the less they cost us. JavaScript is a loosely typed language, so JavaScript compilers are unable to detect type-related errors. This can be alarming to people who comes from strongly-typed languages. But it turns out that strong typing does not eliminate the need for careful testing. And I have found in my work that the sorts of errors that strong type checking finds are not the errors I worry about. On the other hand, I find loose typing to be liberating. I do not need to form a complex class hierarchies. And I never have to cast or wrestle with type system to get the behavior that I want. — Douglas Crockford

Why is 'prototypal inheritance' a controversial part of JavaScript?

A controversial feature of JavaScript is prototypal inheritance. JavaScript has a class-free object system in which objects inherit properties directly from other objects. This is really powerful, but it is unfamiliar to classically-trained programmers. If you attempt to apply classical design patterns directly to JavaScript, you will be frustrated. But if you learn to work with JavaScript's prototypal nature, your efforts will be rewarded.

When should we avoid block comment form?

JavaScript has two forms of comments, block comments formed with /* */ and the line-ending comments starting with //. The block comment form came from a language called PL/I. PL/I chose the /* */ pairs as the symbols for comments because they were unlikely to occur in that language's programs, except perhaps in string literals. In JavaScript, those pairs can also occur in regular expression literals, so block comments are not safe from commenting out blocks of code. For example:

  var rm_a = /a*/.match($);

causes a syntax error.

What are reserved words in JavaScript?

abstract, boolean, break, byte, case, catch, char, class, const, continue, debugger, default, delete, do, double, else, enum, export, extends, false, final, finally, float, for, function, goto, if, implements, import, in, instanceof, int, interactive, long, native, new, null, package, private, protected, public, return, short, static, super, switch, synchronized, this, throw, throws, transient, true, try, typeof, var, volatile, void, while, with.

This list does not include some words that should have been reserved, but were not, such as undefined, NaN, and Infinity.

We are not permitted to name a variable or parameter with a reserved word. We are also not permitted to use a reserved word as the name of an object property in an object literal or following a dot in a refinement.

Are numbers implemented as 32-bit or 64-bit in JavaScript?

64-bit. JavaScript has a single number type. Internally, it is represented as 64-bit floating point. Unlike most other programming languages, there is no separate integer type, so 1 and 1.0 are the same value. This is a significant convenience because problems of overflow in short integers are completely avoided, and all you need to know about number is that it is a number.

Is there multiple types to represent numbers such as integer and floating point numbers?


How can we detect NaN?

Use the isNaN function. The value NaN is a number value that is the result of an operation that cannot produce a normal result. NaN is not equal to any value, including itself. You can detect NaN with the isNaN() function.

How can we represent Infinity in JavaScript?

The value Infinity represents all values greater than 1.79769313486231570e+308

How can we represent a number using scientific notation?


Does JavaScript have a type to represent characters?

Not really. JavaScript does not have a character type. To represent a character, make a string with just one character in it.

How many bits does each character take in JavaScript?

JavaScript was built at a time when Unicode was a 16-bit character set, so all characters in JavaScript are 16-bit wide.

How can we specify a character using its code point numerically?

Use the \u convention:

"A" === "\u0041"

The above code is a comparison, which eval to true, but if you look on the right side, it is just a string.

Is String immutable?

Yes. In JavaScript, Strings are immutable. Once it is made, as string can never be changed. But it is easy to make a new string by concatenating other strings with the + operator.

How can we concatenate Strings in JavaScript?

Use the + operator:

a = a + ' whatever';

How can we compare strings?

Use the double-equal operator or the triple-equal operator:

'c' + 'a' + 't' === 'cat';
'c' + 'a' + 't' == 'cat';

Two strings containing exactly the same characters in the same order are considered equal.

Does a block create a new scope?

No. A block is a set of statements wrapped in curly braces. Unlike many other languages, blocks in JavaScript do not create a new scope, so variables should be defined at the top of the functions, not in blocks.

What are falsy values in JavaScript?

false, null, undefined, empty string, the number 0, the number NaN. All other values are truthy, including true, the string 'false', and all other objects, including empty objects.

What are the operator precedence in JavaScript?

  1. refinement and invocation operators: . [] ()
  2. unary operators: delete, new, typeof, +, -, !
  3. multiplication, division, modulo: *, /, %
  4. addition, concatenation, subtraction: +, -
  5. inequality: >=, <=, >, <
  6. equality operators: ===, !==
  7. logical and: &&
  8. logical or: ||
  9. ternary operator: ?:

Why is object literal consider a good part of JavaScript?

Object literals are a convenient notation for specifying new objects. The names of the properties can be specified as names or as strings. The names are treated as literal names, not as variable names, so the name of the properties of the object must be known at compile time. The values of the properties are expressions.

var flight = {
  airline: "Oceanic",
  number: 815,
  departure: {
    IATA: 'SYD',
    time: '...',
    city: 'Sydney'
  arrival: {
    IATA: 'LAX',
    time: '...',
    city: 'Los Angeles'

What is the purpose of the arguments array?

In JavaScript, arguments is a special variable. It is like an array (it has the length property), but it is not an array. It is a special variable because we do not have to declare it, and it only exist inside a function. This arguments variable contains all the parameters that was passed to it. This arguments variable also contains other interesting properties, such as .callee.

What is the replacement for arguments.caller?

The obsolete arguments.caller property used to provide the function that invoked the currently executing function. This property has been removed and no longer works, but we can use Function.caller.

How can we design a function that can take an arbitrary number of parameters?

Use the special variable named arguments. In JavaScript, arguments is a special variable. It is like an array (it has the length property), but it is not an array.

function whatever() {
  var i = 0;
  var len = arguments.length;
  var param;
    param = arguments[i];

The above code shows us how to obtain all the parameters that was passed to the whatever function. Notice that we do not declare a list of parameters that the whatever function would except.

What types are considered as objects in JavaScript?

Simple types in JavaScript are numbers, strings, boolean, null, and undefined. All other values are objects. Numbers, strings, and booleans are object-like in that they have methods, but they are immutable. Objects in JavaScript are mutable keyed collections. In JavaScript, arrays are objects, functions are objects, regular expressions are objects, and objects are objects.

Can we use an empty string as the name of a object property?


Can we use the string 'undefined' as the name of an object property?

Probably no, but I need to confirm this. We definitely cannot use undefined as a name of an object property, but I am not sure about the string 'undefined'.

Is there any restriction impose on objects by JavaScript?


Objects in JavaScript are class-free. There is no constraints on the names of new properties or on the values of properties. Objects are useful for collecting and organizing data. Objects can contain other objects, so they can easily represent tree or graph structures.

JavaScript includes a prototye linkage feasture that allows one object to inherit the properties of another. When used well, this can reduce object initialization time and memory consumption.

What is a notable behavior of the logical and operator?

The logical and operator (&&) produces the value of the first operand if the first operand is falsy. Otherwise, it produces the value of the second operand. Perhaps, it might be interesting when we have code like this:

var result = a && b && c && d

The variable named result will contain the value of the d variable if they are all truthy. The variable named result will contain falsy value if any of them is falsy.

What is a notable behavior of the logical or operator?

The logical or operator (||) produces the value of its first operand if the first operand is truthy. Otherwise, it produces the value of the second operand.

How does JavaScript pass parameters when they are objects?

Objects are passed around by references. They are never copied.

How can we create 3 variables that point to the same object?

Objects are passed around by references. They are never copied.

var a, b, c;
a = b = c = {}; // a, b, and c all refer to the same empty object.

var a = {}, b = {}, c = {}; // a, b, and c each refer to a different empty object