JavaScript

JavaScript was invented by Brendan Eich in 1995, and became an ECMA standard in 1997.
ECMA-262 is the official name of the standard. ECMAScript is the official name of the language.

  1. JavaScript accepts both double and single quotes:
  2. Old JavaScript examples may use a type attribute: <script type=”text/javascript”>.
    The type attribute is not required. JavaScript is the default scripting language in HTML.
  3. Placing scripts at the bottom of the <body> element improves the display speed, because script compilation slows down the display.
  4. External scripts cannot contain <script> tags.
  5. Using document.write() after an HTML document is fully loaded, will delete all existing HTML:
  6. Numbers are not allowed as the first character.
    This way JavaScript can easily distinguish identifiers from numbers.
  7. Hyphens are not allowed in JavaScript. It is reserved for subtractions.
  8. JavaScript identifiers are case-sensitive.
  9. JavaScript keywords are reserved words. Reserved words cannot be used as names for variables.
  10. A variable declared without a value will have the value undefined.
  11. If you re-declare a JavaScript variable, it will not lose its value.
    • var carName = “Volvo”;
    • var carName;
    • The variable carName will still have the value “Volvo” after the execution of these statements:
  12. JavaScript evaluates expressions from left to right. Different sequences can produce different results:
  13. If you put a number in quotes, the rest of the numbers will be treated as strings, and concatenated.
    • var x = “5” + 2 + 4;    output 524
    • var x = 2 + 4 + “5”;    output 65
  14. Accessing a function without () will return the function definition instead of the function result:
    1.  function toCelsius(fahrenheit) {
      return (5/9) * (fahrenheit-32);
      }
      document.getElementById(“demo”).innerHTML = toCelsius;

    will return     function toCelsius(f) { return (5/9) * (f-32); }

JavaScript Comparison Operators

Operator Description
== equal to
=== equal value and equal type
!= not equal
!== not equal value or not equal type

JavaScript Bitwise Operators

Bit operators work on 32 bits numbers.

Any numeric operand in the operation is converted into a 32 bit number. The result is converted back to a JavaScript number.

Operator Description Example Same as Result Decimal
& AND 5 & 1 0101 & 0001 0001  1
| OR 5 | 1 0101 | 0001 0101  5
~ NOT ~ 5  ~0101 1010  10
^ XOR 5 ^ 1 0101 ^ 0001 0100  4
<< Zero fill left shift 5 << 1 0101 << 1 1010  10
>> Signed right shift 5 >> 1 0101 >> 1 0010   2
>>> Zero fill right shift 5 >>> 1 0101 >>> 1 0010   2

The examples above uses 4 bits unsigned examples. But JavaScript uses 32-bit signed numbers.

Because of this, in JavaScript, ~ 5 will not return 10. It will return -6.
~00000000000000000000000000000101 will return 11111111111111111111111111111010

Null and Undefined ———————————–

In JavaScript null is “nothing”. It is supposed to be something that doesn’t exist. Unfortunately, in JavaScript, the data type of null is an object.

You can empty an object by setting it to null:

var person = {firstName:”John”, lastName:”Doe”, age:50, eyeColor:”blue”};
person = null;        // Now value is null, but type is still an object

You can also empty an object by setting it to undefined:

var person = {firstName:”John”, lastName:”Doe”, age:50, eyeColor:”blue”};
person = undefined;   // Now both value and type is undefined

Undefined and null are equal in value but different in type:

typeof undefined           // undefined
typeof null                    // object
null === undefined      // false
null == undefined         // true

typeof Operator ——————————————-

typeof {name:’John’, age:34} // Returns “object”
typeof [1,2,3,4]             // Returns “object” (not “array”, see note below)
typeof null                  // Returns “object”
typeof function myFunc(){}   // Returns “function”

typeof    x     // Returns “undefined” (if x has no value)

typeof NaN;            // returns “number”

typeof Infinity;        // returns “number”

Automatically Global ———————————-

If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable. This code example will declare a global variable carName, even if the value is assigned inside a function.

myFunction();

// code here can use carName 

function myFunction() {
    carName = “Volvo”;
}

Do NOT create global variables unless you intend to.In “Strict Mode” automatically global variables will fail.

slice() method ——————————————-

slice() extracts a part of a string and returns the extracted part in a new string.The method takes 2 parameters: the starting index (position), and the ending index (position).

var str = “Apple, Banana, Kiwi”;
var res = str.slice(7, 13);

The result of res will be: Banana

If a parameter is negative, the position is counted from the end of the string.

var str = “Apple, Banana, Kiwi”;
var res = str.slice(-12, -6);

The result of res will be: Banana

If you omit the second parameter, the method will slice out the rest of the string:

var str = “Apple, Banana, Kiwi”;

var res = str.slice(7);

The result of res will be: Banana, Kiwi

Numeric Strings ———————————–

JavaScript will try to convert strings to numbers in all numeric operations:

