Monday, November 23, 2015

Python Basic Operators

Operators are the constructs which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator.

Types of Operator

Python language supports the following types of operators.
  • Arithmetic Operators
  • Comparison (Relational) Operators
  • Assignment Operators
  • Logical Operators
  • Bitwise Operators
  • Membership Operators
  • Identity Operators
Let us have a look on all operators one by one.

Python Arithmetic Operators

Assume variable a holds 10 and variable b holds 20, then −
[ Show Example ]
Operator Description Example
+ Addition Adds values on either side of the operator. a + b = 30
- Subtraction Subtracts right hand operand from left hand operand. a – b = -10
* Multiplication Multiplies values on either side of the operator a * b = 200
/ Division Divides left hand operand by right hand operand b / a = 2
% Modulus Divides left hand operand by right hand operand and returns remainder b % a = 0
** Exponent Performs exponential (power) calculation on operators a**b =10 to the power 20
// Floor Division - The division of operands where the result is the quotient in which the digits after the decimal point are removed. 9//2 = 4 and 9.0//2.0 = 4.0

Python Comparison Operators

These operators compare the values on either sides of them and decide the relation among them. They are also called Relational operators.
Assume variable a holds 10 and variable b holds 20, then −
[ Show Example ]
OperatorDescriptionExample
== If the values of two operands are equal, then the condition becomes true. (a == b) is not true.
!= If values of two operands are not equal, then condition becomes true.
<> If values of two operands are not equal, then condition becomes true. (a <> b) is true. This is similar to != operator.
> If the value of left operand is greater than the value of right operand, then condition becomes true. (a > b) is not true.
< If the value of left operand is less than the value of right operand, then condition becomes true. (a < b) is true.
>= If the value of left operand is greater than or equal to the value of right operand, then condition becomes true. (a >= b) is not true.
<= If the value of left operand is less than or equal to the value of right operand, then condition becomes true. (a <= b) is true.

Python Assignment Operators

Assume variable a holds 10 and variable b holds 20, then −
[ Show Example ]
Operator Description Example
= Assigns values from right side operands to left side operand c = a + b assigns value of a + b into c
+= Add AND It adds right operand to the left operand and assign the result to left operand c += a is equivalent to c = c + a
-= Subtract AND It subtracts right operand from the left operand and assign the result to left operand c -= a is equivalent to c = c - a
*= Multiply AND It multiplies right operand with the left operand and assign the result to left operand c *= a is equivalent to c = c * a
/= Divide AND It divides left operand with the right operand and assign the result to left operand c /= a is equivalent to c = c / ac /= a is equivalent to c = c / a
%= Modulus AND It takes modulus using two operands and assign the result to left operand c %= a is equivalent to c = c % a
**= Exponent AND Performs exponential (power) calculation on operators and assign value to the left operand c **= a is equivalent to c = c ** a
//= Floor Division It performs floor division on operators and assign value to the left operand c //= a is equivalent to c = c // a

