JavaScript and Camel Case

Historically, programmers have used three ways of joining multiple words into one variable name:

Hyphens:

first-name, last-name, master-card, inter-city.

Underscore:

first_name, last_name, master_card, inter_city.

Camel Case:

FirstName, LastName, MasterCard, InterCity.


JavaScript Notes 1_sed

In programming languages, especially in JavaScript,camel case often starts with a lowercase letter:

firstName, lastName, masterCard, interCity.

Hyphens are not allowed in JavaScript. It is reserved for subtractions.


2. Strings are written with quotes. You can use single or double quotes. Similar with python


3. You can use the JavaScript typeof operator to find the type of a JavaScript variable:

typeof "John" (no brakets!!!)


4. function

Example


function myFunction(p1, p2) {
     return p1 * p2;               // The function returns the product of p1 and p2
}

 

5. JS is OOP. Object definition

Spaces and line breaks are not important. An object definition can span multiple lines:


Example



var person = {
    firstName: "John",
    lastName: "Doe",
    age: 50,
    eyeColor: "blue"
};

6.

Automatically Global

GLOBAL

This code example will declare carName as a global variable, even if it is executed inside a function.


Example



// code here can use carName

function myFunction() {
    carName =  "Volvo";

     // code here can use carName

}



7.

Common HTML Events

Here is a list of some common HTML events:

Event

Description

onchange

An HTML element has been changed

onclick

The user clicks an HTML element

onmouseover

The user moves the mouse over an HTML element

onmouseout

The user moves the mouse away from an HTML element

onkeydown

The user pushes a keyboard key

onload

The browser has finished loading the page

The list is much longer: W3Schools JavaScript Reference HTML DOM Events.


8.


Objects cannot be compared:


Example



var x =  new String( "John");             
var y =  new String( "John");

// (x == y) is false because objects cannot be compared




9. For string, Note indexOf(), lastIndexOf(), search(), slice(), substring(), substr(), replace(), toUpperCase(), toLowerCase(), charAt(), charCodeAt(), split() (similar with python)


   For number, toString() convert to string, toExponential(), toFixed(), toPrecision(), 

   convert variables to number: Number(), parseInt(), parseFloat()

valueOf()

10.


But you can use the toString() method to output numbers as base 16 (hex), base 8 (octal), or base 2 (binary).


Example



var myNumber =  128;
myNumber.toString( 16);      // returns 80
myNumber.toString( 8);       // returns 200
myNumber.toString( 2);       // returns 10000000





11. 


Infinity

Infinity (or -Infinity) is the value JavaScript will return if you calculate a number outside the largest possible number.


Example



var myNumber =  2;
while (myNumber !=  Infinity) {           // Execute until Infinity
    myNumber = myNumber * myNumber;
}




12. 


You can use the global JavaScript function isNaN() to find out if a value is a number.


Example



var x =  100 /  "Apple";
isNaN(x);                // returns true because x is Not a Number



13. Math object


14. Date()

    e.g. d = new Date("2015-05-14")

    e.g. d = new Date() returns the current time

15. Array object

   like the vector in c++


16. Note Array object is different from object data type.

arrays use numbered indexes.  

objects use named indexes.



17. Avoid new Array()

new

Use [] instead.

These two different statements both create a new empty array named points:


var  points =  new  Array();          // Bad
var                   // Good 


These two different statements both create a new array containing 6 numbers:


var points =  new Array( 40,  100,  1,  5,  25,  10)   // Bad
var points = [ 40,  100,  1,  5,  25,  10];           // Good



18.

In JavaScript, all objects have the valueOf() and toString() methods.

valueOf()

can also use join(), like the python

19.  for array, pop(), push()

20. Pay attention to the JS Array Methods, important!!!!


21. boolean: true & false


22. === : equal value and equal type


23. if else is the same with C


24. for loop is the same with C

it can also support the "for(x in array)"

25. break and continue


JavaScript Labels

To label JavaScript statements you precede the statements with a label name and a colon:


label:
statements

 


26. regular expression. search() and replace()

      test() and exec()


27. try and catch and throw error


JavaScript try and catch

try

catch

try and catch


try {
     Block of code to try
}
catch(err) {
     Block of code to handle errors
}


The throw Statement

throw

throw an exception.

The exception can be a JavaScript String, a Number, a Boolean or an Object:


throw  "Too big";     // throw a text
throw  500;           // throw a number


throw together with try and catch, you can control program flow and generate custom error messages.



e.g. 



try { 


        if(x == "") throw "empty";


        if(isNaN(x)) throw "not a number";


        x == Number(x);


        if(x < 5) throw "too low";


        if(x > 10) throw "too high";


    }


    catch(err) {


        message.innerHTML = "Input is " + err;


    }

finally{


}



28. in browser, F12 is the debugger!!


29. Hoisting is JavaScript's default behavior of moving all declarations to the top of the current scope (to the top of the current script or the current function).


30. JavaScript only hoists declarations, not initializations.


31. "use strict";


32. Naming Convention


PascalCase:

PascalCase is often preferred by C programmers.

camelCase:

camelCase is used by JavaScript itself, by jQuery, and other JavaScript libraries.



33. getElementById();



34. 

Always treat numbers, strings, or booleans as primitive values. Not as objects.

Declaring these types as objects, slows down execution speed, and produces nasty side effects:

35. IMPORTANT!!!

Don't Use new Object()

  • Use {} instead of new Object()
  • Use "" instead of new String()
  • Use 0 instead of new Number()
  • Use false instead of new Boolean()
  • Use [] instead of new Array()
  • Use /()/ instead of new RegExp()
  • Use function (){} instead of new function()

Example



var x1 = {};            // new object
var x2 =  "";            // new primitive string
var x3 =  0;             // new primitive number
var x4 =  false;         // new primitive boolean
var x5 = [];            // new array object
var x6 = /()/;          // new regexp object
var x7 =  function(){};  // new function object



36.


Reduce Activity in Loops

Loops are often used in programming.

Each statement in a loop, including the for statement, is executed for each iteration of the loop.

Search for statements or assignments that can be placed outside the loop.


Bad Code:



for (i =  0; i < arr.length; i++) {


Better Code:



l = arr.length;
for (i =  0; i < l; i++) {


The bad code accesses the length property of an array each time the loop is iterated.

The better code accesses the length property outside the loop, and makes the loop run faster.




37.  

  • JSON stands for JavaScript Object Notation

JSON.parse