Object Oriented Javascript : ECMA Script 5 : Summary

Introduction

JavaScript is famous for being the world’s most misunderstood programming language. JavaScript is now used by an incredible number of high-profile applications, showing that deeper knowledge of this technology is an important skill for any web or mobile developer.

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, but JavaScript interpreters can also be found in a huge list of other places, including Adobe Acrobat, Adobe Photoshop, SVG images, Yahoo’s Widget engine, server-side environments such as Node.js, NoSQL databases like the open source Apache CouchDB, embedded computers, complete desktop environments like GNOME (one of the most popular GUIs for GNU/Linux operating systems), and others.

So the type diagram looks more like this:

Numbers

Numbers in JavaScript are “double-precision 64-bit format IEEE 754 values”, according to the spec.

0.1 + 0.2 == 0.30000000000000004

You can convert a string to an integer using the built-in parseInt() function.

parseInt("123", 10); // 123
parseInt("11", 2); // 3

Similarly, you can parse floating point numbers using the built-in parseFloat() function.

You can also use the unary + operator to convert values to numbers:

+ "42";   // 42
+ "010";  // 10
+ "0x10"; // 16

A special value called NaN (short for “Not a Number”) is returned if the string is non-numeric:

parseInt("hello", 10); // NaN
isNaN(NaN); // true
1 / 0; //  Infinity
-1 / 0; // -Infinity
isFinite(1/0); // false
isFinite(-Infinity); // false
isFinite(NaN); // false

 

Strings

Strings in JavaScript are sequences of Unicode characters.

To find the length of a string (in code units), access its length property:

"hello".length; // 5
"hello".charAt(0); // "h"
"hello, world".replace("hello", "goodbye"); // "goodbye, world"
"hello".toUpperCase(); // "HELLO"

Other types

JavaScript distinguishes between null, which is a value that indicates a deliberate non-value (and is only accessible through the null keyword), and undefined

Boolean

Any value can be converted to a boolean according to the following rules:

  1. false, 0, empty strings (""), NaN, null, and undefined all become false.
  2. All other values become true.

You can perform this conversion explicitly using the Boolean() function:

Boolean("");  // false
Boolean(234); // true

Variables

New variables in JavaScript are declared using the var keyword:

var a;
var name = "simon";

varkeyword declares the variable to the local scope. If you declare a variable without assigning any value to it, its type is undefined.

So if a variable is defined using var in a compound statement (for example inside an if control structure), it will be visible to the entire function.

Operators

JavaScript’s numeric operators are +, -, *, / and % — which is the remainder operator (which is not the same as modulo.) Values are assigned using =, and there are also compound assignment statements such as +=and -=. These extend out to x = x operator y.

x += 5
x = x + 5
"hello" + " world"; // "hello world"
"3" + 4 + 5;  // "345"
 3 + 4 + "5"; // "75"

Comparison

123 == "123"; // true
1 == true; // true

but

123 === "123"; // false
1 === true;    // false

There are also != and !== operators.

JavaScript also has bitwise operations. If you want to use them, they’re there.

 

Control structures

If Statement

Conditional statements are supported by if and else; you can chain them together if you like.

var name = "kittens";
if (name == "puppies") {
  name += "!";
} else if (name == "kittens") {
  name += "!!";
} else {
  name = "!" + name;
}
name == "kittens!!"

While  and Do – While

JavaScript has while loops and do-while loops. The first is good for basic looping; the second for loops where you wish to ensure that the body of the loop is executed at least once:

while (true) {
  // an infinite loop!
}

var input;
do {
  input = get_input();
} while (inputIsNotValid(input))

For Loop

JavaScript’s for loop is the same as that in C and Java:

for (var i = 0; i < 5; i++) {
  // Will execute 5 times
}

 

Syntax Short-Hands

The && and || operators use short-circuit logic, which means whether they will execute their second operand is dependent on the first. This is useful for checking for null objects before accessing their attributes:

var name = o && o.getName();

like in Ruby

if object && object.method

Or for setting default values:

var name = otherName || "default";

JavaScript has a ternary operator for conditional expressions:

var allowed = (age > 18) ? "yes" : "no";

Switch Statement

The switch statement can be used for multiple branches based on a number or string:

switch(action) {
  case 'draw':
    drawIt();
    break;
  case 'eat':
    eatIt();
    break;
  default:
    doNothing();
}

 

Objects

JavaScript objects can be thought of as simple collections of name-value pairs. As such, they are similar to:

  • Hashes in Perl and Ruby.
  • Hash tables in C and C++.
  • HashMaps in Java.
  • Associative arrays in PHP.

here are two basic ways to create an empty object:

var obj = new Object();

And:

var obj = {};

This syntax is also the core of JSON format and should be preferred at all times.

Object literal syntax can be used to initialize an object in its entirety:

var obj = {
  name: "Carrot",
  "for": "Max",
  details: {
    color: "orange",
    size: 12
  }
}

Attribute access can be chained together:

obj.details.color; // orange
obj["details"]["size"]; // 12

Arrays

var a = ["dog", "cat", "hen"];
a.length; // 3
var a = ["dog", "cat", "hen"];
a[100] = "fox";
a.length; // 101

Remember — the length of the array is one more than the highest index.
If you query a non-existent array index, you’ll get a value of undefined returned:

typeof a[90]; // undefined

Iterating over an array

["dog", "cat", "hen"].forEach(function(currentValue, index, array) {
  // Do something with currentValue or array[index]
});
a.push(item);

It Supports almost all methods in Ruby Array but in CamelCase instead of snake_case.

Functions

Along with objects, functions are the core component in understanding JavaScript. The most basic function couldn’t be much simpler:

function add(x, y) {
  var total = x + y;
  return total;
}

Like in Ruby, you can pass any number of argument than the method/function is expecting.

add(2, 3, 4); // 5 
// added the first two; 4 was ignored

Like *arg parameter in Ruby

That may seem a little silly, but functions have access to an additional variable inside their body calledarguments, which is an array-like object holding all of the values passed to the function. Let’s re-write the add function to take as many values as we want:

function add() {
  var sum = 0;
  for (var i = 0, j = arguments.length; i < j; i++) {
    sum += arguments[i];
  }
  return sum;
}

add(2, 3, 4, 5); // 14

 

Anonymous Functions

JavaScript lets you create anonymous functions.

var avg = function() {
  var sum = 0;
  for (var i = 0, j = arguments.length; i < j; i++) {
    sum += arguments[i];
  }
  return sum / arguments.length;
};

Here’s a way of “hiding” some local variables — like block scope in C:

var a = 1;
var b = 2;

(function() {
  var b = 3;
  a += b;
})();

a; // 4
b; // 2

 

IIFEs (Immediately Invoked Function Expressions)

var charsInBody = (function counter(elm) {
  if (elm.nodeType == 3) { // TEXT_NODE
    return elm.nodeValue.length;
  }
  var count = 0;
  for (var i = 0, child; child = elm.childNodes[i]; i++) {
    count += counter(child);
  }
  return count;
})(document.body);

 

 

 

 

 

 

 

Sources:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s