Python Bitwise Operators

Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b = 13; Now in binary format they will be as follows −
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a  = 1100 0011
There are following Bitwise operators supported by Python language
[ Show Example ]
Operator Description Example
& Binary AND Operator copies a bit to the result if it exists in both operands (a & b) (means 0000 1100)
| Binary OR It copies a bit if it exists in either operand. (a | b) = 61 (means 0011 1101)
^ Binary XOR It copies the bit if it is set in one operand but not both. (a ^ b) = 49 (means 0011 0001)
~ Binary Ones Complement It is unary and has the effect of 'flipping' bits. (~a ) = -61 (means 1100 0011 in 2's complement form due to a signed binary number.
<< Binary Left Shift The left operands value is moved left by the number of bits specified by the right operand. a << = 240 (means 1111 0000)
>> Binary Right Shift The left operands value is moved right by the number of bits specified by the right operand. a >> = 15 (means 0000 1111)

Python Logical Operators

There are following logical operators supported by Python language. Assume variable a holds 10 and variable b holds 20 then
[ Show Example ]
Used to reverse the logical state of its operand.

Python Membership Operators

Python’s membership operators test for membership in a sequence, such as strings, lists, or tuples. There are two membership operators as explained below
[ Show Example ]
OperatorDescriptionExample
in Evaluates to true if it finds a variable in the specified sequence and false otherwise. x in y, here in results in a 1 if x is a member of sequence y.
not in Evaluates to true if it does not finds a variable in the specified sequence and false otherwise. x not in y, here not in results in a 1 if x is not a member of sequence y.

Python Identity Operators

Identity operators compare the memory locations of two objects. There are two Identity operators explained below:
[ Show Example ]
OperatorDescriptionExample
isEvaluates to true if the variables on either side of the operator point to the same object and false otherwise.x is y, here is results in 1 if id(x) equals id(y).
is notEvaluates to false if the variables on either side of the operator point to the same object and true otherwise.x is not y, here is not results in 1 if id(x) is not equal to id(y).

Python Operators Precedence

The following table lists all operators from highest precedence to lowest.
[ Show Example ]
OperatorDescription
** Exponentiation (raise to the power)
~ + - Ccomplement, unary plus and minus (method names for the last two are +@ and -@)
* / % // Multiply, divide, modulo and floor division
+ - Addition and subtraction
>> << Right and left bitwise shift
& Bitwise 'AND'
^ | Bitwise exclusive `OR' and regular `OR'
<= < > >= Comparison operators
<> == != Equality operators
= %= /= //= -= += *= **= Assignment operators
is is not Identity operators
in not in Membership operators
not or and Logical operators

JavaScript Validation API

Constraint Validation DOM Methods

Property Description
checkValidity() Returns true if an input element contains valid data.
setCustomValidity() Sets the validationMessage property of an input element.

If an input field contains invalid data, display a message:

The checkValidity() Method

<input id="id1" type="number" min="100" max="300">
<button onclick="myFunction()">OK</button>

<p id="demo"></p>

<script>
function myFunction() {
    var inpObj = document.getElementById("id1");
    if (inpObj.checkValidity() == false) {
        document.getElementById("demo").innerHTML = inpObj.validationMessage;
    }
}
</script>
Try it Yourself »

Constraint Validation DOM Properties

Property Description
validity Contains boolean properties related to the validity of an input element.
validationMessage Contains the message a browser will display when the validity is false.
willValidate Indicates if an input element will be validated.

Validity Properties

The validity property of an input element contains a number of properties related to the validity of data:
Property Description
customError Set to true, if a custom validity message is set.
patternMismatch Set to true, if an element's value does not match its pattern attribute.
rangeOverflow Set to true, if an element's value is greater than its max attribute.
rangeUnderflow Set to true, if an element's value is less than its min attribute.
stepMismatch Set to true, if an element's value is invalid per its step attribute.
tooLong Set to true, if an element's value exceeds its maxLength attribute.
typeMismatch Set to true, if an element's value is invalid per its type attribute.
valueMissing Set to true, if an element (with a required attribute) has no value.
valid Set to true, if an element's value is valid.

Examples

If the number in an input field is greater than 100 (the input's max attribute), display a message:

The rangeOverflow Property

<input id="id1" type="number" max="100">
<button onclick="myFunction()">OK</button>

<p id="demo"></p>

<script>
function myFunction() {
    var txt = "";
    if (document.getElementById("id1").validity.rangeOverflow) {
       txt = "Value too large";
    }
    document.getElementById("demo").innerHTML = txt;
}
</script>
Try it Yourself »
If the number in an input field is less than 100 (the input's min attribute), display a message:

The rangeUnderflow Property

<inputid="id1"type="number"min="100">
<buttononclick="myFunction()">OK</button>

<pid="demo"></p>

<script>
function myFunction() {
    var txt = "";
    if (document.getElementById("id1").validity.rangeUnderflow) {
       txt = "Value too small";
    }
    document.getElementById("demo").innerHTML = txt;
}
</script>

JavaScript Forms

JavaScript Form Validation

HTML form validation can be done by a JavaScript.
If a form field (fname) is empty, this function alerts a message, and returns false, to prevent the form from being submitted:

JavaScript Example

function validateForm() {
    var x = document.forms["myForm"]["fname"].value;
    if (x == null || x == "") {
        alert("Name must be filled out");
        return false;
    }
}
The function can be called when the form is submitted:

HTML Form Example

<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
Try it Yourself »

HTML Form Validation

HTML form validation can be performed automatically by the browser:
If a form field (fname) is empty, the required attribute prevents this form from being submitted:

HTML Form Example

<form action="demo_form.asp" method="post">
  <input type="text" name="fname" required>
  <input type="submit" value="Submit">
</form>
Try it Yourself »
Note HTML form validation does not work in Internet Explorer 9 or earlier.

Data Validation

Data validation is the process of ensuring that computer input is clean, correct, and useful.
Typical validation tasks are:
  • has the user filled in all required fields?
  • has the user entered a valid date?
  • has the user entered text in a numeric field?
Most often, the purpose of data validation is to ensure correct input to a computer application.
Validation can be defined by many different methods, and deployed in many different ways.
Server side validation is performed by a web server, after input has been sent to the server.
Client side validation is performed by a web browser, before input is sent to a web server.

HTML Constraint Validation

HTML5 introduced a new HTML validation concept called constraint validation.
HTML constraint validation is based on:
  • Constraint validation HTML Input Attributes
  • Constraint validation CSS Pseudo Selectors
  • Constraint validation DOM Properties and Methods

Constraint Validation HTML Input Attributes

Attribute Description
disabled Specifies that the input element should be disabled
max Specifies the maximum value of an input element
min Specifies the minimum value of an input element
pattern Specifies the value pattern of an input element
required Specifies that the input field requires a element
type  Specifies the type of an input element
For a full list, go to HTML Input Attributes.

Constraint Validation CSS Pseudo Selectors

Selector Description
:disabled Selects input elements with the "disabled" attribute specified
:invalid Selects input elements with invalid values
:optional Selects input elements with no "required" attribute specified
:required Selects input elements with the "required" attribute specified
:valid Selects input elements with valid values

JavaScript JSON

JSON is a format for storing and transporting data.
JSON is often used when data is sent from a server to a web page.

What is JSON?

  • JSON stands for JavaScript Object Notation
  • JSON is lightweight data interchange format
  • JSON is language independent *
  • JSON is "self-describing" and easy to understand
* The JSON syntax is derived from JavaScript object notation syntax, but the JSON format is text only. Code for reading and generating JSON data can be written in any programming language.

JSON Example

This JSON syntax defines an employees object: an array of 3 employee records (objects):

JSON Example

{
"employees":[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]
}

The JSON Format Evaluates to JavaScript Objects

The JSON format is syntactically identical to the code for creating JavaScript objects.
Because of this similarity, a JavaScript program can easily convert JSON data into native JavaScript objects.

JSON Syntax Rules

  • Data is in name/value pairs
  • Data is separated by commas
  • Curly braces hold objects
  • Square brackets hold arrays

JSON Data - A Name and a Value

JSON data is written as name/value pairs, just like JavaScript object properties.
A name/value pair consists of a field name (in double quotes), followed by a colon, followed by a value:
"firstName":"John"
Note JSON names require double quotes. JavaScript names don't.

JSON Objects

JSON objects are written inside curly braces.
Just like in JavaScript, objects can contain multiple name/value pairs:
{"firstName":"John", "lastName":"Doe"}

JSON Arrays

JSON arrays are written inside square brackets.
Just like in JavaScript, an array can contain objects:
"employees":[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]
In the example above, the object "employees" is an array. It contains three objects.
Each object is a record of a person (with a first name and a last name).

Converting a JSON Text to a JavaScript Object

A common use of JSON is to read data from a web server, and display the data in a web page.
For simplicity, this can be demonstrated using a string as input (or read more in our JSON tutorial):
First, create a JavaScript string containing JSON syntax:
var text = '{ "employees" : [' +
'{ "firstName":"John" , "lastName":"Doe" },' +
'{ "firstName":"Anna" , "lastName":"Smith" },' +
'{ "firstName":"Peter" , "lastName":"Jones" } ]}';
Then, use the JavaScript built-in function JSON.parse() to convert the string into a JavaScript object:
var obj = JSON.parse(text);
Finally, use the new JavaScript object in your page:

Example

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
obj.employees[1].firstName + " " + obj.employees[1].lastName;
</script>

JavaScript Reserved Words

In JavaScript, some identifiers are reserved words and cannot be used as variables or function names.

JavaScript Standards

ECMAScript 3 (ES3) was released in December 1999.
ECMAScript 4 (ES4) was abandoned.
ECMAScript 5 (ES5) was released in December 2009.
ECMAScript 6 (ES6) was released in June 2015, and is the latest official version of JavaScript.
Time passes, and we are now beginning to see complete support for ES5/ES6 in all modern browsers.

JavaScript Reserved Words

In JavaScript you cannot use these reserved words as variables, labels, or function names:
abstract arguments boolean break byte
case catch char class* const
continue debugger default delete do
double else enum* eval export*
extends* false final finally float
for function goto if implements
import* in instanceof int interface
let long native new null
package private protected public return
short static super* switch synchronized
this throw throws transient true
try typeof var void volatile
while with yield

Words marked with* are new in ECMAScript5

JavaScript Objects, Properties, and Methods

You should also avoid using the name of JavaScript built-in objects, properties, and methods:
Array Date eval function hasOwnProperty
Infinity isFinite isNaN isPrototypeOf length
Math NaN name Number Object
prototype String toString undefined valueOf

Java Reserved Words

JavaScript is often used together with Java. You should avoid using some Java objects and properties as JavaScript identifiers:
getClass java JavaArray javaClass JavaObject JavaPackage

Windows Reserved Words

JavaScript can be used outside HTML. It can be used as the programming language in many other applications.
In HTML you must (for portability you should) avoid using the name of HTML and Windows objects and properties:
alert all anchor anchors area
assign blur button checkbox clearInterval
clearTimeout clientInformation close closed confirm
constructor crypto decodeURI decodeURIComponent defaultStatus
document element elements embed embeds
encodeURI encodeURIComponent escape event fileUpload
focus form forms frame innerHeight
innerWidth layer layers link location
mimeTypes navigate navigator frames frameRate
hidden history image images offscreenBuffering
open opener option outerHeight outerWidth
packages pageXOffset pageYOffset parent parseFloat
parseInt password pkcs11 plugin prompt
propertyIsEnum radio reset screenX screenY
scroll secure select self setInterval
setTimeout status submit taint text
textarea top unescape untaint window

HTML Event Handlers

In addition you should avoid using the name of all HTML event handlers.
Examples:
onblur onclick onerror onfocus
onkeydown onkeypress onkeyup onmouseover
onload onmouseup onmousedown onsubmit

JavaScript Performance

How to speed up your JavaScript code.

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.

Reduce DOM Access

Accessing the HTML DOM is very slow, compared to other JavaScript statements.
If you expect to access a DOM element several times, access it once, and use it as a local variable:

Example

obj = document.getElementById("demo");
obj.innerHTML = "Hello";
Try it Yourself »

Reduce DOM Size

Keep the number of elements in the HTML DOM small.
This will always improve page loading, and speed up rendering (page display), especially on smaller devices.
Every attempt to search the DOM (like getElementsByTagName) will benefit from a smaller DOM.

Avoid Unnecessary Variables

Don't create new variables if you don't plan to save values.
Often you can replace code like this:
var fullName = firstName + " " + lastName;
document.getElementById("demo").innerHTML = fullName;
With this:
document.getElementById("demo").innerHTML = firstName + " " + lastName

Delay JavaScript Loading

Putting your scripts at the bottom of the page body, lets the browser load the page first.
While a script is downloading, the browser will not start any other downloads. In addition all parsing and rendering activity might be blocked.
Note The HTTP specification defines that browsers should not download more than two components in parallel.
An alternative is to use defer="true" in the script tag. The defer attribute specifies that the script should be executed after the page has finished parsing, but it only works for external scripts.
If possible, you can add your script to the page by code, after the page has loaded:

Example

<script>
window.onload = downScripts;

function downScripts() {
    var element = document.createElement("script");
    element.src = "myScript.js";
    document.body.appendChild(element);
}
</script>

Avoid Using with

Avoid using the with keyword. It has a negative effect on speed. It also clutters up JavaScript scopes.
The with keyword is not allowed in strict mode.

JavaScript Common Mistakes

This chapter points out some common JavaScript mistakes.

Accidentally Using the Assignment Operator

JavaScript programs may generate unexpected results if a programmer accidentally uses an assignment operator (=), instead of a comparison operator (==) in an if statement.
This if statement returns false (as expected) because x is not equal to 10:
var x = 0;
if (x == 10)
Try it Yourself »
This if statement returns true (maybe not as expected), because 10 is true:
var x = 0;
if (x = 10)
Try it Yourself »
This if statement returns false (maybe not as expected), because 0 is false:
var x = 0;
if (x = 0)
Try it Yourself »
Note An assignment always returns the value of the assignment.

Expecting Loose Comparison

In regular comparison, data type does not matter. This if statement returns true:
var x = 10;
var y = "10";
if (x == y)
Try it Yourself »
In strict comparison, data type does matter. This if statement returns false:
var x = 10;
var y = "10";
if (x === y)
Try it Yourself »
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");
}
Try it Yourself »
This case switch will not display an alert:
var x = 10;
switch(x) {
    case "10": alert("Hello");
}
Try it Yourself »

Confusing Addition & Concatenation

Addition is about adding numbers.
Concatenation is about adding strings.
In JavaScript both operations use the same + operator.
Because of this, adding a number as a number will produce a different result from adding a number as a string:
var x = 10 + 5;          // the result in x is 15var x = 10 + "5";        // the result in x is "105"
Try it Yourself »
When adding two variables, it can be difficult to anticipate the result:
var x = 10;
var y = 5;
var z = x + y;           // the result in z is 15
var x = 10;
var y = "5";
var z = x + y;           // the result in z is "105"
Try it Yourself »

Misunderstanding Floats

All numbers in JavaScript are stored as 64-bits Floating point numbers (Floats).
All programming languages, including JavaScript, have difficulties with precise floating point values:
var x = 0.1;
var y = 0.2;
var z = x + y            // the result in z will not be 0.3if (z == 0.3)            // this if test will fail
Try it Yourself »
To solve the problem above, it helps to multiply and divide:

Example

var z = (x * 10 + y * 10) / 10;       // z will be 0.3
Try it Yourself »

Breaking a JavaScript String

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

Example 1

var x =
"Hello World!";
Try it Yourself »
But, breaking a statement in the middle of a string will not work:

Example 2

var x = "Hello
World!"
;
Try it Yourself »
You must use a "backslash" if you must break a statement in a string:

Example 3

var x = "Hello \
World!"
;
Try it Yourself »

Misplacing Semicolon

Because of a misplaced semicolon, this code block will execute regardless of the value of x:
if (x == 19);
{
    // code block  }
Try it Yourself »

Breaking a Return Statement

It is a default JavaScript behavior to close a statement automatically at the end of a line.
Because of this, these two examples will return the same result:

Example 1

function myFunction(a) {
    var power = 10 
    return a * power
}
Try it Yourself »

Example 2

function myFunction(a) {
    var power = 10;
    return a * power;
}
Try it Yourself »
JavaScript will also allow you to break a statement into two lines.
Because of this, example 3 will also return the same result:

Example 3

function myFunction(a) {
    var
    power = 10
    return a * power;
}
Try it Yourself »
But, what will happen if you break the return statement in two lines like this:

Example 4

function myFunction(a) {
    var
    power = 10
    return
    a * power;
}
Try it Yourself »
The function will return undefined!
Why? Because JavaScript thinks you meant:

Example 5

function myFunction(a) {
    var
    power = 10
    return;
    a * power;
}
Try it Yourself »

Explanation

If a statement is incomplete like:
var
JavaScript will try to complete the statement by reading the next line:
power = 10;
But since this statement is complete:
return
JavaScript will automatically close it like this:
return;
This happens because closing (ending) statements with semicolon is optional in JavaScript.
JavaScript will close the return statement at the end of the line, because it is a complete statement.
Note Never break a return statement.

Accessing Arrays with Named Indexes

Many programming languages support arrays with named indexes.
Arrays with named indexes are called associative arrays (or hashes).
JavaScript does not support arrays with named indexes.
In JavaScript, arrays use numbered indexes:  

Example

var person = [];
person[0] = "John";
person[1] = "Doe";
person[2] = 46;
var x = person.length;         // person.length will return 3var y = person[0];             // person[0] will return "John"
Try it Yourself »
In JavaScript, objects use named indexes.
If you use a named index, when accessing an array, JavaScript will redefine the array to a standard object.
After the automatic redefinition, array methods and properties will produce undefined or incorrect results:

Example:

var person = [];
person["firstName"] = "John";
person["lastName"] = "Doe";
person["age"] = 46;
var x = person.length;         // person.length will return 0var y = person[0];             // person[0] will return undefined
Try it Yourself »

Ending an Array Definition with a Comma

Incorrect:

points = [40, 100, 1, 5, 25, 10,];
Some JSON and JavaScript engines will fail, or behave unexpectedly.

Correct:

points = [40, 100, 1, 5, 25, 10];

Ending an Object Definition with a Comma

Incorrect:

person = {firstName:"John", lastName:"Doe", age:46,}
Some JSON and JavaScript engines will fail, or behave unexpectedly.

Correct:

person = {firstName:"John", lastName:"Doe", age:46}

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.
It is a common mistake, among new JavaScript developers, to believe that this code returns undefined:

Example

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

JavaScript Best Practices

Avoid global variables,  avoid new,  avoid  ==,  avoid eval()

Avoid Global Variables

Minimize the use of global variables.
This includes all data types, objects, and functions.
Global variables and functions can be overwritten by other scripts.
Use local variables instead, and learn how to use closures.

Always Declare Local Variables

All variables used in a function should be declared as local variables.
Local variables must be declared with the var keyword, otherwise they will become global variables.
Note Strict mode does not allow undeclared variables.

Declarations on Top

It is a good coding practice to put all declarations at the top of each script or function.
This will:
  • Give cleaner code
  • Provide a single place to look for local variables
  • Make it easier to avoid unwanted (implied) global variables
  • Reduce the possibility of unwanted re-declarations
// Declare at the beginningvar firstName, lastName, price, discount, fullPrice;

// Use laterfirstName = "John";
lastName = "Doe";

price = 19.90;
discount = 0.10;

fullPrice = price * 100 / discount;
This also goes for loop variables:
// Declare at the beginningvar i;

// Use laterfor (i = 0; i < 5; i++) {
Note By default, JavaScript moves all declarations to the top (JavaScript hoisting).

Initialize Variables

It is a good coding practice to initialize variables when you declare them.
This will:
  • Give cleaner code
  • Provide a single place to initialize variables
  • Avoid undefined values
// Declare and initiate at the beginningvar firstName = "",
    lastName = "",
    price = 0,
    discount = 0,
    fullPrice = 0,
    myArray = [],
    myObject = {};
Note Initializing variables provides an idea of the intended use (and intended data type).

Never Declare Number, String, or Boolean Objects

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:

Example

var x = "John";            
var y = new String("John");
(x === y) // is false because x is a string and y is an object.

Or even worse:

Example

var x = new String("John");            
var y = new String("John");
(x == y) // is false because you cannot compare objects.


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


Beware of Automatic Type Conversions

Beware that numbers can accidentally be converted to strings or NaN (Not a Number).
JavaScript is loosely typed. A variable can contain different data types, and a variable can change its data type:

Example

var x = "Hello";     // typeof x is a string x = 5;               // changes typeof x to a number

When doing mathematical operations, JavaScript can convert numbers to strings:

Example

var x = 5 + 7;       // x.valueOf() is 12,  typeof x is a number var x = 5 + "7";     // x.valueOf() is 57,  typeof x is a string var x = "5" + 7;     // x.valueOf() is 57,  typeof x is a string var x = 5 - 7;       // x.valueOf() is -2,  typeof x is a number var x = 5 - "7";     // x.valueOf() is -2,  typeof x is a number var x = "5" - 7;     // x.valueOf() is -2,  typeof x is a number var x = 5 - "x";     // x.valueOf() is NaN, typeof x is a number

Subtracting a string from a string, does not generate an error but returns NaN (Not a Number):

Example

"Hello" - "Dolly"    // returns NaN


Use === Comparison

The == comparison operator always converts (to matching types) before comparison.
The === operator forces comparison of values and type:

Example

0 == "";        // true 1 == "1";       // true 1 == true;      // true
0 === "";       // false 1 === "1";      // false 1 === true;     // false


Use Parameter Defaults

If a function is called with a missing argument, the value of the missing argument is set to undefined.
Undefined values can break your code. It is a good habit to assign default values to arguments.

Example

function myFunction(x, y) {
    if (y === undefined) {
        y = 0;
    }
}

Read more about function parameters and arguments at Function Parameters

End Your Switches with Defaults

Always end your switch statements with a default. Even if you think there is no need for it.

Example

switch (new Date().getDay()) {
    case 0:
        day = "Sunday";
        break;
    case 1:
        day = "Monday";
        break;
    case 2:
        day = "Tuesday";
        break;
    case 3:
        day = "Wednesday";
        break;
    case 4:
        day = "Thursday";
        break;
    case 5:
        day = "Friday";
        break;
    case 6:
        day = "Saturday";
        break;
    default:
        day = "Unknown";
}


Avoid Using eval()

The eval() function is used to run text as code. In almost all cases, it should not be necessary to use it.
Because it allows arbitrary code to be run, it also represents a security problem.

JavaScript Style Guide and Coding Conventions

Always use the same coding conventions for all your JavaScript projects.

JavaScript Coding Conventions

Coding conventions are style guidelines for programming. They typically cover:
  • Naming and declaration rules for variables and functions.
  • Rules for the use of white space, indentation, and comments.
  • Programming practices and principles
Coding conventions secure quality:
  • Improves code readability
  • Make code maintenance easier
Coding conventions can be documented rules for teams to follow, or just be your individual coding practice.
Note This page describes the general JavaScript code conventions used by W3Schools.
You should also read the next chapter "Best Practices", and learn how to avoid coding pitfalls.

Variable Names

At W3schools we use camelCase for identifier names (variables and functions).
All names start with a letter.
At the bottom of this page, you will find a wider discussion about naming rules.
firstName = "John";
lastName = "Doe";

price = 19.90;
tax = 0.20;

fullPrice = price + (price * tax);

Spaces Around Operators

Always put spaces around operators ( = + - * / ), and after commas:

Examples:

var x = y + z;
var values = ["Volvo", "Saab", "Fiat"];

Code Indentation

Always use 4 spaces for indentation of code blocks:

Functions:

function toCelsius(fahrenheit) {
    return (5 / 9) * (fahrenheit - 32);
}
Note Do not use tabs (tabulators) for indentation. Different editors interpret tabs differently.

Statement Rules

General rules for simple statements:
  • Always end a simple statement with a semicolon.

Examples:

var values = ["Volvo", "Saab", "Fiat"];

var person = {
    firstName: "John",
    lastName: "Doe",
    age: 50,
    eyeColor: "blue"
};
General rules for complex (compound) statements:
  • Put the opening bracket at the end of the first line.
  • Use one space before the opening bracket.
  • Put the closing bracket on a new line, without leading spaces.
  • Do not end a complex statement with a semicolon.

Functions:

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

Loops:

for (i = 0; i < 5; i++) {
    x += i;
}

Conditionals:

if (time < 20) {
    greeting = "Good day";
} else {
    greeting = "Good evening";
}

Object Rules

General rules for object definitions:
  • Place the opening bracket on the same line as the object name.
  • Use colon plus one space between each property and its value.
  • Use quotes around string values, not around numeric values.
  • Do not add a comma after the last property-value pair.
  • Place the closing bracket on a new line, without leading spaces.
  • Always end  an object definition with a semicolon.

Example

var person = {
    firstName: "John",
    lastName: "Doe",
    age: 50,
    eyeColor: "blue"
};
Short objects can be written compressed, on one line, using spaces only between properties, like this:
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

Line Length < 80

For readability, avoid lines longer than 80 characters.
If a JavaScript statement does not fit on one line, the best place to break it, is after an operator or a comma.

Example

document.getElementById("demo").innerHTML =
    "Hello Dolly.";

Naming Conventions

Always use the same naming convention for all your code. For example:
  • Variable and function names written as camelCase
  • Global variable written in UPPERCASE
  • Constants (like PI) written in UPPERCASE
Should you use hyp-hens, camelCase, or under_scores in variable names?
This is a question programmers often discuss. The answer depends on who you ask:
Hyphens in HTML and CSS:
HTML5 attributes can start with data- (data-quantity, data-price).
CSS uses hyphens in property-names (font-size).
Note Hyphens can be mistaken as subtraction attempts. Hyphens are not allowed in JavaScript names.
Underscores:
Many programmers prefer to use underscores (date_of_birth), especially in SQL databases.
Underscores are often used in PHP documentation.
PascalCase:
PascalCase is often preferred by C programmers.
camelCase:
camelCase is used by JavaScript itself, by jQuery, and other JavaScript libraries.
Note Don't start names with a $ sign. It will put you in conflict with many JavaScript library names.

Loading JavaScript in HTML

Use simple syntax for loading external scripts (the type attribute is not necessary):
<script src="myscript.js">

Accessing HTML Elements

A consequence of using "untidy" HTML styles, might result in JavaScript errors.
These two JavaScript statements will produce different results:
var obj = getElementById("Demo")

var obj = getElementById("demo")
If possible, use the same naming convention (as JavaScript) in HTML.
Visit the HTML Style Guide.

File Extensions

HTML files should have a .html extension (not .htm).
CSS files should have a .css extension.
JavaScript files should have a .js extension.

Use Lower Case File Names

Most web servers (Apache, Unix) are case sensitive about file names:
london.jpg cannot be accessed as London.jpg.
Other web servers (Microsoft, IIS) are not case sensitive:
london.jpg can be accessed as London.jpg or london.jpg.
If you use a mix of upper and lower case, you have to be extremely consistent.
If you move from a case insensitive, to a case sensitive server, even small errors can break your web site.
To avoid these problems, always use lower case file names (if possible).

Performance

Coding conventions are not used by computers. Most rules have little impact on the execution of programs.
Indentation and extra spaces are not significant in small scripts.
For code in development, readability should be preferred. Larger production scripts should be minified. 

JavaScript Use Strict

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

The "use strict" Directive

The "use strict" directive is new in JavaScript 1.8.5 (ECMAScript version 5).
It is not a statement, but a literal expression, ignored by earlier versions of JavaScript.
The purpose of "use strict" is to indicate that the code should be executed in "strict mode".
With strict mode, you can not, for example, use undeclared variables.
Note Strict mode is supported in:
Internet Explorer from version 10. Firefox from version 4.
Chrome from version 13. Safari from version 5.1. Opera from version 12.

Declaring Strict Mode

Strict mode is declared by adding "use strict"; to the beginning of a JavaScript or a JavaScript function.
Declared at the beginning of a JavaScript file, it has global scope (all code will execute in strict mode):

Example

"use strict";
x = 3.14;       // This will cause an error (x is not defined)

Example

"use strict";
myFunction();

function myFunction() {
    y = 3.14;   // This will also cause an error (y is not defined)}

Declared inside a function, it has local scope (only the code inside the function is in strict mode):
x = 3.14;       // This will not cause an error. myFunction();

function myFunction() {
   "use strict";
    y = 3.14;   // This will cause an error (y is not defined)}


The "use strict"; Syntax

The syntax, for declaring strict mode, was designed to be compatible with older versions of JavaScript.
Compiling a numeric literal (4 + 5;) or a string literal ("John Doe";) in a JavaScript program has no side effects. It simply compiles to a non existing variable and dies.
So "use strict"; only matters to new compilers that "understand" the meaning of it.

Why Strict Mode?

Strict mode makes it easier to write "secure" JavaScript.
Strict mode changes previously accepted "bad syntax" into real errors.
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.
In normal JavaScript, a developer will not receive any error feedback assigning values to non-writable properties.
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.

Not Allowed in Strict Mode

Using a variable, without declaring it, is not allowed:
"use strict";
x = 3.14;                // This will cause an error (x is not defined)


Note Objects are variables too.
Using an object, without declaring it, is not allowed:
"use strict";
x = {p1:10, p2:20};      // This will cause an error (x is not defined)


Deleting a variable (or object) is not allowed.
"use strict";
var x = 3.14;
delete x;                // This will cause an error


Deleting a function is not allowed.
"use strict";
function x(p1, p2) {};
delete x;                // This will cause an error 


Duplicating a parameter name is not allowed:
"use strict";
function x(p1, p1) {};   // This will cause an error


Octal numeric literals are not allowed:
"use strict";
var x = 010;             // This will cause an error


Escape characters are not allowed:
"use strict";
var x = \010;            // This will cause an error


Writing to a read-only property is not allowed:
"use strict";
var obj = {};
Object.defineProperty(obj, "x", {value:0, writable:false});

obj.x = 3.14;            // This will cause an error


Writing to a get-only property is not allowed:
"use strict";
var obj = {get x() {return 0} };

obj.x = 3.14;            // This will cause an error


Deleting an undeletable property is not allowed:
"use strict";
delete Object.prototype; // This will cause an error


The string "eval" cannot be used as a variable:
"use strict";
var eval = 3.14;         // This will cause an error


The string "arguments" cannot be used as a variable:
"use strict";
var arguments = 3.14;    // This will cause an error


The with statement is not allowed:
"use strict";
with (Math){x = cos(2)}; // This will cause an error


For security reasons, eval() is not allowed to create variables in the scope from which it was called:
"use strict";
eval ("var x = 2");
alert (x);               // This will cause an error


In function calls like f(), the this value was the global object. In strict mode, it is now undefined.

Future Proof!

Future reserved keywords are not allowed in strict mode. These are:
  • implements
  • interface
  • let
  • package
  • private
  • protected
  • public
  • static
  • yield
"use strict";
var public = 1500;      // This will cause an error