Invalid Left-Hand Side In Assignment Jquery Download

The function evaluates JavaScript code represented as a string.

The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone and send us a pull request.



A string representing a JavaScript expression, statement, or sequence of statements. The expression can include variables and properties of existing objects.

Return value

The completion value of evaluating the given code. If the completion value is empty, is returned.


is a function property of the global object.

The argument of the function is a string. If the string represents an expression, evaluates the expression. If the argument represents one or more JavaScript statements,  evaluates the statements. Do not call to evaluate an arithmetic expression; JavaScript evaluates arithmetic expressions automatically.

If you construct an arithmetic expression as a string, you can use to evaluate it at a later time. For example, suppose you have a variable . You can postpone evaluation of an expression involving by assigning the string value of the expression, say "", to a variable, and then calling at a later point in your script.

If the argument of is not a string, returns the argument unchanged. In the following example, the constructor is specified and returns a object rather than evaluating the string.

eval(new String('2 + 2')); // returns a String object containing "2 + 2" eval('2 + 2'); // returns 4

You can work around this limitation in a generic fashion by using .

var expression = new String('2 + 2'); eval(expression.toString());

If you use the function indirectly, by invoking it via a reference other than , as of ECMAScript 5 it works in the global scope rather than the local scope. This means, for instance, that function declarations create global functions, and that the code being evaluated doesn't have access to local variables within the scope where it's being called.

function test() { var x = 2, y = 4; console.log(eval('x + y'));  // Direct call, uses local scope, result is 6 var geval = eval; // equivalent to calling eval in the global scope console.log(geval('x + y')); // Indirect call, uses global scope, throws ReferenceError because `x` is undefined   (0, eval)('x + y'); // another example of Indirect call }

Do not ever use !

is a dangerous function, which executes the code it's passed with the privileges of the caller. If you run with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage / extension. More importantly, a third-party code can see the scope in which was invoked, which can lead to possible attacks in ways to which the similar is not susceptible.

is also slower than the alternatives, since it has to invoke the JS interpreter, while many other constructs are optimized by modern JS engines.

Additionally, modern javascript interpreters convert javascript to machine code. This means that any concept of variable naming gets obliterated. Thus, any use of eval will force the browser to do long expensive variable name lookups to figure out where the variable exists in the machine code and set it's value. Additonally, new things can be introduced to that variable through  such as changing the type of that variable, forcing the browser to reevaluate all of the generated machine code to compensate. However, there (thankfully) exists a very good alternative to eval: simply using window.Function. As an example of how you convert code using evil  to using  , see below.

Bad code with eval:

Better code without eval:

Comparing the two code snippets above, the two code snippets might seem to work the same way, but think again: the eval one is a huge amount slower. Notice  in the evaluated object. In the function without the eval, the object is being evaluated in the global scope, so it is safe for the browser to assume that  refers to  instead of a local variable called Date. But, in the code using , the browser cannot assume this since what if your code looked like the following:

Thus, in the  version of the code, the browser is forced to make the expensive lookup call to check to see if there are any local variables called . This is incredibly innefficient compared to .

In a related circumstance, what if you actually wanted your  function to be able to be called from the code inside . Should you just wimp out and fall back to ? Absolutely not, never ever. Instead try the aproach below.

function Date(n){ return ["Monday","Tuesday","Wednessday","Thursaday","Friday","Saturday","Sunday"][n%7 || 0]; } function runCodeWithDateFunction(obj){ return Function('"use strict";return (' + obj + ')')()( Date   ); } console.log(runCodeWithDateFunction( "function(Date){ return Date(5) }" ))

The code above may seem inefficiently slow because of the triple nested function, but let's analyse the benefits of the above efficient method:

1. It allows the code in the string passed to  to be minified.

2. Function call overhead is minimal, making the far smaller code size well worth the benefit

3.  more easily allows your code to utilize the performance buttering 

4. The code does not use , making it orders of magnitude faster than otherwise.

Lastly, let's examine minification. With using   as shown above, you can minify the code string passed to  far more efficiently because the function arguments names can be minified too as seen in the minified code below.

console.log(Function('"use strict";return(function(a){return a(5)})')()(function(a){ return"Monday Tuesday Wednessday Thursaday Friday Saturday Sunday".split(" ")[a%7||0]}));

There are also additional safer (and faster!) alternatives to  or  for common use-cases.

Accessing member properties

You should not use to convert property names into properties. Consider the following example where the property of the object to be accessed is not known until the code is executed. This can be done with eval:

var obj = { a: 20, b: 30 }; var propName = getPropName(); // returns "a" or "b" eval( 'var result = obj.' + propName );

However, is not necessary here. In fact, its use here is discouraged. Instead, use the property accessors, which are much faster and safer:

var obj = { a: 20, b: 30 }; var propName = getPropName(); // returns "a" or "b" var result = obj[ propName ]; // obj[ "a" ] is the same as obj.a

You can even use this method to access descendant properties. Using this would look like:

var obj = {a: {b: {c: 0}}}; var propPath = getPropPath(); // returns e.g. "a.b.c" eval( 'var result = obj.' + propPath );

Avoiding here could be done by splitting the property path and looping through the different properties:

function getDescendantProp(obj, desc) {   var arr = desc.split('.');   while (arr.length) { obj = obj[arr.shift()]; }   return obj; } var obj = {a: {b: {c: 0}}}; var propPath = getPropPath(); // returns e.g. "a.b.c" var result = getDescendantProp(obj, propPath);

Setting a property that way works similarly:

function setDescendantProp(obj, desc, value) {   var arr = desc.split('.');   while (arr.length > 1) { obj = obj[arr.shift()]; }   return obj[arr[0]] = value; } var obj = {a: {b: {c: 0}}}; var propPath = getPropPath(); // returns e.g. "a.b.c" var result = setDescendantProp(obj, propPath, 1); // test.a.b.c will now be 1

Use functions instead of evaluating snippets of code

JavaScript has first-class functions, which means you can pass functions as arguments to other APIs, store them in variables and objects' properties, and so on. Many DOM APIs are designed with this in mind, so you can (and should) write:

// instead of setTimeout(" ... ", 1000) use: setTimeout(function() { ... }, 1000); // instead of elt.setAttribute("onclick", "...") use: elt.addEventListener('click', function() { ... } , false);

Closures are also helpful as a way to create parameterized functions without concatenating strings.

Parsing JSON (converting strings to JavaScript objects)

If the string you're calling on contains data (for example, an array: ), as opposed to code, you should consider switching to JSON, which allows the string to use a subset of JavaScript syntax to represent data. See also Downloading JSON and JavaScript in extensions.

Note that since JSON syntax is limited compared to JavaScript syntax, many valid JavaScript literals will not parse as JSON. For example, trailing commas are not allowed in JSON, and property names (keys) in object literals must be enclosed in quotes. Be sure to use a JSON serializer to generate strings that will be later parsed as JSON.

Pass data instead of code

For example, an extension designed to scrape contents of web-pages could have the scraping rules defined in XPath instead of JavaScript code.

Run code with limited privileges

If you must run the code, consider running it with reduced privileges. This advice applies mainly to extensions and XUL applications, which can use Components.utils.evalInSandbox for this.



In the following code, both of the statements containing return 42. The first evaluates the string ""; the second evaluates the string "".

var x = 2; var y = 39; var z = '42'; eval('x + y + 1'); // returns 42 eval(z); // returns 42

Using to evaluate a string of JavaScript statements

The following example uses to evaluate the string . This string consists of JavaScript statements that open an alert dialog box and assign a value of 42 if is five, and assigns 0 to otherwise. When the second statement is executed, will cause these statements to be performed, and it will also evaluate the set of statements and return the value that is assigned to .

var x = 5; var str = "if (x == 5) {console.log('z is 42'); z = 42;} else z = 0;"; console.log('z is ', eval(str));

If you define multiple values then the last value is returned.

var x = 5; var str = "if (x == 5) {console.log('z is 42'); z = 42; x = 420; } else z = 0;"; console.log('x is ', eval(str)); // z is 42 x is 420

Last expression is evaluated

returns the value of the last expression evaluated.

var str = 'if ( a ) { 1 + 1; } else { 1 + 2; }'; var a = true; var b = eval(str); // returns 2 console.log('b is : ' + b); a = false; b = eval(str); // returns 3 console.log('b is : ' + b);

as a string defining function requires "(" and ")" as prefix and suffix

var fctStr1 = 'function a() {}' var fctStr2 = '(function a() {})' var fct1 = eval(fctStr1) // return undefined var fct2 = eval(fctStr2) // return a function


Browser compatibility

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out and send us a pull request.

FeatureChromeEdgeFirefoxInternet ExplorerOperaSafari
Basic support Yes Yes1 Yes Yes Yes
FeatureAndroid webviewChrome for AndroidEdge mobileFirefox for AndroidOpera AndroidiOS SafariSamsung Internet
Basic support Yes Yes Yes4 Yes Yes ?
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidiOS SafariSamsung InternetNode.js
Basic supportFull support YesFull support YesFull support 1Full support YesFull support YesFull support YesFull support YesFull support YesFull support YesFull support 4Full support YesFull support Yes ? Full support Yes


Full support
Full support
Compatibility unknown
Compatibility unknown

Firefox-specific notes

  • Historically had an optional second argument, specifying an object in whose context the evaluation was to be performed. This argument was non-standard, and was definitely removed from Firefox 4. See bug 531675.

See also


JavaScript is the most widely used client-side programming language that lets you supercharge your HTML with interactivity, animation and dynamic visual effect for better User Interface and User Experience (UI/UX). It is:

  • a small, lightweight, object-oriented, cross-platform, special-purpose scripting language meant to be run under a host environment (typically a web browser).
  • a client-side scripting language to enrich web user-interfaces and create dynamic web pages (e.g., form input validation, and immediate response to user's actions).
  • the engine that supports AJAX (Asynchronous JavaScript and XML), which generate renew interest in JavaScript.

JavaScript works together with HTML/CSS. HTML provides the contents (or structure); CSS specifies the presentation; and JavaScript programs the behavior. Together, they enrich the UI/UX of the web users.

History and Versions

JavaScript, originally called LiveScript, was created by Brendan Eich at Netscape in 1995. Soon after, Microsoft launched its own version of JavaScript called JScript. Subsequently, Netscape submitted it to ECMA (formerly "European Computer Manufacturers Association", now "Ecma International - European association for standardizing information and communication systems") for standardization, together with Microsoft's JScript.

The ECMA Specification is called "ECMA-262 ECMAScript Language Specification" (also approved as "ISO/IEC 16262"):

Meanwhile, the Mozilla Project (@ continues to upgrade the JavaScript with these major versions:

  • 1.0 (1996)
  • 1.3 (1998): ECMA-262 version 1 compliance
  • 1.5 (1999): ECMA-262 version 3 compliance
  • 1.6, 1.7:
  • 1.8 (2008), Latest 1.8.5 (2010): ECMA-262 version 5 compliance
JavaScript vs. Java

Java is a full-fledgedgeneral-purpose programming language created by James Gosling at Sun Microsystems (now part of Oracle), released in Aug 1995. JavaScript is created by Brendan Eich at Netscape in 1995. Originally called LiveScript, it is a small and lightweight special-purpose language for writing client-side program running inside the web browser to create active user-interface and generate dynamic web pages. Java also supports client-side programming via the so-called Java applets.

JavaScript is not a general-purpose nor a stand-alone programming language (it has to be run inside the browser). It was originally called LiveScript and was renamed to JavaScript in an ill-fated marketing decision to try to capitalize on the popularity of Java language, when Netscape released it Navigator 2 in 1996 (Navigator 2 also runs the Java applets). Java and JavaScript are totally different languages for different programming purposes. However, in the early days, some efforts were made to adopt Java syntaxes and conventions into JavaScript, such that JavaScript seems to be a subset of Java. In reality, they have very little in common. But, if you know Java, you should find JavaScript easier to learn because of these common syntaxes.

What JavaScript CANNOT Do?

Remember that JavaScript is a client-side program that you downloaded from a server, and run inside the browser of your (client) machine. What to stop someone from writing a JavaScript that wipes out your hard disk, or triggers a denial-of-service attack to another server? As a result, for security purpose,

  1. It cannot read file from the client's machine.
  2. It can only connect to the server that it come from. It can read file from the server that it come from. It cannot write file into the server machine.
  3. It cannot connect to another server.
  4. It cannot close a window that it does not open.
JavaScript is Now Everywhere!

JavaScript was originally created as a client-side web programming language, running in a web browser, to supercharge HTML. It has grown beyond the client-side programming.

The popular Node.js is a standalone JavaScript engine that lets you run JavaScripts in a standalone manner (i.e., without a browser). Node.js also enables you to write server-side programs in JavaScript, i.e., you can now write both your client-side programs and server-side programs in the same language. Many front-end web development tools, such as and , are built upon Node.js and programmed in JavaScript.

JavaScript is also used for writing scripts for Software such as Acrobat, Dreamweaver and Google Apps.


jQuery is a cross-browser JavaScript Library. It is reported that more than 64% of the production websites are written in jQuery nowadays (as in May 2015). jQuery is JavaScript (but having its own extension syntax), hence, you need to understand JavaScript. I suggest you read through the JavaScript syntax (and pay particular attention to objects), and then switch into jQuery for your production. Read "jQuery Basics".

JavaScript by Examples

I shall assume that you know HTML and CSS (read my HTML/CSS articles otherwise). I shall also assume that you understanding some programming basics such as variables, if-else and for-loop constructs.

You need a text editor to write your JavaScript. You could use a plain text editor such as NotePad. But to improve your productivity, a good programming text editor is essential. There are many freeware/shareware available, such as Sublime Text (@, NotePad++ (, PSPad (, TextPad ( You can also use a full-scale IDE such as NetBeans or Eclipse, which provides content-assist (auto-complete) feature that greatly enhances your productivity.

JavaScripts run inside a browser. There are standards on JavaScript. But the Big-5 (Chrome, Firefox, IE, Safari and Opera), in particular the IE, does not adhere to all the standards strictly. Furthermore, they create their own extensions. Hence, the behavior of JavaScript could be different in different browsers. You may need to test your JavaScripts on more than one browsers. [That's where jQuery comes in handy, as jQuery provides cross-browser support.]

Example 1: Functions and

Let us write our first JavaScript to print the message "Hello, world".

Start with a new file and enter the following codes. Do not enter the line numbers, which is used to aid in explanation. Take note that:

  • JavaScript is case sensitive. A is NOT a and is NOT a .
  • "Extra" white spaces (blanks, tabs and newlines) are ignored. That is, multiple white spaces is treated as a single blank character. You could use them liberally to make your program easier to read.

Save the file as "" (or any filename that you prefer, with file extension of "" or ""). Run the script by loading the HTML file into a JavaScript-enabled browser (e.g., One of the BIG FIVE - Chrome, Firefox, Internet Explorer, Safari or Opera).

How it Works?
  1. JavaScripts are programming codes that are embedded inside an HTML document. The codes are contained between a pair of and tags, as follows: <script> </script> NOTE: In HTML4/XHTML, you need to include attribute to the opening tag.
  2. You could place the scripts in either the section (called header script) or section (called body script) of an HTML document. You are free to embed as many scripts into a single document as you like, using multiple element. Lines 7-9 and Line 13-17 are two pieces of JavaScripts, placed in the and sections, respectively.
  3. JavaScript statements are terminated by a semicolon .
  4. The function (Line 8) pops out a dialog box displaying the and a OK button. Strings are enclosed by a pair of double quotes or single quotes.
  5. The current web page is represented by the so-called object in the JavaScript. The (Line 16) property stores the last modified date of the current document. The function (Line 14 to 16) can be used to write the specified to the current document, as part of the current HTML document.
  6. The operator (Line 16) concatenates pieces of the strings (similar to Java language).
  7. As a result of the , the BODY section of this document contains: <h1>My First JavaScript says</h1> <h2><em>Hello world, again!</em></h2><p>This document was last modified on mm/dd/yyyy hh:mm:ss.</p>
  8. The and are some of the commonly-used built-in functions provided in JavaScript.

TRY: Print the document's title and the URL location. (Hints: use and properties.)

Example 2: Variables and Functions ,

This script prompts the user for his/her name, confirms the name, and prints a greeting message.

There are three kinds of pop-up dialog boxes for interacting with the users:

  1. The function puts the on a pop-up box with a OK button. User needs to click the OK button to continue.
  2. The function puts up an input pop-up box with the with an OK and Cancel buttons. It returns the input entered by the user as a string; or a special value called if the user hits the Cancel button. The optional parameter defaultString specifies the initial string to be shown. In this article, I shall indicate optional function parameters with a trailing for compactness.
  3. The function puts on a pop-up box with OK and Cancel buttons. It returns if user hits the OK button; or otherwise.
How it Works?
  1. Line 8 declares a variable called , via the keyword . A variable is a named storage location that holds a value. Once the variable is declared, you can assign (and re-assign) a value to that variable, via the assignment operator (Line 9).
  2. Line 9 invokes the function to pop out a dialog box, and reads in the string entered by the user. The string read is assigned to the variable . The function is similar to the , but it accepts a user's input.
  3. In Line 10, the function puts up the message and returns either or , depending on whether the user hits the OK or Cancel button.
  4. If the result is , Line 11 prints . Otherwise, Line 13 prints .

TRY: Instead of printing the greeting message using , do it via an .

Example 3: The Object

The following script creates a object representing the current date-time, and prints the current time.

How it Works?
  • Line 8 declares a variable called . It also creates a object (via the operator), which contains the current date-time stamp, and assign it to .
  • "" begins an end-of-line comment (Lines 8 and 9). Comments are ignored by the JavaScript engine but important in explaining your codes to others (and to yourself three days later).
  • Line 9 declares a variable called . It also invokes the function on object , in the form of , to retrieve the hour part of object , and assign it to variable . Lines 9 and 10, similarly, handle the minutes and seconds.
  • Line 12 to 14 use to write to the current document. (write-line) writes a newline () after the given string. Take note that browser ignores extra white space (newlines, blanks, tabs) in an HTML document; you need to write a or tag to ask the browser to display a line break.
  • Lines 16-20 contains a conditional if-then-else statement. Depending on the value of , one of the messages will be displayed.
  1. Modify the above script to print the current date, month, year and day of the week. (Hints: Use functions , , and of a object. returns 1-31. returns 0 to 11 for January to December. returns a 4-digit year. returns 0 to 6 for Sunday to Saturday).
  2. Use a conditional statement to print the day of the week in word (i.e., 0 for Sunday, 1 for Monday and etc.). (Hints: Use the construct as follow.) if (condition-1) {block-1 ; } else if (condition-2) {block-2 ; } else if (condition-3) {block-3 ; ...... ...... } else {block-n ; }

Example 4: Loops

The following script prompts the user for a multiplier, and prints the multiples of 1 to 100 using a for-loop.

How it Works?
  • Line 11 prompts the user for a number, and assigns it to the variable .
  • Lines 12-14 contain a for-loop. A for-loop takes the following syntax: for (initialization;test;post-processing) {body;}

    There are four parts in a for-loop. Three of them, initialization, test and post-processing, are enclosed in brackets and separated by 2 semicolons. The body contains the repetitive task to be performed. The initialization statement is first executed. The test is then evaluated. If the test returns true, the body is executed; followed by the post-processing statement. The test is evaluated again and the process repeats until the test returns false. When the test is false, the for-loop completes and program execution continues to the next statement after the for-loop. The following flow chart illustrates the for-loop process:

    In this example, the variable is initialized to 1. If is less than or equal to 100, the body of the loop executes, followed by the post-processing statement, which increment the value of by 1. The loop repeats until the value of is NOT less than or equal to 100 (i.e., more than 100).

  1. Modify the above script to prompt the user for the multiplier as well as the number of multiples to be printed (in two statements).
  2. Modify the above script to print only multiples that are odd number. (Hint: The modulo operator "" can be used to compute the remainder, e.g., computes the remainder of divides by 2, which results in either 0 or 1.)

Example 5: User-defined Functions and Event Handler

Besides the JavaScript built-in functions such as , , , and , you can define your own functions. A function has a name and a body consisting of a set of JavaScript statements that collectively performs a certain task. It may take zero or more argument(s) from the caller and return zero or one value back to the caller.

How it Works?
  • Lines 8-10 define a function called , via the keyword . The function invokes the built-in function , which opens a new browser window (or tab) and loads the page "".
  • Lines 15-16 create an HTML button. Clicking the button triggers the event handler, i.e., defined earlier.

TRY: Include another button, which opens "".

Example 6: More Event Handlers: , and

JavaScript can be used to handle many types of events, in response to a user's action or browser's action. For example,

  • : fires after browser loaded the page.
  • and : fires when the user points the mouse pointer at/away from the HTML element.
Dissecting the Program
  • Line 8 defines a variable , which holds the strings to be displayed in the event handlers.
  • In the opening tag (Line 12), we define the event handler for the event. It invokes with the message defined earlier.
  • Line 13 and 14 defines the event handlers and for the HTML element . The text's color will be changed to red when the user points the mouse pointer at the element (by setting the CSS style property to red), and revert back to its original color when the mouse pointer is moved away (by resetting the CSS style property to an empty string). The special keyword refer to this object.

Example 7: Separating HTML, CSS and JavaScript

The previous example works fine. You will find many such example in textbooks, especially the older textbooks. However, it has a big problem. All the HTML contents, CSS presentation styles and JavaScript programming codes are placed in a single file. For a small toy program, the problem is not serious. But when your program grows and if the HTML, CSS and JavaScript are written by different people, you will have a real challenge in maintaining the program. Remember that HTML is for the contents, CSS for presentation and JavaScript for the behavior.

Let's rewrite the example to place the HTML, CSS and JavaScript in three different files.

How it Works?
  1. Placing the scripting codes inside the HTML page is not a good software engineering practice. Instead, the now-preferred approach is to place the scripts, as well as CSS styles, in external files, which can then uniformly applied to all pages in your website.
  2. Let's begin with the HTML file. Now, the HTML file keeps only the contents, no presentation style and nor programming logic.
    1. <link rel="stylesheet" href="JSExFiles.css">
      The CSS style sheet is kept in an external file, referenced via the above tag.
      Note: In HTML4/XHTML1.0 you need to include attribute in the opening tag.
    2. <script src="JSExFiles.js"></script>
      Also, the JavaScript programming code is kept in an external file, referenced via the above tag. Take note that the closing tag is needed, although there is no content.
      Note: In HTML4/XHTML1.0, you need to include attribute in the opening tag.
    3. <p id="magic">Point your mouse pointer here!!!</p>
      We provide an unique to this tag. This will be used in the JavaScript to select this tag.
  3. The CSS file contains only one style definition:
    .highlight { color:red; }
    This define a CSS Class-Selector called to display the element with in color red.
  4. In the JavaScript:
    1. window.onload = function() { ... }
      We attach a so-called inline function as the event handler. This function will be invoked after the page is fully loaded.
    2. document.getElementById("magic").onmouseover = function() { this.className = "highlight"; }
      We use function to select the element. We then attach an inline function as the event handler for this element. When the user moves the mouse over this element, this function changes the attribute to "". In response, the CSS turns the element to color red.
    3. document.getElementById("magic").onmouseout = function() { this.className = ""; }
      Similarly, when the user moves the mouse out of the element, the event handler changes the attribute to "". In response, CSS changes the color to its default.
    4. alert("Hello!")
      This puts up an alert dialog box.

Example 8: Manipulating the Contents of HTML Elements

You can select HTML element(s) within the current page via these functions:

  1. document.getElementById(anId): returns the HTML element with , or if the does not exist. The attribute should be unique within an HTML document.
  2. document.getElementsByTagName(aTagName): returns an array of HTML elements with the given HTML tag name.
  3. document.getElementsByClassName(aClassName): returns an array of HTML elements having attribute .
  4. document.getElementsByName(aName): returns an array of HTML elements having attribute .

To modify the content of an HTML element, you can assign a new value to the property of that element. (The property is really useful and is supported in most of the browsers. It is, however, not included in the W3C DOM specification?!)

How it works?
  1. This HTML document contains a element with an unique (Line 10), two elements (Line 11-12), three elements with (Line 13-15), and three with unique (Line 16-18).
  2. In the user-defined function , we use to select the element, and then modify its property.
  3. In function, we use to select all the elements in an array . We then use a for-loop to iterate through all the elements in the array. The property keeps the length of the array.
  4. In function, we use to select all the elements.
  5. The page contains three buttons to trigger the functions defined (Line 16-18).
  6. The script contains a function , which is assigned as the handler via . That is, will be triggered after the page is loaded. The function assigns event handlers to the buttons, selected via using the unique buttons' .


Example 9: Intercepting a Hyperlink

This example uses a script to intercept a hyperlink to put up a warning message, then proceed to the link.

How it works?
  1. The HTML page has an hyperlink with an unique .
  2. The function assigns an handler to the hyperlink, selected via .
  3. When the hyperlink is clicked, the handler triggered. If returns true, the new page will be loaded; otherwise, the current page remains.


More Advanced JavaScript Examples

More "Advanced JavaScript Examples".

Debugging JavaScripts

A good graphic debugger is a MUST for programming in any language. Programming in JavaScript, in particular, requires a graphic debugger. It is because JavaScripts are interpreted and does not need to be compiled. Hence, there is no compiler to show you the syntax errors. A simple and trivial syntax error (e.g., missing bracket, mis-spelling) will render the entire script not workable. Worst still, you would not see any error message when the script did not work. Can you debug without any error message or clue?

Without a graphic debugging, the only mean to debug JavaScript is to insert at strategic locations to print out selected data.

After modifying a JavaScript, I recommend that you use Ctrl-F5 to refresh the page, which shall load a fresh copy instead of loading from the cache. You might need to clear the browser's cache or re-start the browser, if you modification does not take effect.

F12 Developer Tools

In Chrome and Firefox, you can press F12 to activate the developer Tools (hence called F12 Developer Tools).

Firefox: Firebug plug-in (or Web Developer Tools) - ESSENTIAL!!!

Simply GREAT and MUST HAVE for debugging HTML/CSS and JavaScript!!! You can install firebug from It provides these features:

  1. Console: View the JavaScript error messages. Start the firebug and switch to the "Console" panel.
  2. Script: View and debug JavaScript. Start the firebug. Switch to the "Script" panel. "Enable" or "Reload" if necessary. You can set a breakpoint by clicking on the statement number, single step through the JavaScript statements, watch the expression, and etc. Read "JavaScript Debugger and Profiler".
  3. DOM: View the HTML DOM of the current document.
  4. HTML and CSS.

To debug JavaScript under Firebug:

  1. Launch Firebug ⇒ Choose the "Script" panel to view your JavaScript, shown with green-bold line numbers.
  2. Refresh (Ctrl-F5) the page, and check the error console (Under "Console" ⇒ "Errors") for syntax errors! Correct all the syntax errors.
  3. To trace the program, set breakpoints at selected JavaScript statements, by clicking on the right margin (to the left of line number). A red circle shows up denoting a breakpoint. Take note that you can only set breakpoint on statements with a green-bold line number. [If your JavaScript statements do not have a green-bold line number, there are syntax errors on these statements. You need to correct the syntax errors and reload the page.]
  4. Trigger the script (via clicking button/link, or reloading the page). The execution stops at the first breakpoint. You can then step-over the statement (or step-into function), and inspect the variables by positioning the mouse pointer on the variable; or add the variable to "watch".
  5. You can resume the execution (via the continue button).

Notes: If you get the error "Script Panel was inactive during page load" when switching into the "script" panel, you need to disable "private browsing" in Firefox's Tools ⇒ Options ⇒ Privacy.

Firefox also has a built-in "Web Developer Tools", having similar functions as Firebug plug-in.

Chrome: Developer Tools

You can activate Chrome's Developer Tools via "Control" ⇒ "More Tools" ⇒ "Developer Tools".


Instead of using and to show the intermediate results, you can also use , which writes the and the value of the to the error console. It does not interfere the appearance you web page nor your normal operations.

For example, modify the JavaScript in Example 8 to print the values of innerHTML before modification. You need to turn on the console (press F12) to see the output.

JavaScript IDE

Popular JavaScript IDEs are:


You can write JavaScripts by creating a web application under NetBeans (Read "Developing web application under NetBeans"), via "new" ⇒ "Others" ⇒ In "Categories", select "Other" ⇒ In "File Types", select "HTML File" or "JavaScript File". NetBeans provides content-assist (or auto-complete) feature, which greatly improves your productivity.

You need to use Firebug or Web developer Tools to debug JavaScript.



Aptana Studio

An open source IDE (based on Eclipse), which supports JavaScript and Ajax.

JavaScript and HTML

As seen from the previous examples, JavaScripts are embedded inside an HTML document, and executed by the browser. There are two occasions on which browser executes JavaScript instructions:

  1. JavaScripts enclosed in runs during loading of the page.
  2. Some JavaScripts, called event handlers, run as a result of the user's or browser's action (or event). For example, clicking a button () or loaded a page ().

There are, therefore, two places to put your JavaScript:

  1. between and container tags; and
  2. inside the HTML tags as the event handlers (such as , , ), e.g., .

The Element

The element contains the JavaScript programming statements. For example,

<script> </script>

In HTML4/XHTML1.0, you need to include the attribute in the opening tag.

In or ?

You can place your JavaScript in either the section (called Header Script) or section (called Body Script) of an HTML document. Typically, global variables and function definitions are placed in section, which will always be loaded and available to be used by the scripts in the section. If you script refers to the DOM elements. place it before the , so as to ensure that the DOM is constructed. Placing the outside the HEAD or BODY causes a HTML5 validation error.

External JavaScripts

The now-preferred approach is to keep the JavaScript in an external file with file extension of "", and reference it via the (source) attribute as follows:

<script src="JavaScriptFilename.js"></script>

Take note that the closing tag is needed although there is no content!?

In HTML4/XHTML1.0, you need to include in the opening tag.

The Element

The element provide an alternate message if scripting is disabled or not supported.

JavaScript Basic Syntax


Comments are ignored by the JavaScript runtime but greatly useful in explaining your codes to others (and also to yourself three days later). You should use comments liberally to explain or document your codes.

An end-of-line comment begins with and lasts till the end of the current line. A multi-line comment begins with and lasts till .

Take note that:

  • HTML comments are enclosed inside ;
  • CSS uses , but NOT .
  • JavaScript supports both and , like Java/C/C++.


An expression is a combination of variables, literals, operators, and sub-expressions that can be evaluated to produce a single value.

Statement and Block

A statement is a single instruction consisting of operators, variables and expression. It is strongly recommended to end each statement with a semicolon (Although it is not strictly necessary as the new-line can also serve as the statement terminator in JavaScript).

A block consists of zero or more statements enclosed in a pair of curly braces . No semicolon is needed after the closing brace.

Variable, Literals & Types

Variables & Assignment Operator

A variable is a named storage location that holds a value, e.g., , , and .

  • A variable name (aka identifier) must begins with a letter (, ), underscore , or dollar sign . Subsequent characters could contain digits (). Take that that jQuery uses , , which are valid identifiers. Hyphen and space are not allowed, hence, , , are NOT valid identifiers.
  • JavaScript is case sensitive. A is not a and is not a .
  • A variable is declared using keyword .
  • You can assign (and re-assign) a value to a variable using the assignment operator.

A literal is a fixed value, e.g., , , , , that can be assigned to a variable, or form part of an expression.


JavaScript is object-oriented. But, It supports both primitive types and objects.

JavaScript supports these primitive types:

  1. string: a sequence of characters. Strings literals are enclosed in a pair of single quotes or double quotes (e.g., , ).
  2. number: takes both integer (e.g., ) or floating-point (e.g., ).
  3. boolean: takes boolean literal of either or (in lowercase).
  4. undefined: takes a special literal value called . Take note that is both a type and a literal value.
  5. symbol: new in ECMAScript 6. A data type whose instances are unique and immutable.

JavaScript also supports these object types and value (we shall discuss object later):

  1. object: for general objects.
  2. function: for function objects.
  3. null: A special literal value for unallocated .

Unlike most of the general programming languages (such as Java/C/C++/C#) which are strongly type, JavaScript is loosely type (similar to most of the scripting languages such as UNIX Shell Script, Perl, Python). You do not have to explicitly declare the type of a variable (such as and ) during declaration. The type is decided when a value is assigned to that variable. If a number is assigned, the variable takes on the type and can perform numeric operations such as addition and subtraction. If a string is assigned, the variable takes on the type and can perform string operations such as string concatenation.


You can use the operator to check the type of a variable.

The Type and Literal Value

An undeclared variable (via keyword) takes on a special type called . You cannot refer to its value.

When a variable is declared (via keyword) without assigning an initial value, it takes on the type and holds a special value called ( is probably more precise?!), As soon as a value is assigned, the variable takes on the type of that value. The act of putting a value into a variable sets its type. You can change the type of a variable by re-assigning a value of another type. Types are converted automatically as needed during execution (known as dynamically-typed).

For examples,

console.log('type:' + typeof v1); var v1; console.log('type: ' + typeof v1); console.log('value: ' + v1); v1 = 'abc'; console.log('type: ' + typeof v1); console.log('value: ' + v1); v1 = '123'; console.log('type: ' + typeof v1); console.log('value: ' + v1); v1 = 123; console.log('type: ' + typeof v1); console.log('value: ' + v1); v1 = 55.66; console.log('type: ' + typeof v1); console.log('value: ' + v1); v1 = false; console.log('type: ' + typeof v1); console.log('value: ' + v1); v1 = null; console.log('type: ' + typeof v1); console.log('value: ' + v1); v1 = {name:'peter', age:21}; console.log('type: ' + typeof v1); console.log('value: ' + v1); console.log('value: ' +; console.log('value: ' + v1.age); v1 = new Date(); console.log('type: ' + typeof v1); console.log('value: ' + v1); v1 = function() { return 'hello'; }; console.log('type: ' + typeof v1); console.log('value: ' + v1);

You can create a read-only, named constant with the keyword (in place of ). For example,

const SIZE = 9;

Unfortunately, the keyword has yet to be widely supported by web browsers. So don't use.

The Type, Literals & Operations

A variable of type holds a number, either an integer or a floating-point number.

Integer literals can be expressed in:

  • Decimal: begins with a digit to (not ), e.g., or ,
  • Octal: begins with a digit , e.g., or ,
  • Hexadecimal: begins with (or ), e.g., or .
  • Binary: begins with (or ), e.g., or . [Binary may not be supported in some browsers.]

Floating-point literals can be expressed in the usual form (e.g., ) or scientific notation, e.g., , .

JavaScript also provides some special literals:

  • infinity: e.g.,
  • -infinity: e.g.,
  • NaN (Not-a-Number): e.g., , or converting the string to a number.
Arithmetic Operations

Arithmetic operations, as tabulated below, can be applied to numbers. The following results are obtained assuming that , before the operation.

OperatorDescriptionExample (, )Result
+Additionz = x + y;z is 7
-Subtraction (or Unary Negation)z = x - y;z is 3
*Multiplicationz = x * y;z is 10
/Divisionz = x / y;z is 2.5
%Modulus (Division Remainder)z = x % y;z is 1
++Unary Pre- or Post-Incrementy = x++; z = ++x;
Same as: y = x; x = x+1; x = x+1; z = x;
y is 5; z is 7; x is 7
--Unary Pre- or Post-Decrementy = --x; z = x--;
Same as: x = x-1; y = x; z = x; x = x-1;
y is 4; z is 4; x is 3

In JavaScript, arithmetic operations are always performed in double-precision floating-point. That is, gives (instead of 0 in Java/C/C++). You may use the built-in function to truncate a floating-point value to an integer, e.g., and gives . You may also use the built-in mathematical functions such as , , for converting a floating-point number to an integer.

Arithmetic cum Assignment Operators

These are short-hand operators to combine two operations.

+=Addition cum Assignmentx += y;Same as: x = x + y;
-=Subtraction cum Assignmentx -= y;Same as: x = x - y;
*=Multiplication cum Assignmentx *= y;Same as: x = x * y;
/=Division cum Assignmentx /= y;Same as: x = x / y;
%=Modulus cum Assignmentx %= y;Same as: x = x % y;
The Operations
  • parseInt(aString): Parse the until the first non-digit, and return the number; or .
  • parseFloat(aString):
  • Math.round(aNumber), Math.floor(aNumber), Math.ceil(aNumber):
  • Math.random(): Generate a random number between 0 (inclusive) and 1 (exclusive).
  • isNaN(aString): return true if the is not a number. For example, console.log(isNaN('123')); console.log(isNaN('1.23')); console.log(isNaN('123abc')); It is interesting to note that JavaScript does not have counterpart functions like , .
  • Number(aString): Return the number represented by , or . Take that that this function name begins with uppercase, because this is a type casting operation.
  • .toFixed(deciamlPlaces): Return this number/string to the given number of decimal places. For example, var n = 1.2345; console.log(n.toFixed(2)); console.log(n);

The Type, Literals & Operations

A is a sequence of characters enclosed within a pair of single quotes or double quotes (e.g., , , , ). You can use an escape sequence to represent special characters (such as for new-line, for tab, and for Unicode character); and to resolve conflict (e.g., , , ).

Unlike Java/C/C++, but like HTML/CSS's attributes, you can use either single quotes or double quotes for . This is handy as you can use single quotes if the contains double quotes (e.g., ), without using the escape sequences (e.g., ).

JavaScript is dynamically-type, and performs type conversion automatically. When a value is used in arithmetic operations (such as subtraction or multiplication), JavaScript runtime automatically converts the to a if it represents a valid ; or a special called (not-a-number) otherwise. For example,

console.log('55' - '66'); console.log('55' * 2); console.log('Hello' - 1);
The Operator: Addition or Concatenation?

If both the operands to a operator are , it performs the usual numeric addition. However, if one (or both) of the operand is a , the operator is overloaded to perform string concatenation. The other operand will be converted to a , if necessary. For example,

console.log(11 + 22); console.log('11' + '22'); console.log('11' + 22); console.log('Hello' + 22);
Built-in Functions , and

To convert a numeric to a , you could use the built-in functions or , which returns a if conversion is successful; or otherwise. For example,

var magic = "11"; console.log(magic + 22); console.log(parseInt(magic) + 22); console.log(parseInt(magic) + "22"); console.log(parseInt(magic) + parseFloat("22.33")); console.log(parseInt("abc"));

Take note that works as long as the begins with digits. It will parse up to the first non-digit. For example,


You can also use the function , which converts the object argument to a number that represents the object's value; or if conversion fails. For example,

var magic = "8888" console.log(magic + 8); console.log(Number(magic) + 8); console.log(new Date(2015, 5, 1, 12, 34, 56));
String's Properties
  • .length: E.g., returns the length of the string.
String's Operations
  • .toUpperCase(): returns the uppercase string.
  • .toLowerCase(): returns the lowercase string.
  • .charAt(index): returns the character at the position. Index begins from 0. Negative index can be used, which counts from the end of the string.
  • .substring(beginIndex, endIndex): returns the substring from (inclusive) to (exclusive).
  • .substr(beginIndex, length): returns the substring from of .
  • .indexOf(searchString, fromIndex?): Return the beginning index of the first occurrence of , starting from an optional (default of 0); or if not found.
  • .lastIndexOf(searchString, fromIndex?): Return the beginning index of the last occurrence of , starting from an optional (default of ); or if not found.
  • .slice(beginIndex, endIndex): Return the substring from (inclusive) to (exclusive).
  • .split(delimiter): returns an array by splitting the string using .
  • Searching/Modifying Strings using Regular Expression: See "Regular Expression".
Multi-line String

You can create a multi-line string via back-quotes `...`. For example,

console.log(`string line 1 string line 2`); console.log('string line 1\nstring line 2');

The Type, Literals & Operations

A variable of the type holds a value of either of . and are keywords in JavaScript.

As mentioned, JavaScript performs automatic type conversion if necessary. During the type conversion, the following 6 values are converted to :

  1. number
  2. number (Not-a-Number),
  3. empty string (, ),
  4. value,
  5. boolean ,
  6. (unallocated) object.

All the other values are converted to .

You need to memorize this: return if is one of these 6 values: , , , , , and .

Comparison Operators

The following relational operators, which produce a result, are defined in JavaScript. The results are obtained assuming , .

OperatorDescriptionExample (, )Result
==Equal To
(in Value)
num == 8 str == '8' num == str 8 == '8' true true true true
!=Not Equal To  
===Strictly Equal To
(in Type and Value)
num === 8 str === '8' num === str8 === '8' true true falsefalse
!==Strictly Not Equal To  
>Greater Than  
>=Greater Than or Equal To  
<Less Than  
<=Less Than or Equal To  

The strictly equality operator returns if both operands have the same type and same value; while returns if both operands have the same value, but may or may not be the same type.

JavaScript needs to provide two different equality operators, because it is loosely type and carries out automatic type conversion in many situation. For example,

  • When a number is compared with a string, the string is converted to a number (or if it does not contain a valid number). Hence, returns . But, returns , because the operands are not of the same type.
  • , , , can be applied to boolean (and all the JavaScript types), e.g., gives (because empty string is converted to ); but gives .
  • It is RECOMMENED to use (or ), instead of (or ), unless you are certain that type is not important.
String Sorting (Collation) Order

When two strings are compared, the encoding order (ASCII or Unicode table) is used. Hence, string is greater than string .

For example,

var x = 8; console.log(x == 8); console.log(x == '8'); console.log(x === 8); console.log(x === '8'); console.log(x < 10); console.log(x < '10'); console.log('8' < '10'); console.log('8' < '9'); console.log('Hello' < 'hi');
Logical Operators

The following boolean (or logical) operators are provided in JavaScript:

&&Logical AND  
||Logical OR  
!Logical NOT  
Short-Circuit Evaluation for Boolean Expressions

Evaluation of logical operations are always short-circuited. That is, the operation is terminated as soon as the result is certain, e.g., () is short-circuited to give , () gives , the will not be evaluated.

Explicit Type Conversion

The JavaScript runtime performs type conversion automatically. However, at times, you may need to convert from one type to another explicitly.

Converting a to a : Simply concatenate the with an empty , e.g., gives .

Converting a to a : Use built-in functions , or to convert a which contains a valid. For example, gives , gives , gives , gives , gives , but gives .

Converting a float to an integer: Use (e.g., gives ), or built-in mathematical functions such as , or .

Flow Control - Decision

JavaScript provides these flow control construct. The syntax is the same as Java/C/C++.

if (condition) {trueBlock; }if (day === 'sat' || day === 'sun') { alert('Super weekend!'); }
if (condition) {trueBlock; } else {falseBlock; }if (day === 'sat' || day === 'sun') { alert('Super weekend!'); } else { alert('It is a weekday...'); }
variable= (condition) ?trueValue :falseValue; if (condition) { variable = trueValue; } else { variable = falseValue; }var max = (a > b) ? a : b; var abs = (a >= 0) ? a : -a;
if (condition1) {block1; } elseif (condition2) {block2; } elseif (...) { ...... } else {elseBlock; }if (day === 'sat' || day === 'sun') { alert('Super weekend!'); } else if (day === 'fri') { alert("Thank God, it's Friday!"); } else { alert('It is a weekday...'); }
switch (expression) { casevalue1:statements; break; casevalue2:statements; break; ...... ...... default:statements; }switch (day) { case 'sat': case 'sun': alert('Super weekend!'); break; case 'mon': case 'tue': case 'wed': case 'thu': alert('It is a weekday...'); break; case 'fri': alert("Thank God, it's Friday"); break; default: alert("You are on earth?! Aren't you?"); }

Flow Control - Loops

JavaScript provides the following loop constructs. The syntax is the same as Java/C/C++.

while (test) {trueBlock; } var sum = 0, number = 1; while (number <= 100) { sum += number; }
do {trueBlock; } while (test); var sum = 0; number = 1; do { sum += number; }
for (initialization; test;post-processing) {trueBlock; } var sum = 0; for (var number = 1; number <= 100; number++) { sum += number; }
, and label

The following loop-control statements are provided (same syntax as Java/C/C++):

  • break - exit the innermost loop.
  • continue - abort the current iteration, and continue to the next iteration.
  • label: - provide an identifier for a statement, which can be used by and .

Try to avoid these statements, as they are hard to trace and maintain.


An array is an indexed collection. An array can be used to store a list of items (elements) under a single name with an integral index. You can reference individual element via the integral index in the form of . Furthermore, you can conveniently process all the elements of an array collectively via a loop.

Creating an Array via Array Initializer

You can create an array by assigning an array literal to a variable, known as Array Initializer, in the form of . For examples,

var weekdays = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"]; document.writeln(weekdays); console.log(weekdays); console.log(typeof weekdays); console.log(weekdays.length); var somethings = [1, 2.3, "abc", false]; console.log(somethings); console.log(somethings.length); var fruits = []; console.log(fruits); console.log(fruits.length); fruits[0] = "apple"; console.log(fruits); console.log(fruits.length); fruits[3] = "orange"; document.writeln(fruits); console.log(fruits); console.log(fruits.length); fruits.push('banana'); document.writeln(fruits); console.log(fruits); console.log(fruits.length); for (var i = 0; i < fruits.length; ++i) { console.log(i + ": " + fruits[i]); }for (var i in fruits) { console.log(i + ": " + fruits[i]); }for (var item of fruits) { console.log(item); }

Take note that JavaScript's array literal is enclosed in square bracket , instead of in Java/C/C++. JavaScript uses for object literal (to be discussed later).

You can also use an Array Initializer to create an array with missing indexes. For example,

var fruits = ['apple', , , 'orange']; console.log(fruits);
Accessing an Item

You can access individual element of an array via an integral index, in the form of . The index of the array begins at 0, and shall be a non-negative integer.


The length of the array is maintained in a variable called , which can be accessed via . In fact, the property returns the last integral index plus 1, as JavaScript's array index is 0-based. Nonetheless, you are allow to manipulate the . For example,

a = ['11', '22', '33']; console.log(a); console.log(a.length); a.length = 10; console.log(a); console.log(a.length);

Clearly, setting the does not affect the array elements.

Dynamic Array

Unlike Java/C/C++, the JavaScript array is dynamically allocated. You can add more elements to an array. You can also remove the content of an element using keyword . For examples,

var days = ["sun", "mon", "tue"]; console.log(days.length); console.log(days); days[5] = "fri"; console.log(days.length); console.log(days); delete days[1]; console.log(days.length); console.log(days); days.push("sat"); console.log(days.length); console.log(days); console.log(days.pop()); console.log(days.length); console.log(days); days.unshift("hi"); console.log(days.length); console.log(days); console.log(days.shift()); console.log(days.length); console.log(days); days[-9] = 'hello'; console.log(days.length); console.log(days);
Accessing All Items using for-loop with index

Array is usually processed collectively using a loop, e.g.,

var days = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']; for (var i = 1; i < days.length; ++i) { console.log(i + ": " + days[i]); }
The JavaScript's loop

JavaScript provides a special loop to process all the elements in an array. The syntax is as follows, where takes on the each of the index number of element which are not .

for (varindexinarrayName) { ... }

For example,

var months = ["jan", "feb"]; months[11] = "dec"; for (var i in months) { console.log(i + ": " + months[i]); }
The JavaScript's loop

JavaScript provides a special loop to process all the elements in an array. The syntax is as follows, where takes on the each of the element including the .

for (varitemofarrayName) { ... }
Add/Remove item(s)

You can:

  • Use to add one item to the end of an array.
  • Use to remove a particular index (set it to ).
  • Use to add one or more items to the end of an array. returns the resultant length of the array.
  • Use to add one or more items to the beginning of an array. returns the resultant length of the array.
  • Use to remove and return the last item of an array.
  • Use to remove and return the first item of an array.

For examples,

Add one item to the end using var a = [0, 'a', 'b']; a[a.length] = 3; console.log(a.length); console.log(a);
Add one or items to the end using .
returns the resultant length of the array.
var a = [0, 'a', 'b']; console.log(a.push(1, 'c')); console.log(a.length); console.log(a);
Add one or items to the beginning using .
returns the resultant length of the array.
var a = [0, 'a', 'b']; console.log(a.unshift(-2, -1, 'c')); console.log(a.length); console.log(a);
Remove and return the last item using var a = [0, 'a', 'b']; console.log(a.pop()); console.log(a.length); console.log(a);
Remove and return the first item using var a = [0, 'a', 'b']; console.log(a.shift()); console.log(a.length); console.log(a);
Array's Properties and Operations

The object has these commonly-used properties:

  • .length: the number of items including s. In fact, is set to the last index plus 1.

It has these commonly-used methods:

  • .join([separator]): join the elements of an array together into a single string, separated by the (defaulted to ). For example, var fruits = ["apple", "orange", "banana"]; console.log(fruits.join()); console.log(fruits.join("|"));
  • aString.split([separator, limit]): Reverse of . Take a string and split into an array based on the . For example, var str = 'apple, orange, banana'; var fruits = str.split(); console.log(fruits); str = 'apple|*|orange|*|banana'; fruits = str.split(); console.log(fruits); fruits = str.split('|*|'); console.log(fruits); fruits = str.split('*'); console.log(fruits);
  • .concat(value1, value2, ..., valueN): returns a new array composing of this array and the given arrays or values. For example, var fruits = ['apple', 'orange']; moreFruits = fruits.concat('banana', 'watermelon'); console.log(moreFruits); console.log(fruits);
  • .reverse(): reverses the order of elements in the array, the first becomes last. For example, var a = ["1", "2", "3", "4", "5"]; a.reverse(); console.log(a);
  • .sort(): sorts the elements in the array. For example, var a = ["8", "10", "a", "b"]; a.sort(); console.log(a); a = [8, 20, 5, 100]; a.sort(); console.log(a); Take note take, by default, number are also sorted based on ASCII (Unicode) order. To sort numbers numerically, you can supply a callback comparison function. The function shall take 2 arguments, say and , and return a negative number if ; a positive number if ; and 0 if var a = [8, 20, 5, 100]; a.sort( function(a, b) { return a - b; } ); console.log(a);
  • .slice(beginIndex, endIndex): extracts and returns a section of an array from (inclusive) to (exclusive). For example, var a = ["a", "b", "c", "d", "e"]; console.log(a.slice(1, 4)); console.log(a);
  • .splice(startIndex, countToRemove, insertItem1, insertItem2, ...): removes elements from an array, and insert elements at its place. For example, var a = ["1", "2", "3", "4", "5"]; a.splice(2, 2, "a", "b", "c", "d"); console.log(a); console.log(a.length);
  • .indexOf(searchItem[, startIndex]) and .lastIndexOf(searchItem[, startIndex]): search for the index of the item forward or backward. It returns -1 if item cannot be found. For example, var a = ['a', 'b', 'c', 'a', 'b', 'c']; var searchItem = 'b'; var idx = a.indexOf(searchItem) console.log(idx); idx = a.indexOf(searchItem, idx + 1) console.log(idx); idx = a.indexOf(searchItem, idx + 1) console.log(idx); console.log(a.lastIndexOf('a')); console.log(a.lastIndexOf('a', 2));
  • .push(): adds one or more elements to the end of an array and returns the resultant length of the array.
  • .pop(): removes and return the last element from an array.
  • .shift(): removes and returns the first element from an array.
  • .unshift(): adds one or more elements to the front of an array and returns the resultant length of the array.

Arrays also support these iterative methods that iterate through each item of the array:

  • .forEach(callback): takes a function with an argument which iterates through all the items in the array. var fruits = ['apple', 'orange', 'banana']; fruits.forEach( function(item) { console.log('processing item: ' + item); }); NOTE: Using or or simple loop is probably more conventional.
  • .map(callback): return a new array, which contains all the return value from executing on each item. For example, var fruits = ['apple', 'orange', 'banana']; var results = function(item) { console.log('processing item: ' + item); return item.toUpperCase(); }); console.log(results);
  • .filter(callback): return a new array, containing the items for which returned . For example, var fruits = ['apple', 'orange', 'banana']; var result = fruits.filter( function(item) { console.log('processing item: ' + item); return /.*e$/.test(item); }); console.log(result);
  • .every(callback): return if returns for ALL items.
  • .some(callback): return if returns for at least one item in the array.

For detailed specification and examples about a built-in object, check "Core JavaScript References".

Associative Array

An associative array is an array of key-value pair. Instead of using numbers 0, 1, 2,... as keys as in the regular array, you can use anything (such as string) as key in an associative array. Associative arrays are used extensively in JavaScript and jQuery.

JavaScript does not support native associative array (it actually does not support native array too). In JavaScript, associative arrays (and arrays) are implemented as objects (to be elaborate later).

You can create an associative array via the Object Initializer. For example,

var aStudent = { name: 'peter', id: 8888, isMarried: false }; aStudent['age'] = 24; for (key in aStudent) { console.log(key + ": " + aStudent[key]); } console.log(typeof aStudent); aStudent.height = 190; console.log(aStudent.height);

Take note that Array initializer uses square brackets ; while object initializer (for associative array) uses curly brackets .


Functions are useful:

  • when you have to use the same codes several times.
  • as the JavaScript event handler.
  • make your program easier to read and understood.

A function accepts zero or more arguments from the caller, performs the operations defined in the body, and returns zero or a single result to the caller.

The syntax for user-defined function is:

functionfunctionName(argument1, argument2, ...) {statements; ...... returnaValue;}

Functions are declared using the keyword . You do not have to specify the return-type and the types of the arguments because JavaScript is loosely typed. You can use a statement to return a single piece of result to the caller anywhere inside the function body. If no statement is used (or a with no value), JavaScript returns . Functions are generally defined in the section, so that it is always loaded before being invoked.

To invoke a function:

functionName(argument1, argument2, ...)


<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Function Demo</title> <script> function add(item1, item2) { return Number(item1) + Number(item2); } </script> </head> <body> <script> var number1 = prompt('Enter the first integer:'); var number2 = prompt('Enter the second integer:'); alert('The sum is ' + add(number1, number2)); </script> </body> </html>

Function has access to an additional variable called inside its body, which is an array containing all the arguments. For example,

<!DOCTYPE html>

0 thoughts on “Invalid Left-Hand Side In Assignment Jquery Download”


Leave a Comment

Your email address will not be published. Required fields are marked *