var x = “100”;
var y = “10”;
var z = x / y;       // z will be 10

var x = “100”;
var y = “10”;
var z = x * y;       // z will be 1000

var x = “100”;
var y = “10”;
var z = x – y;       // z will be 90

var x = “100”;
var y = “10”;
var z = x + y;       // z will not be 110 (It will be 10010)

var x = 10;
var y = 20;
var z = “The result is: ” + x + y;    // The result is: 1020

var x = 100 / “10”;     // x will be 10

NaN – Not a Number ———————————

NaN is a JavaScript reserved word indicating that a number is not a legal number.

var x = 100 / “Apple”;  // x will be NaN (Not a Number)

However, if the string contains a numeric value , the result will be a number:

var x = 100 / “10”;     // x will be 10

Watch out for NaN. If you use NaN in a mathematical operation, the result will also be NaN:

var x = NaN;
var y = 5;
var z = x + y;         // z will be NaN

Or the result might be a concatenation:

var x = NaN;
var y = “5”;
var z = x + y;         // z will be NaN5

Strict Mode ——————————————-

“use strict”; Defines that JavaScript code should be executed in “strict mode”.

With strict mode, you can not, for example, use undeclared variables.

“use strict”;
x = 3.14;       // This will cause an error because x is not declared

Why Strict Mode?

Strict mode makes it easier to write “secure” JavaScript.

  1. As an example, in normal JavaScript, mistyping a variable name creates a new global variable. In strict mode, this will throw an error, making it impossible to accidentally create a global variable.
  2. In normal JavaScript, a developer will not receive any error feedback assigning values to non-writable properties.
  3. In strict mode, any assignment to a non-writable property, a getter-only property, a non-existing property, a non-existing variable, or a non-existing object, will throw an error.
  4. Deleting a variable (or object) is not allowed.

           “use strict”;
            var x = 3.14;
            delete x;                // This will cause an error

Common Mistakes ——————————–

This if statement returns true (maybe not as expected), because 10 is true:

var x = 0;
if (x = 10)

This if statement returns false (maybe not as expected), because 0 is false:

var x = 0;
if (x = 0)

In regular comparison, data type does not matter. This if statement returns true:

var x = 10;
var y = “10”;
if (x == y)

In strict comparison, data type does matter. This if statement returns false:

var x = 10;
var y = “10”;
if (x === y)


It is a common mistake to forget that switch statements use strict comparison:

This case switch will display an alert:

var x = 10;
switch(x) {
    case 10: alert(“Hello”);
}

This case switch will not display an alert:

var x = 10;
switch(x) {
    case “10”: alert(“Hello”);
}


JavaScript will allow you to break a statement into two lines:

var x =
“Hello World!”;           \\output Hello World!

But, breaking a statement in the middle of a string will not work:

var x = “Hello
World!”;                      \\no output

You must use a “backslash” if you must break a statement in a string:

var x = “Hello \
World!”;                      \\output Hello World!


Because of a misplaced semicolon, this code block will execute regardless of the value of x:

if (x == 19);
{
    // code block  
}


It is a default JavaScript behavior to close a statement automatically at the end of a line.

JavaScript will also allow you to break a statement into two lines.

Because of this, example below return the result:

function myFunction(a) {
    var
    power = 10;  
    return a * power;
}

But, what will happen if you break the return statement in two lines like this:

function myFunction(a) {
    var
    power = 10;  
    return
    a * power;
}

The function will return undefined!

Why? Because JavaScript thinks you meant:

function myFunction(a) {
    var
    power = 10;  
    return;
    a * power;
}

so never break a return statement.

Undefined is Not Null

With JavaScript, null is for objects, undefined is for variables, properties, and methods.

To be null, an object has to be defined, otherwise it will be undefined.

If you want to test if an object exists, this will throw an error if the object is undefined:

Incorrect:
if (myObj !== null && typeof myObj !== “undefined”) 

Because of this, you must test typeof() first:

Correct:
if (typeof myObj !== “undefined” && myObj !== null) 
————————————————————–

Expecting Block Level Scope

JavaScript does not create a new scope for each code block.

It is true in many programming languages, but not true in JavaScript.

This code will display the value of i (10), even OUTSIDE the for loop block:

for (var i = 0; i < 10; i++) {
    // some code
}
return i;
————————————————————–

Self-Invoking Functions

Function expressions can be made “self-invoking”.

A self-invoking expression is invoked (started) automatically, without being called.

Function expressions will execute automatically if the expression is followed by ().

You cannot self-invoke a function declaration.

You have to add parentheses around the function to indicate that it is a function expression:

(function () {
    var x = “Hello!!”;      // I will invoke myself
})();

The function above is actually an anonymous self-invoking function (function without name).


function myFunction(a, b) {
return arguments.length;
}

myFunction(4, 3,1,2);      // output 4

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Thanks for your comment

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

%d bloggers like this: