Javascript is a language often used within html documents to trigger interactive features.

Since its release in December 4, 1995 (six months after Java, which was released in May 23, 1995), JavaScript has gone through many changes. JavaScript began as a client-side programming language (which runs inside a web browser via a built-in JavaScript engine) for adding interactive contents to the web pages. It became more robust with DHTML (1997) and Ajax (1999). With Node.js (released in May 27, 2009), JavaScript can be used to program server-side and build full-stack web applications. In 2015, the ECMAScript 6 (ES6) introduces major update to the language.

Introduction

It began as a Client-side Programming Language run inside a web browser via a Built-in JavaScript Engine

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 - that can be used to update one part of the web page asynchronously), which generate renew interest in JavaScript.

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

JavaScript is Now Everywhere with Node.js

JavaScript has grown beyond the client-side programming. With the introduction of Node.js in 2009 (an open-source, cross-platform JavaScript run-time environment), you can run your JavaScript standalone or inside the server (instead of a browser). This allows you to use one single language for both the server-side and client-side programming.

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" @ http://www.ecma-international.org/publications/standards/Ecma-262.htm (also approved as "ISO/IEC 16262"):

  • ECMA-262 version 1 (June 1997): First edition
  • ECMA-262 version 2 (August 1998)
  • ECMA-262 version 3 (December 1999): Added regular expressions, try/catch, switch, do-while, etc.
  • ECMA-262 version 4 - Abandon due to political differences. In 2007, the TC-39 (the committee responsible for ECMAScript) put up a draft specification for ECMAScript 4, which was massive in scope and introduced many new syntax and features. But a group of developers from Yahoo, Google and Microsoft felt that was too much and created an alternate proposal called ECMAScript 3.1. ECMAScript 4 was never finalized.
  • ECMA-262 version 5 and 5.1 (June 2011): ECMAScript 3.1 was eventually standardized as ECMAScript 5. Added "strict mode", JSON, Array iteration methods, etc.
  • ECMA-262 2015: most popularly known as ECMAScript 6 or ES6.
    This version added significant new syntax for writing complex application, including class declaration, let for local declarations, const for constant local declaration, default parameter values, iterators and for...of loops, Python-style generators, arrow function expression (() => {...}), binary data, typed arrays, new collections (maps, sets and WeakMap), promises, reflection, proxies, template literals for strings, and many more.
  • ECMAScript 2016 (ES7): Since ES6, ECMAScript standards are on yearly release cycles in June.
    This version added exponential operator (**), block-scoping of variables and functions, await and async keywords for asynchronous programming, etc.
  • ECMAScript 2017 (ES8): Added string padding, async functions which use generators and promises, Object.values, Object.entries for easy object manipulation, etc.
  • ECMAScript 2018 (ES9): Added rest parameters (...), spread operator, asynchronous iteration, additions to regular expression.
  • ECMAScript 2019 (ES10): Added Array.prototype.flat, Array.prototype.flatMap, changes Array.sort and Object.fromEntries, catch binding becomes optional, etc.
  • ECMAScript 2020 (ES11): introduces a BigInt primitive type for arbitrary-size integers, the nullish coalescing operator (??) and the gloablThis object.
  • ECMAScript 2021 (ES12): Added enhancement to strings (replaceAll), promises (Promise.any), and object references. Logical assignment operators (??=, &&=,||=,)
JavaScript vs. Java

Java is a full-fledged general-purpose programming language. It was created by James Gosling at Sun Microsystems (now part of Oracle) and released in August 1995.

JavaScript was created by Brendan Eich at Netscape, also in 1995. Originally called LiveScript, it was a small and lightweight special-purpose language for writing client-side program running inside a browser to create active user-interface and generate dynamic web pages. It was renamed to JavaScript in an ill-fated marketing decision to try to capitalize on the popularity of Java language, when Netscape released its Navigator 2 in 1996.

Java and JavaScript are totally different languages for different programming purposes. However, in the early days, some efforts were made to adopt Java syntax and convention into JavaScript, such that JavaScript seems to be a subset of Java. In reality, they have very little in common.

What Client-side 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.
jQuery

jQuery is a popular cross-browser JavaScript Library. 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".

Standalone and Server-side JavaScripts with Node.js JavaScript Engine

[TODO]

JavaScript Source-Code Editors and IDEs

You need a text editor to write your JavaScript. You could use a plain-text editor such as Windows' NotePad or macOS's TextEdit (strictly NOT recommended as they can't do syntax highlighting). To improve your productivity, a good source-code editor (which provides syntax highlighting, auto-code-complete, snippets, documentation, symbol navigation, refactoring, etc.) is essential. There are many freeware/shareware available, such as Visual Studio Code (VS Code), Sublime Text, Atom, Brackets, Komodo Edit, Emacs, Vim, BBEdit, TextMate, NotePad++ (Windows), etc. You can also use a full-scale IDE such as Eclipse, NetBeans, IntelliJ IDEA. There are also many "online" editors and compilers available (e.g., Programiz, JSFiddle, Playcode), but I think that you should install your own.

Client-Side 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 (computational thinking) such as variables, if-else and for-loop constructs.

Client-side JavaScripts run inside a browser via a built-in JavaScript engine. There are standards on JavaScript. But the Big-5 (Chrome, Firefox, IE/Edge, 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.

JavaScript also run standalone (and in the server). To run JavaScript standalone, you need to install Node.js, which is a JavaScript engine. I will present the examples in the next section.

Client-side JS EG 1: Functions alert() and document.write()

Let us write our first client-side 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 rose is NOT a ROSE and is NOT a Rose.
  • "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 "JSExAlertWrite.html" (or any filename that you prefer, with file extension of ".html" or ".htm"). Run the script by loading the HTML file into a JavaScript-capable browser (e.g., One of the BIG FIVE - Chrome, Firefox, Internet Explorer/Edge, Safari or Opera).

JavaScript Example: Functions alert() and document.write()

My first JavaScript says:

How it Works?
  1. JavaScripts are programming codes that are embedded inside an HTML document. The codes are contained between a pair of tags, as follows: NOTE: In HTML4/XHTML, you need to include attribute type="text/JavaScript" to the elements. Lines 7-9 and Line 13-17 are two pieces of JavaScripts, placed in the HEAD and BODY sections, respectively.
  2. JavaScript statements are terminated by a semicolon ';' (like Java/C/C++/C#).
  3. The alert(str) function (Line 8) pops out a dialog box displaying the str and a OK button. Strings are enclosed by a pair of double quotes or single quotes, e.g., "hello" or 'hello'.
  4. The current web page is represented by the so-called document object in the JavaScript. The document.lastModified (Line 16) property stores the last modified date of the current document. The document.write(str) function (Line 14 to 16) can be used to write the specified str to the current document, as part of the current HTML document.
  5. The '+' operator (Line 16) can be used to concatenates two strings (like Java).
  6. As a result of the document.write(), the BODY section of this document contains:

    My First JavaScript says

    Hello world, again!

    This document was last modified on mm/dd/yyyy hh:mm:ss.

  7. The alert(str) and document.write(str) are some of the commonly-used built-in functions provided in JavaScript.

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

Don't Get Caught by the Cache - Do Control-Refresh (or Control-F5)

If you modify the codes and reload the web page, the new codes may not get executed because the browser caches the previously loaded version. You could use Control-F5 (Control-Refresh) to ask the browser to discard the cache, and fetch a new page.

Client-Side JS EG 2: Variables and Functions prompt(), confirm()

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 alert(str) function puts the str on a pop-up box with a OK button. User needs to click the OK button to continue.
  2. The prompt(promptingStr, defaultStr?) function puts up an input pop-up box with the promptingStr with an OK and Cancel buttons. It returns the input entered by the user as a string; or a special value called null if the user hits the Cancel button. The optional parameter defaultStr specifies the initial string to be shown. In this article, I shall indicate optional function parameters with a trailing '?' for compactness.
  3. The confirm(str) function puts str on a pop-up box with OK and Cancel buttons. It returns true if user hits the OK button; or false otherwise.
JavaScript Example: Variables and functions prompt() and confirm()

Welcome to JavaScript!

How it Works?
  1. Line 8 declares a global variable called username, via the keyword var. 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 prompt(promptingStr, defaultStr?) function to pop out a dialog box, and reads in the string entered by the user. The string read is assigned to the variable username. The function prompt() is similar to the alert(), but it accepts a user's input.
  3. In Line 10, the confirm(str) function puts up the message and returns either true or false, depending on whether the user hits the OK or Cancel button.
  4. If the result is true, Line 11 prints "Hello, username!". Otherwise, Line 13 prints "Hello, world!".

TRY: Instead of printing the greeting message using document.write(), do it via an alert().

Client-Side JS EG 3: The Date Object

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

JavaScript Example: The Date object
How it Works?
  • Line 8 declares a variable called now. It also creates a Date object (via the new operator), which contains the current date-time stamp, and assign it to now.
  • "//" 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 hrs. It also invokes the function getHours() on object now, in the form of now.getHours(), to retrieve the hour part of object now, and assign it to variable hrs. Lines 9 and 10, similarly, handle the minutes and seconds.
  • Line 12 to 14 use document.writeln() to write to the current document. writeln() (write-line) writes a newline (\n) 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 hrs, one of the messages will be displayed.
TRY:
  1. Modify the above script to print the current date, month, year and day of the week. (Hints: Use functions getDate(), getMonth(), getFullYear() and getDay() of a Date object. getDate() returns 1-31. getMonth() returns 0 to 11 for January to December. getFullYear() returns a 4-digit year. getDay() 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 if-elseif-elseif...else construct as follow.) if ( condition-1 ) { block-1 ; } else if ( condition-2 ) { block-2 ; } else if ( condition-3 ) { block-3 ; ...... ...... } else { block-n ; }

Client-Side JS EG 4: Loops

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

JavaScript Example: Loop

Testing Loop

How it Works?
  • Line 11 prompts the user for a number, and assigns it to the variable multiplier.
  • Lines 12-14 contain a for-loop. A for-loop takes the following syntax: for ( initialization ; test ; post-processing ) { body ; }
    Javascript is a language often used within html documents to trigger interactive features.

    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 number is initialized to 1. If number is less than or equal to 100, the body of the loop executes, followed by the post-processing statement, which increment the value of number by 1. The loop repeats until the value of number is NOT less than or equal to 100 (i.e., more than 100).

TRY:
  1. Modify the above script to prompt the user for the multiplier as well as the number of multiples to be printed (in two prompt() 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., x % 2 computes the remainder of x divides by 2, which results in either 0 or 1.)

Client-Side JS EG 5: User-defined Functions and onclick Event Handler

Besides the JavaScript built-in functions such as alert(), prompt(), write(), and writeln(), 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.

JavaScript Example: User-defined function and onclick Event Handler

Example on event and user-defined function

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

TRY: Include another button, which opens "JSExVar.html".

Client-Side JS EG 6: More Event Handlers: onload, onmouseover and onmouseout

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

  • onload: fires after browser loaded the page.
  • onmouseover and onmouseout: fires when the user points the mouse pointer at/away from the HTML element.
JavaScript Example: Events onload, onmouseover and onmouseout

"Hello" alert Box appears after the page is loaded.

Point your mouse pointer here!!!

Dissecting the Program
  • Line 8 defines a variable msgLoad, which holds the strings to be displayed in the onload event handlers.
  • In the opening tag (Line 12), we define the onload event handler for the load event. It invokes alert() with the message defined earlier.
  • Line 13 and 14 defines the event handlers onmouseover and onmouseout 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 color to red), and revert back to its original color when the mouse pointer is moved away (by resetting the CSS style property color to an empty string). The special keyword this refer to this object.

Client-Side JS EG 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.

JavaScript Example: Separating HTML, CSS and JavaScript

"Hello" alert Box appears after the page is loaded.

Point your mouse pointer here!!!

/* JSExFiles.css */ @CHARSET "UTF-8"; .highlight { color: red; }// JSExFiles.js window.onload = function() { init(); alert("Hello!"); } function init() { document.getElementById("magic").onmouseover = function() { this.className = "highlight"; } document.getElementById("magic").onmouseout = function() { this.className = ""; } }
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. 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 type="text/css" in the opening tag.

    2. Also, the JavaScript programming code is kept in an external file, referenced via the above is needed, although there is no content.
      Note: In HTML4/XHTML1.0, you need to include attribute type="text/JavaScript" in the // JSExInnerHtml.js window.onload = init; function init() { document.getElementById("btn1").onclick = changeHeading1; document.getElementById("btn2").onclick = changeHeading2; document.getElementById("btn3").onclick = changeParagraph; } function changeHeading1() { var elm = document.getElementById("heading1"); // One element elm.innerHTML = "Hello"; } function changeHeading2() { var elms = document.getElementsByTagName("h2"); // Array of elements for (var i = 0; i < elms.length; i++) { elms[i].innerHTML = "Hello again!"; } } function changeParagraph() { var elms = document.getElementsByClassName("para"); // Array of elements for (var i = 0; i < elms.length; i++) { elms[i].innerHTML = "Hello again and again!"; } }
      How it works?
      1. This HTML document contains a

        element with an unique id="heading1" (Line 10), two

        elements (Line 11-12), three

        elements with class="para" (Line 13-15), and three with unique id (Line 16-18).

      2. In the user-defined function changeHeading1(), we use document.getElementById("heading1") to select the

        element, and then modify its innerHTML property.

      3. In changeHeading2() function, we use document.getElementsByTagName("h2") to select all the

        elements in an array elms. We then use a for-loop to iterate through all the elements in the array. The elms.length property keeps the length of the array.

      4. In changeParagraph() function, we use document.getElementsByClassName("para") 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 init(), which is assigned as the onload handler via window.onload=init. That is, init() will be triggered after the page is loaded. The init() function assigns onclick event handlers to the buttons, selected via document.getElementById() using the unique buttons' id.

      TRY: [TODO]

      Client-Side JS EG 9: Intercepting a Hyperlink

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

      JavaScript Example: Intercept an Hyperlink JavaScript Example 1 // JSExLink.js window.onload = init; function init() { document.getElementById("myLink").onclick = showWarning; } function showWarning() { return confirm("Warning! Proceed with care!"); }
      How it works?
      1. The HTML page has an hyperlink with an unique id.
      2. The init() function assigns an onclick handler to the hyperlink, selected via document.getElementById().
      3. When the hyperlink is clicked, the onclick handler showWarning() triggered. If confirm() returns true, the new page will be loaded; otherwise, the current page remains.

      TRY: [TODO]

      More Advanced JavaScript Examples

      More "Advanced JavaScript Examples".

      Debugging JavaScripts

      A graphic debugger is a MUST in programming. Programming in JavaScript, in particular, requires a good 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 alert() 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 Web Developer Tools

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

      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.
      3. DOM: View the HTML DOM of the current document.
      4. HTML and CSS.

      To debug JavaScript:

      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).
      The console.log()

      Instead of using alert() and document.write() to show the intermediate results, you can also use console.log(message[, element]), which writes the message and the value of the element 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.

      // JSExInnerHtmlDebug.js window.onload = init; function init() { document.getElementById("btn1").onclick = changeHeading1; document.getElementById("btn2").onclick = changeHeading2; document.getElementById("btn3").onclick = changeParagraph; } function changeHeading1() { var elm = document.getElementById("heading1"); // One element console.log(elm.innerHTML); // Print current value before modification elm.innerHTML = "Hello"; } function changeHeading2() { var elms = document.getElementsByTagName("h2"); // Array of elements for (var i = 0; i < elms.length; i++) { console.log(elms[i].innerHTML); elms[i].innerHTML = "Hello again!"; } } function changeParagraph() { var elms = document.getElementsByClassName("para"); // Array of elements for (var i = 0; i < elms.length; i++) { console.log(elms[i].innerHTML); elms[i].innerHTML = "Hello again and again!"; } }

      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 (onclick) or loaded a page (onload).

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

      1. between container tags; and
      2. inside the HTML tags as the event handlers (such as onclick, onmouseover, onload), e.g., onclick="JavaScriptStatements".
      The element contains the JavaScript programming statements. For example,

      In HTML4/XHTML1.0, you need to include the attribute type="text/javascript" in the

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

      In HTML4/XHTML1.0, you need to include type="text/javascript" in the tags, and run it under a web browser, you will need to activate the debugger (Web Developer Tools) to see the outputs. See the above section on client-side examples.

    3. Standalone JS Eg 2: [TODO]

      [TODO] Check Limitations such as File IO, Networking etc. Compare with Shell Script and Python script for automation.

      Server-Side JavaScript by Examples

      You can also use JavaScript to program a server-side webapp, just like Java Servlet/JSP, Microsoft ASP, PHP, Python, etc. The appeal is that you can use one single language to program both the client-side and the server-side in a webapp.

      See Node.js article.

      JavaScript Basic Syntax

      Comments

      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:

      Whitespaces (blank, tab, newline)

      Like C/C++/Java, JavaScript ignores additional whitespaces (blanks, tabs, and newlines). I strongly recommend that you use additional whitespaces to format your program to make your code easier to read and understand.

      Expressions

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

      Statements, Semicolon and Blocks

      A statement is a single programming instruction. Unlike C/C++/Java, where you need to end a statement with a semicolon (;), in JavaScript the semicolon is optional. However, if semicolon is missing, you need to end the statement with a newline (and JavaScript engine will insert a semicolon for you).

      Semicolons in JavaScript divide the community. Some prefer to use them always, no matter what. Others like to avoid them for brevity. I shall leave it to you.

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

      Variables, Literals & Types

      Variable declarations (var, let, const) and Assignment Operator (=)

      A variable is a named storage location that holds a value. Prior to ES6, you can only declare a variable using keyword var. ES6 introduces two new keywords: let to declare a local block-scope variable, and const to declare a local block-scope constant; and leave var to declare a global variable. I shall discuss variable scope in the later section.

      You can assign (and re-assign) a value to a variable using the assignment (=) operator. For example,

      const magic = 88; for (let i = 0; i < 5; ++i) { console.log(i); } var font_size = 12;

      It is strongly recommended to use const-declaration if the value doesn't change (this ensure that it will not accidentally change); and let-declaration for local variable (variables shall not live beyond where they are needed). Use var-declaration only for global variable.

      Identifiers

      Identifiers are names given to identify entities (such as variables and functions). The rules for valid identifiers are:

      • An identifier can contain letters (a-z, A-Z), digits (0-9), underscore (_) and dollar sign ($). But it cannot begin with a digit (0-9).
      • Identifiers are case-sensitive. A rose is NOT a Rose, and is NOT a ROSE.
      • Identifiers cannot be keywords.
      • Take note that hyphen (-) and space are NOT allowed. Hence, font-size, roman new, are NOT valid identifiers. You should use underscore (_) instead of hyphen (-).
      Literals

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

      Types

      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., "Hello", 'world').
      2. number: takes both integer (e.g., 5566) or floating-point (e.g., 3.14159265).
      3. boolean: takes boolean literal of either true or false (in lowercase).
      4. undefined: takes a special literal value called undefined. Take note that undefined 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. Unlike Java, function is a first class object in JavaScript, e.g., you can assign a function to a variable.
      3. null: A special literal value for unallocated (unconstructed) object.

      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 int and float) during declaration. The type is decided when a value is assigned to that variable. If a number is assigned, the variable takes on the number type and can perform numeric operations such as addition and subtraction. If a string is assigned, the variable takes on the string type and can perform string operations such as string concatenation. In other words, the type is associated with the value, instead of the variable.

      Operator typeof

      You can use the operator typeof to check the type of the current value assigned to a variable.

      The undefined Type and undefined Literal Value

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

      When a variable is declared (via var keyword) without assigning an initial value, it takes on the type undefined and holds a special value called undefined (uninitialized 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. In other words, type is associated with the value, not the variable. Types are converted automatically as needed during execution (known as dynamically-typed).

      For examples,

      console.log('type: ' + typeof v99); //type: undefined console.log('value:' + v99); //ReferenceError: v99 is not definedvar v1; console.log('type:' + typeof v1); //type:undefined console.log('value:' + v1); //value:undefined v1 = 'abc'; console.log('type:' + typeof v1); //type:string console.log('value:' + v1); //value:abc v1 = '123'; console.log('type:' + typeof v1); //type:string console.log('value:' + v1); //value: 123 v1 = 123; console.log('type:' + typeof v1); //type:number console.log('value:' + v1); //value:123 v1 = 55.66; console.log('type:' + typeof v1); //type:number console.log('value:' + v1); //value:55.66 v1 = false; console.log('type:' + typeof v1) //type:boolean console.log('value:' + v1); //value:false v1 = null; console.log('type:' + typeof v1); //type:object console.log('value:' + v1); //value:null v1 = { name:'peter', age:21 }; console.log('type:' + typeof v1); //type:object console.log('value:' + v1); //value:[object Object] console.log('value:' + v1.name); //value:peter console.log('value:' + v1.age); //value:21 v1 = new Date(); console.log('type:' + typeof v1); //type:object console.log('value:' + v1); //value:Thu Jun 02 2022 13:28:29 GMT+0800 (SGT) v1 = function () { return 'hello'; }; console.log('type:' + typeof v1); //type:function console.log('value:' + v1); //value:function () { // return 'hello'; //}
      (ES6) Constants const-declaration

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

      const SIZE = 9;

      The number Type, Literals & Operations

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

      Integer literals can be expressed in:

      • Decimal: begins with a digit 1 to 9 (not 0), e.g., 123 or -456,
      • Octal: begins with a digit 0, e.g., 0123 or -0456,
      • Hexadecimal: begins with 0x (or 0X), e.g., 0xA1B2 or -0XA1B2.
      • Binary: begins with 0b (or 0B), e.g., 0b10011100 or -0B11001100. [Binary may not be supported in some browsers.]

      Floating-point literals can be expressed in the usual form (e.g., 3.1416) or scientific notation, e.g., -1.23e4, 4.56E-7.

      JavaScript also provides some special number literals:

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

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

      OperatorDescriptionExampleResult (x=5, y=2)
      + Addition z = x + y; z is 7
      - Subtraction (or Unary Negation) z = x - y; z is 3
      * Multiplication z = x * y; z is 10
      / Division z = x / y; z is 2.5
      % Modulus (Division Remainder) z = x % y; z is 1
      ++ Unary Pre- or Post-Increment y = 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-Decrement y = --x; z = x--;
      Same as: x = x-1; y = x; z = x; x = x-1;
      y is 4; z is 4; x is 3
      ** Exponent
      (ES7)
      y ** x  

      In JavaScript, arithmetic operations are always performed in double-precision floating-points (NOT integers). That is, 1/2 gives 0.5 (instead of 0 in Java/C/C++). You may use the built-in function parseInt() to truncate a floating-point value to an integer, e.g., parseInt(55.66) and parseInt("55.66") gives 55. You may also use the built-in mathematical functions such as Math.round(), Math.floor(), Math.ceil() for converting a floating-point number to an integer.

      Exponent Operator (**)

      ECMAScript 2016 (ES7) introduces exponent operator (**), you can write a**n, e.g., 2**5.

      Before ES7, you have to use built-in function Math.pow(base, exponent).

      Arithmetic cum Assignment Operators

      These are short-hand operators to combine two operations.

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

      The string Type, Literals & Operations

      A string is a sequence of characters enclosed within a pair of single quotes or double quotes (e.g., "Hello", 'world', "5566", '3.1416'). You can use an escape sequence to represent special non-printable characters (such as \n for new-line, \t for tab, and \uhhhh 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 string. This is handy as you can use single quotes if the string contains double quotes (e.g., '

      '), without using the clumsy escape sequences (e.g., "
      ").

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

      console.log('55' - '66'); //-11 (number)(subtraction) console.log('55' * 2); //110 (number)(multiplication) console.log('Hello' - 1); //NaN (subtraction failed)
      The '+' Operator: Addition or Concatenation?

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

      console.log(11 + 22); //33 (number)(usual addition) console.log('11' + '22'); //1122 (string)(concatenation) console.log('11' + 22); //1122 (string)(concatenation) console.log('Hello' + 22); //Hello22 (string)(concatenation)
      string/number conversion: parseInt(), parseFloat() and Number()

      To convert a numeric string to a number, you could use the built-in functions parseInt() or parseFloat(), which returns a number if conversion is successful; or NaN otherwise. For example,

      var magic = "11"; console.log(magic + 22); //1122 (string)(concatenation) console.log(parseInt(magic) + 22); //33 (number)(addition) console.log(parseInt(magic) + "22"); //1122 (string)(concatenation) console.log(parseInt(magic) + parseFloat("22.33")); //33.33 (number)(addition) console.log(parseInt("abc")); //NaN

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

      console.log(parseInt("10px")); //10 (number)

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

      var magic = "8888" console.log(magic + 8); //88888 (string)(concatenation) console.log(Number(magic) + 8); //8896 (number)(addition) var d = new Date(2015, 5, 1, 12, 34, 56); console.log(d); //2015-06-01T04:34:56.000Z console.log(Number(d)); //1433133296000
      String's Properties
      • .length: E.g., str.length returns the length of the string.
      String's Operations
      • .toUpperCase(): returns the uppercase string.
      • .toLowerCase(): returns the lowercase string.
      • .charAt(idx): returns the character at the idx position. Index begins from 0. Negative index can be used, which counts from the end of the string.
      • .substring(beginIdx, endIdx): returns the substring from beginIdx (inclusive) to endIdx (exclusive).
      • .substr(beginIdx, length): returns the substring from beginIdx of length.
      • .indexOf(searchStr, fromIdx?): Return the beginning index of the first occurrence of searchStr, starting from an optional fromIdx (default of 0); or -1 if not found.
      • .lastIndexOf(searchStr, fromIdx?): Return the beginning index of the last occurrence of searchStr, starting from an optional fromIdx (default of string.length); or -1 if not found.
      • .slice(beginIdx, endIdx): Return the substring from beginIdx (inclusive) to endIdx (exclusive).
      • .split(delimiter): returns an array by splitting the string using delimiter.
      • Searching/Modifying Strings using Regular Expression: See "Regular Expression".

      (ES6) Multi-line Template String and Substitution

      Prior to ES6, You can enclosed a string literal using either single or double quotes (e.g., "Hello", 'world', "5566", '3.1416'). Escape sequences are to be used for special characters (e.g., \n for new-line, \t for tab) and resolving conflict (e.g., \", \', \\). Multi-line strings are not supported.

      ES6 introduces template string, delimited by back-quotes, for example,

      let msg = `hello, world` console.log(msg) //hello, world console.log(msg.length) //12

      There is no need to escape single or double quote inside a template string. But you need to use escape sequence for back-quote, i.e., \`.

      Template strings support multi-line strings. All whitespaces (blank, tab, newline) within the back-quotes are part of the multi-line string. For example,

      let multilineMsg = `hello, world` console.log(multilineMsg) /hello, // world console.log(multilineMsg.length) //13

      Template strings support substitution, which allow you to embed any valid JavaScript expression as part of the string in the form of ${expr}, for example,

      let name = 'Peter', greeting = 'hello', helloMsg = `${greeting}, ${name}` console.log(helloMsg) //hello, Peter

      Multi-line template string with substitution provides a more convenient way to write out formatted HTML fragment. For example,

      document.body.innnerHTML = `

      ${title}

      ${article.title}

      ${article.body}

      copyright ${new Date().getYear()}

      `

      The boolean Type, Literals & Operations

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

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

      1. number 0
      2. number NaN (Not-a-Number),
      3. empty string ("", ''),
      4. undefined value,
      5. boolean false,
      6. null (unallocated) object.

      All the other values are converted to true.

      You need to memorize this: !value return true if value is one of these 6 values: 0, NaN, "", undefined, false, and null.

      Comparison (Relational) Operators

      The following relational operators, which produce a boolean result, are defined in JavaScript. The results are obtained assuming num=8, str='8'.

      OperatorDescriptionExampleResult
      (num=8, str='8')
      == 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 === str 8 === '8' true true false false
      !== Strictly Not Equal To    
      > Greater Than    
      >= Greater Than or Equal To    
      < Less Than    
      <= Less Than or Equal To    
      === vs. ==

      The strictly equality operator === returns true if both operands have the same type and same value; while == returns true 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 NaN if it does not contain a valid number). Hence, (8 == "8") returns true. But, (8 === "8") returns false, because the operands are not of the same type.
      • ===, !==, ==, != can be applied to boolean (and all the JavaScript types), e.g., ("" == false) gives true (because empty string is converted to false); but ("" === false) gives true.
      • 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/Unicode table) is used. Hence, string "8" is greater than string "10".

      For example,

      var x = 8; console.log(x == 8); //true (same value) console.log(x == '8'); //true (string converted to number) console.log(x === 8); //true (same type and value) console.log(x === '8'); //false (different type) console.log(x < 10) //true console.log(x < '10'); //true (string converted to number) console.log('8' < '10'); //false (comparing two strings alphabetically) console.log('8' < '9'); //true (comparing two strings, not numbers) console.log('Hello' < 'hi'); //true (comparing two strings)
      Logical (Boolean) Operators

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

      OperatorDescriptionExampleResult
      && Logical AND    
      || Logical OR    
      ! Logical NOT    
      &&= Logical AND cum assignment (ES12)    
      ||= Logical OR cum assignment (ES12)    

      Notes: ^ in JavaScript is a bitwise XOR operator, not really boolean XOR (which is rarely needed).

      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., (false && ...) is short-circuited to give false, (true || ...) gives true, 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 number to a string: Simply concatenate the number with an empty string "", e.g., "" + 5 gives "5".

      Converting a string to a number: Use built-in functions parseInt(str), parseFloat(str) or Number(str) to convert a str which contains a valid number. For example, parseInt("55") gives 55, parseInt(55.66) gives 55, parseInt("55.66") gives 55, parseFloat("55.66") gives 55.66, parseInt("55px") gives 55, but parseInt("Hello") gives NaN.

      Converting a float to an integer: Use parseInt() (e.g., parseInt(55.66) gives 55), or built-in mathematical functions such as Math.round(), Math.ceil() or Math.floor().

      Flow Control - Decision (Conditional)

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

      SyntaxExample
      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; Same as: if (condition) { variable = trueValue; } else { variable = falseValue; } var max = (a > b) ? a : b; var abs = (a >= 0) ? a : -a; console.log(i === 0 ? 'zero' : 'not zero');
      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) { case value1: statements; break; case value2: 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?"); }
      [ES12] Logical Nullish Assignment Operator (??=)

      The logical nullish assignmebnt (x ??= y) assigns only if x is null or undefined (i.e. nullish). For example,

      let msg; msg ??= "hello"; console.log(msg); //hello msg ??= "world"; console.log(msg); //hello

      Flow Control - Loops (Repetition)

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

      SyntaxExample
      while (test) { trueBlock; } // Sum from 1 to 100 var sum = 0, number = 1; while (number <= 100) { sum += number; }
      do { trueBlock; } while (test); // Sum from 1 to 100 var sum = 0; number = 1; do { sum += number; }
      for (initialization; test; post-processing) { trueBlock; } // Sum from 1 to 100 var sum = 0; for (var number = 1; number <= 100; number++) { sum += number; }
      break, continue 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 break label and continue label.

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

      Arrays

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

      Creating an Array via "Array Initializer [value1, value2, ...]"

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

      var weekdays = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"]; console.log(weekdays); //[ 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat' ] console.log(typeof weekdays); //object console.log(weekdays.length); //7 var somethings = [1, 2.3, "abc", false]; console.log(somethings); //[ 1, 2.3, 'abc', false ] console.log(somethings.length); //4 var fruits = []; // begins with an empty array console.log(fruits); //[] console.log(fruits.length); //0 fruits[0] = "apple"; console.log(fruits); //[ 'apple' ] console.log(fruits.length); //1 fruits[3] = "orange"; console.log(fruits); //[ 'apple', <2 empty items>, 'orange' ] console.log(fruits.length); //4 fruits.push('banana'); console.log(fruits); //[ 'apple', <2 empty items>, 'orange', 'banana' ] console.log(fruits.length); //5 for (let i = 0; i < fruits.length; ++i) { console.log(i + ":" + fruits[i]); } //0:apple //1:undefined //2:undefined //3:orange //4:banana for (let i in fruits) { console.log(i + ":" + fruits[i]); } //0:apple //3:orange //4:banana (The undefined indexes were skipped) for (let item of fruits) { console.log(item); } //apple //undefined //undefined //orange //banana (The undefined items were not skipped)

      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); //[ 'apple', <2 empty items>, 'orange' ] (fruits[1] and fruits[2] are undefined)
      Accessing an Item

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

      Array's length

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

      a = ['11', '22', '33']; console.log(a); //[ '11', '22', '33' ] console.log(a.length); //3 a.length = 10; console.log(a); //[ '11', '22', '33', <7 empty items> ] console.log(a.length); //10 a.length = 2; console.log(a); //[ '11', '22' ] console.log(a.length); //2
      Dynamic Arrays

      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 delete. For examples,

      var days = ["sun", "mon", "tue"]; console.log(days.length); //3 console.log(days); //[ 'sun', 'mon', 'tue' ] days[5] = "fri"; console.log(days.length); //6 console.log(days); //[ 'sun', 'mon', 'tue', <2 empty items>, 'fri' ] (items in between are undefined) delete days[1]; console.log(days.length); //6 console.log(days); //[ 'sun', <1 empty item>, 'tue', <2 empty items>, 'fri' ] days.push("sat"); console.log(days.length); //7 console.log(days); //[ 'sun', <1 empty item>, 'tue', <2 empty items>, 'fri', 'sat' ] console.log(days.pop()); //sat console.log(days.length); //6 console.log(days); //[ 'sun', <1 empty item>, 'tue', <2 empty items>, 'fri' ] days.unshift("hi"); console.log(days.length); //7 console.log(days); //[ 'hi', 'sun', <1 empty item>, 'tue', <2 empty items>, 'fri' ] console.log(days.shift()); //hi console.log(days.length); //6 console.log(days); //[ 'sun', <1 empty item>, 'tue', <2 empty items>, 'fri' ] days[-9] = 'hello'; console.log(days.length); //6 console.log(days); //[ 'sun', <1 empty item>, 'tue', <2 empty items>, 'fri', '-9': 'hello' ]
      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 (let i = 1; i < days.length; ++i) { console.log(i + ": " + days[i]); } //1: mon //2: tue //3: wed //4: thu //5: fri //6: sat
      The JavaScript's for-in loop

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

      for (let idx in array) { ...... }

      For example,

      var months = ["jan", "feb"]; months[11] = "dec"; for (let idx in months) { console.log(idx + ": " + months[idx]); } //0: jan //1: feb //11: dec
      The JavaScript's for-of loop

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

      for (let item of array) { ...... }
      Add/Remove item(s)

      You can:

      • Use index [array.length] to add one item to the end of an array.
      • Use delete to remove a particular index (set it to undefined).
      • Use .push() to add one or more items to the end of an array. push() returns the resultant length of the array.
      • Use .unshift() to add one or more items to the beginning of an array. unshift() returns the resultant length of the array.
      • Use .pop() to remove and return the last item of an array.
      • Use .shift() to remove and return the first item of an array.

      For examples,

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

      The Array object has these commonly-used properties:

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

      It has these commonly-used methods:

      • array.join([separator]): join the elements of an array together into a single string, separated by the separator (defaulted to ','). For example, var fruits = ["apple", "orange", "banana"]; console.log(fruits.join()); //apple,orange,banana (string) console.log(fruits.join("|")); //apple|orange|banana (string)
      • str.split([separator, limit]): Reverse of join(). Take a string and split into an array based on the separator. For example, var str = 'apple,orange,banana'; var fruits = str.split(); console.log(fruits); //[ 'apple,orange,banana' ] console.log(fruits.length); //1 fruits = str.split(','); console.log(fruits); //[ 'apple', 'orange', 'banana' ] console.log(fruits.length); //3 str = 'coffee|*|tea|*|milk'; fruits = str.split('|*|'); console.log(fruits); //[ 'coffee', 'tea', 'milk' ] console.log(fruits.length); //3 fruits = str.split('*'); console.log(fruits); //[ 'coffee|', '|tea|', '|milk' ] console.log(fruits.length); //3
      • array.concat(value1, value2, ..., valueN): returns a new array composing of this array and the given arrays or values. For example, var fruits = ['apple', 'orange']; var moreFruits = fruits.concat('banana', 'watermelon'); console.log(moreFruits); //[ 'apple', 'orange', 'banana', 'watermelon' ] console.log(fruits); //[ 'apple', 'orange' ] (No change)
      • array.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); //[ '5', '4', '3', '2', '1' ]
      • array.sort(): sorts the elements in the array. For example, var a = ["8", "10", "a", "b"]; a.sort(); console.log(a); //[ '10', '8', 'a', 'b' ] a = [8, 20, 5, 100]; a.sort(); console.log(a); //[ 100, 20, 5, 8 ] 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 a and b, and return a negative number if a < b; a positive number if a > b; and 0 if a == b. For example,var a = [8, 20, 5, 100];/ a.sort( function(a, b) { return a - b; } ); console.log(a); //[ 5, 8, 20, 100 ]
      • array.slice(beginIdx, endIdx): extracts and returns a section of an array from beginIdx (inclusive) to endIdx (exclusive). For example, var a = ["a", "b", "c", "d", "e"]; console.log(a.slice(1, 4)); //[ 'b', 'c', 'd' ] (include start index but exclude end index) console.log(a); //[ 'a', 'b', 'c', 'd', 'e' ] (no change)
      • array.splice(startIdx, 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); // ["1", "2", "a", "b", "c", "d", "5"] //[ '1', '2', 'a', 'b', 'c', 'd', '5' ] console.log(a.length); //7
      • array.indexOf(searchItem[, startIdx]) and array.lastIndexOf(searchItem[, startIdx]): 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); //1 idx = a.indexOf(searchItem, idx + 1) console.log(idx); //4 idx = a.indexOf(searchItem, idx + 1) console.log(idx); //-1 (not found) console.log(a.lastIndexOf('a')); //3 console.log(a.lastIndexOf('a', 2)); //0
      • .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.
      Functional Programming in Filter-Map-Reduce pattern

      Arrays also support these iterative methods that iterate through each item of the array, to support functional programming of filter-map-reduce pattern.

      • 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); }); //processing item: apple //processing item: orange //processing item: banana NOTE: This syntax is meant to support functional programming of filter-map-reduce pattern.
      • array.map(callback): return a new array, which contains all the return value from executing callback on each item. For example, var fruits = ['apple', 'orange', 'banana']; var results = fruits.map(function (item) { console.log('processing item: ' + item); return item.toUpperCase(); }); //processing item: apple //processing item: orange //processing item: banana console.log(results); //[ 'APPLE', 'ORANGE', 'BANANA' ]
      • .filter(callback): return a new array, containing the items for which callback returned true. For example, var fruits = ['apple', 'orange', 'banana']; var result = fruits.filter( function (item) { console.log('processing item: ' + item); return /.*e$/.test(item); }); //processing item: apple //processing item: orange //processing item: banana console.log(result); //[ 'apple', 'orange' ]
      • array.every(callback): return true if callback returns true for ALL items.
      • array.some(callback): return true if callback returns true for at least one item in the array.

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

      Associative Arrays of Key-Value Pairs

      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 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 student = { name: 'peter', id: 8888, isMarried: false }; console.log(student); //{ name: 'peter', id: 8888, isMarried: false } student['age'] = 24; for (let key in student) { console.log(key + ": " + student[key]); } //name: peter //id: 8888 //isMarried: false //age: 24 console.log(typeof student); //object student.height = 190; console.log(student.height); //190

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

      Functions

      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.

      Functions are objects in JavaScript (to be discussed later).

      The syntax for user-defined function is:

      function functionName(argument1, argument2, ...) { statements; ...... return returnValue; }

      Functions are declared using the keyword function. Unlike Java/C/C++, you do not have to specify the return-type and the types of the arguments because JavaScript is loosely typed. You can use a return statement to return a single piece of result to the caller anywhere inside the function body. If no return statement is used (or a return with no value), JavaScript returns undefined.

      For client-side JavaScript, functions are generally defined in the HEAD section, so that it is always loaded before being invoked.

      To invoke a function:

      functionName(argument1, argument2, ...)
      Client-Side JavaScript Function Examples
      Function Demo
      Function's arguments

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

      function add() { var sum = 0; for (var i = 0; i < arguments.length; i++) { sum += Number(arguments[i]); } return sum; } console.log(add(1, 2, 3, 4, 5)); //15 console.log(add(6, 7)); //13 console.log(add(8.8, "9.9")); //18.700000000000003
      Pass by Value vs. Pass by Reference

      In JavaScript, primitive arguments are passed by value. That is, a copy of the variable is made and passed into the function. On the other hand, objects (including array and associative array) are passed by references. That is, if you modify the content of an object inside the function, the "copy" outside the function is also affected.

      The Default Function Arguments

      JavaScript lets you invoke a function omitting some trailing arguments. It sets the omitted arguments to the value undefined. For example,

      function f1(a1, a2, a3) { console.log('argument a1: type is ' + typeof a1 + ', value is ' + a1); console.log('argument a2: type is ' + typeof a2 + ', value is ' + a2); console.log('argument a3: type is ' + typeof a3 + ', value is ' + a3); } f1('hello'); //argument a1: type is string, value is hello //argument a2: type is undefined, value is undefined //argument a3: type is undefined, value is undefined f1(1, 2); //argument a1: type is number, value is 1 //argument a2: type is number, value is 2 //argument a3: type is undefined, value is undefined f1('hello', 1, 2); //argument a1: type is string, value is hello //argument a2: type is number, value is 1 //argument a3: type is number, value is 2 f1(1, 2, 3, 4); //error: This function expects 3 arguments, but 4 were provided.

      You can use this feature to provide default value to function argument, for example,

      function f2(a1, a2, a3) { if (a2 === undefined || a2 === null) a2 = 88; a3 = a3 || 'myDefault'; console.log('argument a2: type is ' + typeof a2 + ', value is ' + a2); console.log('argument a3: type is ' + typeof a3 + ', value is ' + a3); } f2('hello', 1, 2); //argument a2: type is number, value is 1 //argument a3: type is number, value is 2 f2('hello'); //argument a2: type is number, value is 88 //argument a3: type is string, value is myDefault f2('hello', null, null); //argument a2: type is number, value is 88 //argument a3: type is string, value is myDefault

      In the above example, we allow caller to omit the trailing arguments (a2, a3) or pass a null value (which is a special literal for unallocated object).

      The common idiom in practice today is to use the short-circuited OR expression (as in a3) to provide default value if no value (undefined or null) is passed, provided the valid inputs cannot be false, 0, '', and NaN that evaluate to false.

      (ES6) Function with Default Parameter Values

      ES6 greatly simplify the above by introducing default parameter value in the form of param = defaultValue. For example,

      function greets(name = 'everybody', callback = function (n) { console.log(`hello, ${n}`) }) { callback(name) } greets() //hello, everybody greets('peter') //hello, peter greets('peter', console.log) //peter
      (ES6) Rest/Spread Operator (...) and Arrow-Function Notation

      ES6 also introduces rest/spread operator (...) and arrow-function notation. See ES6 article.

      Anonymous (Inline) Functions

      In JavaScript, you can define an anonymous function (without a function name) using the following syntax:

      function( parameters ) { .... }

      Anonymous function is often used in event handlers and others.

      Function Variables

      In JavaScript, a variable can hold a primitive (number, string, boolean) or an object.

      In JavaScript, functions are first-class object. Hence, a variable can also hold a function object. For example,

      function f1(a1) { return 'run f1()'; } console.log(f1); //[Function: f1] console.log(f1('hello')); //run f1() var v2 = function (a2) { return 'run f2()'; } console.log(v2); //[Function: f2] console.log(v2('hello')); //run f2() var v3 = f1; console.log(v3); //[Function: f1] console.log(v3('hello')); //run f1()
      Two Ways in defining a function

      As seen in the above example, there are two ways to define a function:

      1. Use a function declaration statement in the form of: function functionName ( parameters ) { ...... }
      2. Use a function expression by assigning an anonymous function to a variable: var functionVarName = function ( parameters ) { ...... }
      Functions as Arguments

      Recall that a function takes zero or more arguments from the caller. In JavaScript, arguments can be a primitive or object. Since functions are first-class objects in JavaScript, a function may take another function as its argument.

      For example, the following function take a function and an array as its arguments, and apply the function to the array.

      function processArray(inFun, inArray) { let resultArray = []; for (let i in inArray) { resultArray[i] = inFun(inArray[i]); } return resultArray; } console.log(processArray(function (x) { return x * x; }, [1, 2, 3, 4, 5])); //[ 1, 4, 9, 16, 25 ] function cube(x) { return x * x * x; } console.log(processArray(cube, [1, 2, 3, 4, 5])); //[ 1, 8, 27, 64, 125 ]
      Nested Functions

      In JavaScript, you can define a function inside a function. For example,

      function f1(msg1) { console.log('in f1() with message:' + msg1); function f2(msg2) { console.log('in f2() with message:' + msg2); return 'f2:' + msg2; } return 'f1:' + f2(msg1); } console.log(f1('hello')); //in f1() with message:hello //in f2() with message:hello //f1:f2:hello
      Function as the return value

      You can return a function from a function. For example,

      function main(op) { let add = function (a1, a2) { console.log('in add()'); return a1 + a2; }; if (op === 'add') { return add; } else if (op === 'mul') { return function (a1, a2) { console.log('in mul()'); return a1 * a2 }; } else { return "error: invalid argument"; } } console.log(main('add')(1, 2)); //in add() //3 console.log(main('mul')(3, 4)); //in mul() //12

      Interacting with Users

      Client-side JavaScript provides these built-in top-level functions for interacting with the user:

      • alert(str): Pop-up a box to alert user for important information. The user will have to click "OK" to proceed. The alert() returns nothing (or undefined).
      • prompt(str, defaultValue): Pop-up a box to prompt user for input, with an optional defaultValue. The prompt() returns the user's input as a string. For example, var number1 = prompt('Enter the first integer:'); var number2 = prompt('Enter the second integer:'); alert('The sum is ' + number1 + number2); alert('The sum is ' + (Number(number1) + Number(number2)));
      • confirm(str): Pop-up a box and ask user to confirm some information. The user will have to click on "OK" or "Cancel" to proceed. The confirm() which returns a boolean value. For example, var isFriday = confirm("Is it Friday?"); if (isFriday) { alert("Thank God, it's Friday!"); } else { alert('Not a Friday'); }
      • document.write(str), document.writeln(str): Write the specified string to the current document. The writeln() (write-line) writes a newline after the string, while write() does not. Take note that browsers ignores extra white spaces, including newlines, in an HTML document, and treat newline as a single blank character. You need to write a
        or

        ...

        tag to ask the browser to display a line break.

      The following top-level built-in functions are available to client-side as well as server-side (or standalone):

      • console.log(value): write to the system (or error) console, used mainly for debugging.

      Other Top-level Built-in Functions

      JavaScript also pre-defines the following top-level global functions.

      • parseInt(str), parseFloat(str): parses the given str and returns the numeric value or NaN (Not-A-Number). The parseInt(str, radix) accepts an optional radix (or base). For example, var a = parseInt("88"); console.log('type: ' + typeof a + ', value: ' + a); //type: number, value: 88 a = parseInt("88.99"); console.log('type: ' + typeof a + ', value: ' + a); //type: number, value: 88 a = parseInt("14px"); console.log('type: ' + typeof a + ', value: ' + a); //type: number, value: 14 a = parseInt("Hello"); console.log('type: ' + typeof a + ', value: ' + a); //type: number, value: NaN a = parseFloat("88.99"); console.log('type: ' + typeof a + ', value: ' + a); //type: number, value: 88.99 a = parseFloat("0.5%"); console.log('type: ' + typeof a + ', value: ' + a); //type: number, value: 0.5 a = parseFloat('Hi'); console.log('type: ' + typeof a + ', value: ' + a); //type: number, value: NaN
      • Number(object): returns the number representation of the object. It works for String object, as well as many objects such as Date.
      • isFinite(number): returns true if number is not NaN, Infinity or -Infinity.
      • isNaN(number): returns true if number is NaN. Useful for checking the output of parseInt() and parseFloat().
      • eval(codes): evaluate the given JavaScript codes, which could be an expression or a sequence of statements. For example: [TODO]
      • encodeURI(), decodeURI(), encodeURIComponent(), decodeURIComponent(): encode or decode name-value pairs for the HTTP request, by replacing special characters with %xx. For example: [TODO]

      An Introduction to Events (for Client-side JavaScript)

      Client-side JavaScript are often event-driven. That is, a function (called event handler) will be fired in response to a certain user's or browser's action that generates an event.

      The commonly-used events are:

      • click: generated when the user clicks on an HTML element.
      • mouseover, mouseout: generated when the user positions the mouse pointer inside/away from the HTML element.
      • load, unload: generated after the browser loaded a document, and before the next document is loaded, respectively.

      The event handler, called oneventname (such as onclick, onmousemove, onload), is the function that responses to an event. The event handler is typically attached to the target HTML tag, e.g.,

      JavaScript Event Demo

      Hello

      Click this paragraph to say Hi...

      More about events in the later sections.

      Objects

      Objects are Everywhere!

      JavaScript is object-oriented (OO), and objects are everywhere in JavaScript. Arrays are objects. Functions are also objects. Primitives like string and number are auto-box to objects in many operations. Almost everything in JavaScript can be an object, possibly except the undefined and null (object)!

      It is crucial to understanding objects to be proficient in JavaScript, as they are everywhere, and they are used extensively in JavaScript plug-ins like jQuery, AngularJS, React, and etc.

      JavaScript, however, does not support all the OO features, so as to keep the language simple.

      Properties and Methods

      In conventional object-oriented programming languages (like Java/C++/C#), an object is a collection of properties and methods under a common name.

      • Properties (also called variables, attributes): contains values associated with the object.
      • Methods (also called operations, functions): contains actions that the object can perform.

      For example, a Car object has properties such as make, model, price, capacity; and methods such as startEngine(), move(), brake(), stopEngine().

      Unlike full-fledged OO languages, JavaScript is designed on a simple OO paradigm. A JavaScript object is simply a collection of properties. A property is an association between a name (or key) and value (i.e., name-value pair or key-value pair). If the value is a function (recall that functions are first-class objects that can be assigned to a variable), the property is known as a method. In other words, JavaScript does not differentiate between properties and methods like conventional OO languages. A method is simply a property holding a function.

      Creating Objects via Object Initializer

      You can create a new object by directly assign an object literal to a variable, known as Object Initializer. The syntax is as follows:

      var objectName = { property1: value1, property2: value2, ......, ...... }
      • A JavaScript object is a collection of properties. Each property is an association of a name (key) and value pair.
      • The name and value are separated by a colon ':'.
      • The name-value pairs are separated by commas ','. No comma is needed after the last name-value pair.
      • The property name could be a string or a number. For string name which is NOT a valid identifier (an valid identifier begins with an alphabet, underscore or dollar sign; and does not containing special characters like blank or '-'), you need to enclose the name with single or double quotes. Otherwise, the quotes are optional. For example, var student = { name: 'Tan Ah Teck', age: 21, 88: 'hello', 'my name': 'Peter', 'font-size': '14px', } Take note that if the property name's string is a proper identifier, you can omit the quotes. This is commonly practiced by the developers.
      • The property value could be a literal, a variable or an expression.
      • A property's value could take all JavaScript types, including primitives (string, number, boolean), object or function. The property is known as a method, if it holds a function. JavaScript does not differentiate between variables and methods like conventional OO languages (Java/C++/C#). A method is simply a property holding a function.
      • Objects created via Object Initializer are instances of class Object.
      Trailing Commas

      Trailing commas (sometimes called "final commas") can be useful when adding new elements, parameters, or properties to JavaScript code. If you want to add a new property, you can add a new line without modifying the previously last line if that line already uses a trailing comma. This makes version-control diffs cleaner and editing code might be less troublesome. JavaScript has allowed trailing commas in array literals since the beginning, and later added them to object literals (ES?), and more recently, to function parameters (ES?) and to named imports and named exports (ES?).

      Property Accessors: The Dot and Index (Square Bracket) operator

      In JavaScript, you can access an object's properties via either:

      1. The dot (.) operator: In the form of objectName.propertyName or objectName.methodName(arguments), just like Java/C++.
      2. The index [] operator (or bracket notation): In JavaScript, you can also use the index operator to access the object properties, in the form objectName[propertyName], just like accessing an array item.
      The delete operator

      You can remove a property (including method) via "delete propertyName".

      Operator instanceof

      You can use the instanceof operator to check if a particular instance belongs to a particular class of objects, e.g.,

      var now = new Date(); console.log(typeof now); //object console.log(now instanceof Date); //true console.log(now instanceof Object); //true console.log(now instanceof Array); //false console.log(now instanceof Function); //false
      The .hasOwnProperty() method

      The obj.hasOwnProperty(propertyName) returns true if obj has the specific propertyName.

      Operator in

      You can use the in operator to check if a particular property belongs to an object, for example,

      console.log("PI" in Math); //true
      Example 1: A Simple Object
      var request = { type: 'POST', url: 'apple.php', }; console.log(request.type); //POST console.log(request.url); //apple.php request.url = 'orange.php'; console.log(request.url); //orange.php console.log(request['type']); //POST console.log(request['url']); //orange.php request['url'] = 'banana.php'; console.log(request['url']); //banana.php var key = 'url'; console.log(request[key]); //banana.php console.log(request.hasOwnProperty('type')); //true console.log(request.hasOwnProperty('url')); //true delete request.type; console.log(request.hasOwnProperty('type')); //false console.log(request.hasOwnProperty('url')); //true
      Example 2: An object having object properties

      An object's property can hold primitives (number, string). It can also hold an object.

      var request = { type: 'POST', url: 'apple.php', data: { name: 'peter', id: 8888 } }; console.log(request.data.name); //peter console.log(request.data.id); //8888 console.log(request.data); //{ name: 'peter', id: 8888 } console.log(typeof request); //object console.log(typeof request.type); //string console.log(typeof request.data); //object
      Example 3: An object with function

      A JavaScript object's property can also hold a function (or method). You can assign to an anonymous function or a named function as shown in the following example.

      var myCircle = { radius: 5.5, created: new Date(), getArea: function () { return this.radius * this.radius * Math.PI; }, toString: toString } function toString() { return "Circle {radius: " + this.radius + ", created: " + this.created + "}"; } console.log(myCircle.getArea()); //95.03317777109125 console.log(myCircle.toString()); //Circle {radius: 5.5, created: ...} console.log(myCircle); //{ // radius: 5.5, // created: ......, // getArea: [Function: getArea], // toString: [Function: toString] //} console.log(typeof myCircle.getArea); //function (function is a first-class object in JavaScript) console.log(typeof myCircle.toString); //function console.log(typeof myCircle.created); //object (an Date object)
      To quote or not to quote the name in name-value pair?

      The name (of the name-value pair) can take a string or a number, e.g., var a = {88:'b', 'c':'d', fontSize:'14px'}.

      Many developers do not enquote the string name, if it is a valid identifier (a valid identifier begins with an alphabet, '_' or '$'; and does not contain special characters like blank and '-'). For example, var a = {b:'c', d:'e'} is the same as var a = {'b':'c', 'd':'e'}. However, you need to enquote a string name if it is NOT a valid identifier, e.g., var a = {'1b':'c', 'my name':'peter', 'font-size':'14px'}.

      The string value must be enquoted; otherwise, it will be treated as a variable name.

      Dot Operator vs. Index (Square Bracket) Operator

      You can access an object's property via either dot operator or index operator. Dot operator is commonly used as it is more concise and used in conventional OO languages. But index operator allows access to properties containing special characters and selection of properties using variables, which is not feasible with dot operator. For example,

      var a = { 'font-size': '14px' }; //console.log(a.font-size); //ReferenceError: size is not defined console.log(a['font-size']); //14px var key = 'font-size'; console.log(a[key]); //14px console.log(a['font' + '-size']); //14px
      Iterate through all the properties of an Object

      There are three ways to iterate through all properties of an object:

      1. for...in: traverses all enumerable properties of an object and its prototype chain.
      2. Object.keys(obj): return an array of all enumerable property names.
      3. Object.getOwnPropertyNames(obj): return an array of all property names.

      For example,

      var myCircle = { radius: 1.1, color: 'red', getArea: function () { return radius * radius * Math.PI; } }; for (let name in myCircle) { let value = myCircle[name]; console.log("name:" + name + ", value:" + value); } //name:radius, value:1.1 //name:color, value:red //name:getArea, value:function () { ... } var keys = Object.keys(myCircle); console.log(keys); //[ 'radius', 'color', 'getArea' ] for (let i = 0; i < keys.length; i++) { let key = keys[i]; let value = myCircle[key]; console.log("key:" + key + ", value:" + value); } //key:radius, value:1.1 //key:color, value:red //key:getArea, value:function () { ... } var names = Object.getOwnPropertyNames(myCircle); console.log(names); //[ 'radius', 'color', 'getArea' ] for (let name of names) { // "for-of" loop let value = myCircle[name]; console.log("name:" + name + ", value:" + value); } //name:radius, value:1.1 //name:color, value:red //name:getArea, value:function () { ... }
      Operator with

      Establishes the default object for a set of statements. The syntax is:

      with (expression) { statement; }
      The null vs undefined Literal Values

      As discussed earlier:

      • An undeclared variable has type of undefined, and its value cannot be referenced.
      • A declared but uninitialized variable has type of undefined, with a special literal value of undefined too. [undefined is both a type and a literal value!]
      • A unallocated object has a special literal value of null. Take note that null is an object!

      In boolean expressions, both the null and undefined evaluate to false (together with empty-string "", number 0 and NaN, and boolean false). To check for null value, use value === null, as value == null (or !value) returns true for null, undefined, "", 0, NaN, and false

      Built-in JavaScript Objects

      JavaScript provides many useful global objects, such as Array, Date, String, and Number.

      I shall discuss some commonly used objects here. For detailed specification and examples about a built-in object, check "Core JavaScript References".

      Creating an Object via Constructor and the new Operator

      All the built-in objects define a so-called constructor, which is a special method having the same name as the object, for creating new instances. To invoke the constructor, you need to use a special new operator.

      For example, the Date object has a constructor method called Date(). To construct a new instance of Date object:

      var now = new Date(); console.log(now); //Tue May 26 2015 22:59:43 GMT+0800 (SGT) console.log(now.toString()); //Tue May 26 2015 22:59:43 GMT+0800 (SGT) console.log(now.valueOf()); //1432652383342 console.log('type: ' + typeof now); //type: object console.log(now instanceof Object); //true console.log(now instanceof Date); //true console.log(now instanceof Array); //false var day = new Date(1970, 1, 1, 12, 34, 56, 79); console.log(day); //Sun Feb 01 1970 12:34:56 GMT+0800 (SGT) console.log(day.toString()); //Sun Feb 01 1970 12:34:56 GMT+0800 (SGT) console.log(day.valueOf()); //2694896079
      The typeof and instanceof Operators

      As seen from the above examples, the typeof operator returns the type of a value, which can be a primitive type (such as number, string, boolean) or object (including function).

      The instanceof operator check if the value is an instance of a class.

      The .toString() and .valueOf() Methods

      The following methods are available to all built-in JavaScript objects:

      • .toString(): returns a string description about this object.
      • .valueOf(): converts this object to a primitive value such as number.

      The Array Object and Associative Arrays

      For an introduction to arrays, read the "Arrays" section.

      Nowadays, we usually create an array via Array Initializer in the form of [value1, value2, ...]. Nonetheless, as arrays are objects of class Array, we could also construct an array by invoking the Array() constructor with the new operator. This is more complex and, hence, less commonly used today (but may show up in old codes and books).

      For example,

      var weekdays = new Array("sun", "mon", "tue", "wed", "thu", "fri", "sat"); console.log(weekdays.length); //7 console.log(weekdays); //[ 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat' ] console.log(typeof weekdays); //object console.log(weekdays instanceof Array); //true //console.log(weekdays instanceof array); //ReferenceError: array is not defined var a = [0, 'b', 'c']; console.log(typeof a); //object console.log(a instanceof Array); //true
      An Associative Array is a Generic "Object", not an "Array" Object

      For an introduction to arrays, read the "Associative Arrays" section.

      JavaScript does not really support associative array, but allow you to add properties to an object, using the associative array syntax and index operator. In other words,

      var student = { name: 'peter' }; student['age'] = 21; console.log(student['age']); //21 console.log(student.length); //undefined (It is an Object, not Array. The .length is for array) console.log(student instanceof Array); //false
      Using an Array Object for Associative Array

      In JavaScript, we usually create an associative array using a generic object (via the Object Initializer). You can also create an associative array via Array constructor. For examples,

      var student = new Array(); student['name'] = 'Peter'; student['id'] = 12345; for (let key in student) { console.log(key + ": " + student[key]); } //name: peter //id: 12345 console.log(student.length); //0 (!!!) console.log(student instanceof Array); //true console.log(typeof student); //object

      In this case, additional properties are added into an Array object as object's properties. The array has .length of 0, as .length reflects only the numerical indexes! Using an array object for associative array is not recommended. I describe here for completeness.

      The String Object vs string Primitive Type

      JavaScript provides primitive string type. It also provide a String class as a wrapper class for primitive string. Read "The string Type, Literals and Operations" for primitive string.

      A string can be created in two ways:

      1. directly assigned a string literal in the form of "..." or '...' to a variable, resulted in a string primitive.
      2. invoke the String object constructor to construct a String object.

      For examples,

      var str1 = 'Hello'; console.log('type: ' + typeof str1); //type: string (primitive) console.log(str2 instanceof String); //false console.log(str2 instanceof Object); //false var str2 = new String('Hello'); console.log('type: ' + typeof str2); //type: object console.log(str2 instanceof String); //true console.log(str2 instanceof Object); //true

      The former is a primitive string, while the latter is a String object.

      String object is a wrapper for primitive string, which provides many useful methods for manipulating strings. See "The string Type, Literals, and Operations".

      A string primitive is "auto-box" to a String object, when you invoke a String object's methods. For example,

      var str = "hello"; console.log(str.length); //5 console.log(str.substring(1, 3)); //el

      The Number Object vs number Primitive Type

      JavaScript provides primitive number type. It also provide a Number class as a wrapper class for primitive number. Read "The number Type, Literals and Operations" for primitive number.

      The Number object is a wrapper object for primitive number, which provides many properties and methods. Again, a number primitive is auto-box to a Number object, when you invoke a Number object's operation. See "The number Type, Literals, and Operations".

      The Boolean Object vs boolean Primitive Type

      JavaScript provides primitive boolean type. It also provide a Boolean class as a wrapper class for primitive boolean. Read "The boolean Type, Literals and Operations" for primitive boolean.

      The Boolean object is a wrapper object for primitive boolean, which provides many properties and methods.

      The Date Object

      Commonly-used constructors:

      • new Date(): constructs a Date object with the current date and time.
      • new Date(dateTimeStr): constructs a Date object with the given date-time string in an acceptable form (e.g., "Month, day, year, hours:minutes:seconds").
      • new Date(year, Month, day): where month is 0-11 for Jan to Dec.
      • new Date(year, Month, day, hours, minutes, seconds, milliseconds)

      Commonly-used methods:

      • getDate(), setDate(), getMonth(), setMonth(), getFullYear(), setFullYear(): get/set the date (1-31), month (0-11 for Jan to Dec), year (4-digit year).
      • getDay(): get the day of the week (0-6 for Sunday to Saturday).
      • getHours(), setHours(), getMinutes(), setMinutes(), getSeconds(), setSeconds(): get/set the hours/minutes/seconds.
      • getTime(), setTime(): get/set the number of milliseconds since January 1, 1970, 00:00:00.

      The Math Object

      Commonly-used properties:

      • E, PI: Euler’s constant and PI.
      • LN2, LN10, LOG2E, LOG10E: ln(2), ln(10), log2(e), log10(e).
      • SQRT2, SQRT1_2: square root of 2 and one-half.

      Commonly-used methods:

      • abs(x)
      • sin(a), cos(a), tan(a), asin(x), acos(x), atan(x), atan2(x,y)
      • cell(x), floor(x), round(x)
      • exp(x), log(x), pow(base,exp), sqrt(x)
      • max(x,y), min(x,y)
      • random(): returns a pseudo-random number between 0 and 1.

      The Function Object

      For an introduction to functions, read "Function" section.

      Every function in JavaScript is actually a Function object!

      Function Variable

      A variable can be assigned a Function object (called function variable), which takes a special object type called function. [In JavaScript, an object's type is either function (for Function object) or object (for any object not a Function).]

      For example,

      function sayHello(name) { return 'hello, ' + name; } console.log(sayHello('peter')); //hello, peter console.log('type: ' + typeof sayHello); //type: function console.log(sayHello instanceof Function); //true console.log(sayHello instanceof Object); //true var magic = sayHello; console.log(magic('paul')); //hello, paul console.log('type: ' + typeof magic); //type: function console.log(magic instanceof Function); //true console.log(magic instanceof Object); //true
      Anonymous Function

      If a function is called only once, you can use an anonymous function, omitting the function name. Anonymous functions are commonly-used as event handler, e.g.,

      window.onload = function(event) { console.log("run onload handler"); console.log(event.target); } function onloadhandler(event) { console.log("run pre-defined onload handler"); console.log(event.target); } window.onload = onloadhandler;

      You can define a inline (anonymous) function and assign it to a variable as follows:

      var magic = function() { return "Hello" }; function magic() { return "Hello" };
      Function Constructor

      Besides using function keyword, you can also use the Function constructor (with new operator) to define a Function object. This is not easily understood and, hence, not recommended.

      var magic = new Function("arg1", "arg2", "return arg1 + arg2"); // function magic(arg1, arg2) { return arg1 + arg2; } // var magic = function (arg1, arg2) { return arg1 + arg2; } console.log(magic(55, 66)); //121 console.log(magic('55', '66')); //5566 console.log('type: ' + typeof magic); //type: function console.log(magic instanceof Function); //true console.log(magic instanceof Object); //true

      The syntax for Function constructor is:

      var functionName = new Function("argument1", "argument2", ..., "functionBody");

      More on Objects

      Prototype-based vs. Class-based

      JavaScript's OO is prototype-based, instead of class-based like Java/C++/C#.

      A class-based OO language (such as Java/C++/C#) is founded on concepts of class and instance. A class is a blue-print or template of things of the same kind. An instance is a particular realization of a class. For example, "Student" is a class; and "Tan Ah Teck" and "Paul Lee" are instances of the "Student" class. In a class-based OO language, you must first write a class definition, before you can create instances based on the class definition. The instances created have exactly the same properties and methods as the class - no more, and no less.

      On the other hand, a prototype-based OO language (such as JavaScript) simply has objects (or instances). A new object can be constructed based on an existing object as prototype. There is no class definition, and hence, they are also called class-less OO languages.

      In JavaScript:

      • Every JavaScript object has a prototype. The prototype is also an object. A JavaScript object is created from a prototype object and gets its initial properties from the prototype.
      • Every JavaScript object has an internal property called __proto__, which holds its prototype object. When you define a new object via "Object Initializer" (or new Object() constructor), its __proto__ is set to a built-in object called Object.prototype. In other words, the new object uses Object.prototype as its prototype, and gets its initial properties from Object.prototype. The __proto__ property is not enumerable, i.e, it would not shown up in the for..in loop.
        For example, var myCircle = { radius: 1.1, getArea: function () { return this.radius * this.radius * Math.PI; } } console.log(myCircle.radius); //1.1 console.log(myCircle.getArea()); //3.8013271108436504 console.log(myCircle.__proto__ === Object.prototype); //true console.log(Object.prototype); //[Object: null prototype] { } console.log(Object.prototype.__proto__); //null console.log(Object.prototype.toString()); //[object Object] console.log(Object.prototype.valueOf()); //[Object: null prototype] { } console.log(Object.prototype.hasOwnProperty('toString')); //true , console.log(myCircle.toString()); //[object Object] console.log(myCircle.hasOwnProperty('toString')); //false (inherited, NOT own property) console.log(myCircle.hasOwnProperty('radius')); //true for (let key in myCircle) { console.log("key: " + key + ", value: " + myCircle[key]); } //key: radius, value: 1.1 //key: getArea, value: function () { ... } var anotherCircle = new Object(); anotherCircle.radius = 2.2; console.log(anotherCircle.__proto__ === Object.prototype); //true
      • Any object can be the prototype of new objects. For example, Object is the prototype of Person; Person is the prototype for Student; Student is the prototype for UndergraduateStudent. These objects form a so-called prototype chain, i.e., UndergraduateStudent -> Student -> Person -> Object -> null. Take note that Object is always on top of the prototype chain for every JavaScript object.
      • You can add or remove properties for an object at runtime, which is not permitted in conventional OO languages.

      Defining Your Own Custom Objects via a Constructor

      In JavaScript, you can create your own custom objects by defining a constructor. A constructor is simply a function, which can be invoked via the new operator to create and initialize new objects. Recall that JavaScript is prototype-based and class-less. A new object is created from a prototype object, and gets its initial properties from this prototype object. The constructor function provides the prototype to create and initialize new instances (to be explained later).

      By convention, a constructor name begins with an uppercase letter.

      Keyword this

      "this" refers to the current object. this.aPropertyName refers to the property of this object.

      Example

      Let us define a constructor for our custom Circle objects, with properties radius, created, getArea() and toString().

      function Circle(radius) { this.radius = radius || 1; (e.g., undefined) this.dateCreated = new Date(); this.getArea = function () { return this.radius * this.radius * Math.PI; }; this.toString = toString; } function toString() { return "Circle {radius: " + this.radius + ", dateCreated: " + this.dateCreated + "}"; } var circle1 = new Circle(1.5); console.log(circle1); //Circle {radius: 1.5, dateCreated: ...} var circle2 = new Circle(); console.log(circle2); //Circle {radius: 1, dateCreated: ...} var circle3 = new Circle; console.log(circle3); //Circle {radius: 1, dateCreated: ...} console.log(circle1.getArea()); //7.0685834705770345 console.log(circle2.getArea()); //3.141592653589793 console.log(typeof circle1); //object console.log(circle1 instanceof Object); //true console.log(circle1 instanceof Circle); //true console.log(circle1 instanceof Array); //false console.log(Circle.prototype); //{} console.log(circle1.__proto__ === Circle.prototype); //true console.log(Circle.prototype.__proto__ === Object.prototype); //true console.log(Object.prototype.__proto__); //null
      How it Works?
      1. Properties (including methods) are declared inside the constructor via this.propertyName, which can then be initialized.
      2. Methods can be declared inside the constructor via this.methodName. There are a few ways to provide the method's definition:
        1. Define an ordinary function, and assign the functionName (without parentheses, which is a function type) to this.methodName, as in the toString().
        2. Assign this.methodName to an inline function, as in the getArea().
        3. Invoke the Function constructor with new operator (rarely-used): this.getArea = new Function("return this.radius * this.radius * Math.PI");
      3. To invoke a method, use anObjectName.aMethodName(arguments).
      4. The .toString() is a special method, which returns a string description of this object. The .toString() will be implicitly invoked if an object is passed into the document.write(), document.writeln() or '+' operator (like Java).

      __proto__ and .prototype

      Revisit the new Operator

      In JavaScript, the new constructor(args) call does the followings:

      1. Create a new generic object using built-in root Object as prototype.
      2. Assign this newly created object to this variable.
      3. Run the constructor function, which typically adds properties to this.
      4. Set the internal property __proto__ to constructor.prototype (in the above example, Circle.prototype). The __proto__ property is not enumerable (i.e, it would not shown up in the for..in loop). It is used to maintain the so called "prototype chain" of the objects.
      5. Return the newly created object.

      Take note that you can invoke the constructor function WITHOUT the new operator, e.g., Circle(1.5). In this case, the constructor will be run as per ordinary function. There will not be any association of this and __proto__ properties; and the return value will depend on the function codes.

      Try tracing the object created in the above example via Chrome's Developer Tools, which could display the __proto__ internal property.

      Another Example
      function Person(name, age) { this.name = name || ""; this.age = age || ""; this.toString = function () { return "Person {name: " + this.name + ", age: " + this.age + "}"; }; } var p1 = new Person("Peter", 18); console.log(p1); //Person { name: 'Peter', age: 18, toString: [Function (anonymous)] } console.log(p1.toString()); //Person {name: Peter, age: 18} console.log(p1.__proto__ === Person.prototype); //true console.log(Person.prototype); //{} console.log(Person.prototype.__proto__ === Object.prototype); //true console.log(Object.prototype); //[Object: null prototype] {}
      Constructor's .prototype Property

      All the JavaScript constructor function objects (in fact, all function objects) have a special property called .prototype. By default, it holds an object that can be used as a prototype for creating new objects.

      In the Circle example, the Circle constructor function has a Circle.prototype, which holds a Circle object to be used as a prototyping object. When a new Circle object is constructed via the new operator, the newly constructed object's __proto__ property is set to Circle.prototype.

      Adding Shared properties to Constructor's .prototype Property

      The constructor's.prototype is used to implement shared properties (typically shared methods) for all the objects it prototyped. In JavaScript, you can add properties dynamically during runtime into .prototype. The added properties/methods will be available to all the objects (new as well as existing objects). For example,

      function Circle(radius) { this.radius = radius || 1.0; this.getArea = function () { return this.radius * this.radius * Math.PI; }; } var circle1 = new Circle; Circle.prototype.getCircumference = function () { return 2 * this.radius * Math.PI; }; Circle.prototype.color = "green"; console.log(circle1.getCircumference()); //6.283185307179586 console.log(circle1.color); //green var circle2 = new Circle(1.5); console.log(circle2.getArea()); //7.0685834705770345 console.log(circle2.getCircumference()); //9.42477796076938 console.log(circle2.color); //green console.log(circle1.__proto__ === Circle.prototype); //true

      When you reference a property, JavaScript first checks if the property exists locally (or own property); otherwise, it checks the prototype chain through the __proto__ property. Recall that the new constructor() call sets the __proto__ to constructor.prototype. Hence, properties added into constructor.prototype are available to (and shared by) all the objects prototyped by this constructor.

      In practice, we defines methods (and static variables) in constructor.prototype to be shared by all objects; while each object maintains its own properties (instance variables).

      Looking up the Prototype Chain

      Objects in JavaScipt form prototype chains. In the above example, a prototype chain is circle1 -> Circle.prototype -> Object.prototype -> null.

      When you reference an object property, JavaScript follow these steps to locate the property:

      1. Check if the property exists locally (i.e., own property).
      2. Otherwise, check the __proto__ property. This continues recursively up the prototype chain. The process is called "lookup in the prototype chain".

      Hence, in the above example, all the properties in Circle.prototype and Object.prototype are inherited by circle1.

      instanceof Operator

      Every object has a __proto__ object property (except Object); every constructor function has a .prototype property. So objects can be related by 'prototype inheritance' to other objects. You can test for inheritance by comparing an object's __proto__ to the constructor's .prototype. JavaScript provides a shortcut: the instanceof operator tests an object against a function and returns true if the object inherits from the function prototype. For example,

      [TODO]

      Object.create()

      Object.create() lets you create a new object based on the given prototype object. It simply sets the __proto__ to the given prototype object, so that all properties of the prototype are available to the new object. Using Object.create(), You do NOT need to define a constructor function and run new constructor() to create new objects.

      var student1 = { name: 'Peter', getName: function () { return this.name; } } console.log(student1); //{ name: 'Peter', getName: [Function: getName] } console.log(student1.getName()); //Peter console.log(student1.hasOwnProperty('name')); //true var student2 = Object.create(student1); console.log(student2); //{} console.log(student2.__proto__); //{ name: 'Peter', getName: [Function: getName] } (set prototype chain) console.log(student2.__proto__ === student1); //true (same reference) console.log(student2 === student1); //false (different reference) console.log(student2.getName()); //Peter (inherited thru prototype chain) console.log(student2.hasOwnProperty('name')); //false student2.name = 'Paul'; console.log(student2); //{ name: 'Paul' } (added own property) console.log(student2.__proto__); //{ name: 'Peter', getName: [Function: getName] } (no change) console.log(student2.getName()); //Paul console.log(student2.hasOwnProperty('name')); //true

      Inheritance via Prototype Chain

      You can implement inheritance in JavaScript via the prototype chain. For example,

      function Person(name, age) { this.name = name || ""; this.age = age || ""; } function Student(name, age, school) { Person.call(this, name, age); this.school = school || ""; } Student.prototype = Object.create(Person.prototype) function UndergraduateStudent(name, age, school, year) { Student.call(this, name, age, school); this.year = year || ""; } UndergraduateStudent.prototype = Object.create(Student.prototype) var peter = new UndergraduateStudent('peter', 21, 'EEE', 1); console.log(peter); //Person { name: 'peter', age: 21, school: 'EEE', year: 1 } console.log(peter instanceof UndergraduateStudent); //true console.log(peter instanceof Student); //true console.log(peter instanceof Person); //true console.log(peter instanceof Object); //true console.log(peter instanceof Date); //false // Add property to Person's prototype Person.prototype.incAge = function () { return ++this.age; }; console.log(peter); //Person { name: 'peter', age: 21, school: 'EEE', year: 1 } console.log(peter.incAge()); //22 (inherited from Person) console.log('incAge' in peter); //true console.log(peter.hasOwnProperty('incAge')); //false (inherited, NOT own property)
      How It Works

      [TODO]

      Getter and Setter

      In languages like Java, you can declare a variable to be private and define public getter/setter to access the private variable. JavaScript does not really support private access?! But you can also define ordinary methods getXxx() or setXxx() as getter/setter like Java.

      Moreover, in JavaScript, you can define getter/setter as properties instead of methods in one of the following two ways:

      1. via built-in functions Object.defineProperties() or Object.defineProperty();
      2. inside the "object initializer" via keywords get and set.
      Example 1: Define Getters/Setters via Object.defineProperties() or Object.defineProperty()
      function Circle(radius) { this._radius = radius || 1; } Object.defineProperties(Circle.prototype, { 'radius': { get: function () { return this._radius; }, set: function (radius) { this._radius = radius; } }, 'area': { get: function () { return this._radius * this._radius * Math.PI; } }, 'circumference': { get: function () { return 2 * this._radius * Math.PI; } } }); var myCircle = new Circle(1.1); console.log(myCircle.radius); //1.1 myCircle.radius = 2.2; console.log(myCircle.radius); //2.2 console.log(myCircle.area); //15.205308443374602 console.log(myCircle.circumference); //13.823007675795091 console.log(myCircle); //Circle { _radius: 2.2 }

      Notes:

      1. The Objet.defineProperties() allows you to define multiple properties; while Objet.defineProperty() for a single property.
      2. You invoke the getters/setters like properties with assignment operator, instead of via function call.
      Example 2: Define Getter/Setter inside the Object Initializer
      var myCircle = { _radius: 1.1, get radius() { return this._radius; }, set radius(radius) { this._radius = radius; }, get area() { return this._radius * this._radius * Math.PI; }, get circumference() { return 2 * this._radius * Math.PI; } } console.log(myCircle.radius); //1.1 myCircle.radius = 2.2; console.log(myCircle.radius); //2.2 console.log(myCircle.area); //15.205308443374602 console.log(myCircle.circumference); //13.823007675795091

      Notes:

      1. The getter/setter are defined inside Object Initializer via keywords get and set with a rather strange syntax, as shown in the example.

      Object's Properties

      Object.constructor()

      All JavaScript objects inherited a special property called .constructor, which contains a reference to the function that created the object. For example,

      var months = ['jan', 'feb', 'mar']; console.log(months.constructor); //[Function: Array] console.log(months); //[ 'jan', 'feb', 'mar' ] var days = months.constructor('mon', 'tue', 'wed') console.log(days); //[ 'mon', 'tue', 'wed' ]

      [TODO] more Object's properties

      Document Object Model (DOM) API for JavaScript

      Document Object Model (DOM), is a standard API that allows programmers to access and manipulate the contents of an HTML/XHTML/XML document dynamically inside their program. It models an HTML/XHTML/XML document as an object-oriented, tree-like structure, known as a DOM-tree, consisting of nodes resembling the tags (elements) and contents. DOM also provides an interface for event handling, allowing you to respond to user's or browser's action.

      DOM API is implemented in many languages such as Java, JavaScript, Perl, and ActiveX. DOM API specification is maintained by W3C. DOM has various levels:

      • DOM Level 0 (DOM0) (Pre-W3C): obsolete
      • DOM Level 1 (DOM1) (W3C Oct 1998): obsolete
      • DOM Level 2 (DOM2) (W3C Nov 2000) and DOM Level 2 HTML (HTML DOM2) (W3C Jan 2003)
      • DOM Level 3 (DOM3) (W3C Apr 2004): yet to be fully supported by browsers.

      jQuery is much better in selecting and manipulating DOM element. You should use jQuery in production. I keep these sections here for completeness.

      Finding and Selecting Elements

      In JavaScript, we often use DOM API to select elements within the current document, so as to access or manipulate their contents. The most commonly-used functions are:

      FunctionDescriptionExample
      document.getElementById(anId) Returns the element with the given unique id. var elm = document.getElementById("foo"); var input = elm.value;
      document.getElementsByTagName(aTagName) Returns an array of elements with the given tag name. var elms = document.getElementByTagName("input"); var input = elms[0].value;
      document.getElementsByClassName(aClassName) Returns an array of elements with the given class attribute name. var elms = document.getElementByClassName("bar"); var input = elms[0].value;
      document.getElementsByName(aName) Returns an array of elements with the given name attribute. Male Female var x = document.getElementsByName("gender"); for (var i = 0; i < x.length; ++i) { if (x[i].checked) { value = x[i].value; break; } }

      You can use wildcard * in document.getElementsByTagName("*") to select all the elements, e.g.,

      var elms = document.getElementsByTagName("*"); for (var i = 0; i < elms.length; i++) { console.log(elms[i].value); ....... }

      The above functions select element(s) based on the unique id, name attribue and tag-name. HTML 5 further defines two function that can select elements based on class attribute (which is used extensively by CSS in the class-selector):

      FunctionDescriptionExample
      document.querySelector(aClassName) Returns the first element with the given class attribute. [TODO]
      document.querySelectorAll(aClassName) Returns an array of elements with the given class attribute. [TODO]

      Beside the above selection functions, there are many other selection functions available. However, I strongly recommend that you stick to the above functions. I listed below the other function below for completeness.

      1. document.images returns an array of all
        Javascript is a language often used within html documents to trigger interactive features.

        Load the web page onto Firefox, and use the firebug to inspect the DOM tree.

        A DOM-tree comprises the following types of nodes:

        1. Document Node: the root node representing the entire HMTL document.
        2. Element node: represents an HTML element (or tag). An element node may have child nodes, which can be either element or text node. Element node may also have attributes.
        3. Text Node: contains the text content of an element.
        4. Others: such as comment, attribute.

        A DOM node has these properties:

        • nodeName: contain the name of the node, which is read-only. The nodeName for an Element node is the tag-name; nodeName for the Document node is #document; nodeName for Text nodes is #text.
        • nodeValue: contain the value of the node. nodeValue for Text node is the text contained; nodeValue for Element node is undefined.
        • nodeType: an integer indicating the type of the node, e.g., Element (1), Attribute (2), Text (3), Comment (8), Document (9).
        • parentNode: reference to parent node. There is only one parent node in a tree structure.
        • childNodes: array (or node-list) of child nodes.
        • firstChild, lastChild: reference to the first and last child node.
        • prevSibling, nextSibling: reference to the previous and next sibling in the same level.

        Take note of the difference between singular and plural terms. For example, parentNode refer to the parent node (each node except root has one and only one parent node), childNodes holds an array of all the children nodes.

        The root node of the DOM tree is called document. The root node document has only one child, called document.documentElement, representing the tag, and it acts as the parent for two child nodes representing and tags, which in turn will have other child nodes. You can also use a special property called document.body to access the tag directly.

        For example, you can use the following node property to access the Text node "Welcome to " in the above example:

        document.documentElement.lastChild.childNodes[1].firstChild.nodeValue; document.body.lastChild.firstChild.nodeValue;
        Example

        The following JavaScript lists all the nodes in the section, in a depth-first search manner, via a recursive function.

        DOM Tree onload="printNode(document.body)">

        Testing

        welcome to JavaScript...

        Node name=BODY, value=null, type=1 Node name=H2, value=null, type=1 Node name=#text, value=Testing, type=3 Node name=P, value=null, type=1 Node name=#text, value=welcome to , type=3 Node name=I, value=null, type=1 Node name=#text, value=JavaScript, type=3 Node name=#text, value=..., type=3

        Accessing the HTML element via Node interface may not be too useful nor practical for JavaScript applications, as you need to know the actual topological structure of the DOM-tree. Furthermore, some browsers (e.g., firefox) may create extra Text nodes to contain the white spaces between tags.

        Text Node

        DOM models the texts enclosed by HTML tags as a separate text node. It cannot have child node. To retrieve the text content, you could the property nodeValue. For example,

        Hello

        ...... console.log(document.getElementById("magic").firstChild.nodeValue); document.getElementById("magic").firstChild.nodeValue = "Hi";

        Attribute Properties

        To access an attribute of an Element node called elementName, you could either use:

        • property elementName.attributeName, where attributeName is the name of the attribute, or
        • methods elementName.getAttribute(name) and elementName.setAttribute(name, value).

        For example,

        Test Attributes

        Hello

        Hello, again.

        Attribute style (for CSS)

        Element has a property called style, which models CSS style with CSS properties such as color and textAlign. For example,

        Hello

        ...... document.getElementById("magic1").style.color="green"; document.getElementById("magic1").style.textAlign="right";

        Manipulating Nodes

        A Node object has these functions:

        • aNode.hasChildNodes(): returns true if this node has at least one child node.
        • Manipulating child node:
          • aParentNode.insertBefore(newChildNode, existingChildNode): insert a node before an existing child node.
          • aParentNode.replaceChild(newChildNode, existingChildNode): replace an existing child node.
          • aParentNode.removeChild(childNodeToRemove): remove the specified child node.
          • aParentNode.appendChild(nodeToAppend): append the given node as the last child.
        • aNode.cloneNode():
        Creating a New Element (createElement()) and Text Node (createTextNode()), Appending a Node (appendChild())

        To create new text node, you can use document.createTextNode(text) to create a standalone text-node, followed by an anElementNode.appendChid(aTextNode) to append the text node to an element.

        Similarly, you can use document.createElement(tagName) to create a stand-alone element, followed by an anElementNode.appendChild(elementToAppend) to append the created element into an existing element.

        For example, we shall create a new text node, as a child of a new

        element. We shall then append the new

        element as the last child of .

        Hello

        Inserting a new Node (insertBefore())

        Hello

        Replacing a Node (replaceChild())

        Change the last line to document.body.replaceChild(newElm, magicElm).

        Deleting a Node (removeChild())

        You can remove a child node from a parent node via aParentNode.removeChild(aChildNode).

        For example, let remove the last

        from .

        Hello 1

        Hello 2

        Hello 3

        The document object

        The document object is the root node of the DOM-tree. It can be used to access all the elements in an HTML page.

        It contains these properties:

        • documentElement, body, title: references the , and tags respectively.</li><li>lastModified, referrer, cookie, domain: information retrieved from the HTTP response header.</li><li>form[], applets[], images[], embeds[], links[], anchors[]: Arrays containing the respective HTML elements (backward compatible with DOM0).</li></ul><p>The document object has the following methods:</p><ul><li>write(string), writeln(string): Write the specified string to the current document. writeln() (write-line) writes a newline after the string, while write() does not. Take note that browser ignores newlines in an HTML document, you need to write a <br> or <p>...</p> tag for the browser to display a line break.</li><li>clear(): Clear the document.</li><li>open(), close(): Open/close the document stream.</li><li>getElementById(), getElementsByName(), getElementsByTagName(): Select HTML element(s) by id, name, or tag-name, respectively.</li></ul><h3 id="event-handling-in-html-dom">Event Handling in HTML DOM</h3><p>JavaScripts are often event-driven. That is, a piece of codes (called event handler) fire in response to a certain user's or browser's action, such as clicking a button, enter some texts, or loaded a page.</p><p>DOM API provides methods for capturing events so you can perform your own actions in response to them. It also provides an Event object which contains information specific to a given event that can be used by your event handler.</p><p>jQuery is much simpler and better in event handling. I suggest that you use jQuery in production. I keep these sections here for completeness.</p><h4>Attach Event Handler to an HTML tag</h4><p>You can attach event handler (e.g., onclick, onmouseover) to a specific HTML tag as the tag's attribute, as follows:</p><tagName eventHandler="JavaScript statement(s)" otherAttributes >contents</tagName><p>The event handler can be a single JavaScript statement, a series of JavaScript statements (separated by semicolon), or most often, a function call. For example,</p><body <span>onload="alert('welcome')" onunload="alert('bye')"</span>> <script> function myHandler(event) { alert(event); } </script> <input type="button" value="click me" <span>onclick="myHandler()</span>"> <h2 <span>onmouseover="this.style.color='red'; this.style.backgroundColor='black'" onmouseout="this.style.color=''; this.style.backgroundColor=''"</span>>Hello</h2><p>You can also define an event handler in script by assigning a Function object (without parentheses) to an event handler. For example,</p><p id="magic">Welcome</p> <script> <span>document.getElementById("magic").onclick = myHandler;</span> </script><h4>Built-in Events and Event Handlers</h4><p>JavaScript supports many types of events, as tabulated below. Certain events such as click are applicable to all the HTML elements; certain event such as load and unload are applicable to a selected group of tags.</p> <table><tr><th>Event Name</th><th>Event Handler</th><th>Description</th><th>HTML Element</th></tr><tr><td>click </td><td>onclick </td><td>User clicks on the component. </td><td>  </td></tr><tr><td>submit </td><td>onsubmit </td><td>User clicks the "submit" button. </td><td><form>, <input type="submit"> </td></tr><tr><td>reset </td><td>onreset </td><td>User clicks the "reset" button. </td><td><form>, <input type="reset"> </td></tr><tr><td>select </td><td>onselect </td><td>User selects text in a text box or text area. </td><td><textarea>, <input type="text"> </td></tr><tr><td>keypress </td><td>onkeypress </td><td>User holds down a key. </td><td>document, image, link, textarea </td></tr><tr><td>keydown<br> keyup </td><td>onkeydown<br> onkeyup </td><td>User presses/releases a key. </td><td>  </td></tr><tr><td>mousedown<br> mouseup </td><td>onmousedown<br> onmouseup </td><td>User presses/releases a mouse button. </td><td>button, document, link </td></tr><tr><td>mouseover<br> mouseout </td><td>onmouseover<br> onmouseout </td><td>User moves the mouse pointer at/away from a link or hot spot. </td><td>  </td></tr><tr><td>mousemove </td><td>onmousemove </td><td>User moves the mouse pointer </td><td>  </td></tr><tr><td>load </td><td>onload </td><td>When the page is loaded into the window. </td><td><body>, <frameset>, </script> tag.</li><li>Loading CSS via <link rel="stylesheet" href="..."> tag.</li><li>Loading image via tag.</li><li>Others, such as <a>, <video>, <audio>, <object>, <embed>, <applet>, <frame> and <iframe>.</li> </ul><h5>JSONP</h5><p>You can send a cross-site request to a JSONP-enabled website via the <script> tag as follows:</p><script src="http://www.anotherdomain.com/hello.json?callback=mycallback"></script><p>With JSON, the server returns a JSON string (e.g., {"foo": "bar"} ), which will be evaluated and produce nothing.</p><p>Under JSONP, the server is supposed to wrap the JSON object under the callback function provided in the request parameter. That is,</p>mycallback({"foo": "bar"});<p>You can then write your callback function to perform your operations, e.g.,</p>function mycallback(data) { console.log(data.foo); }<p>Hence, when the script is loaded, it'll be evaluated, and your function will be executed - as a cross-domain request!</p><p>With JSONP, it is entirely up to your server to decide whether to support cross-domain request by padding the JSON response.</p><h4>Cross-Origin Resource Sharing (CORS)</h4><p>CORS is the latest W3C standard for cross-domain request, carried out via special HTTP headers.</p><ol><li>The browser sends the request with an Origin HTTP header, e.g., Origin: http://www.anotherdomain.com </li><li>The cross-domain server may response with: <ol><li>An Access-Control-Allow-Origin (ACAO) response header indicating which origin sites are allowed. For example, Access-Control-Allow-Origin: http://www.originaldomain.com</li><li>An Access-Control-Allow-Origin (ACAO) header with a wildcard that allows all domains: Access-Control-Allow-Origin: *</li><li>An error page if the server does not allow the cross-origin request.</li></ol></li></ol><p>With CORS, it is entirely up to your server to decide whether to support cross-domain request (similar to JSONP).</p><h3 id="miscellaneous">Miscellaneous</h3><h4>Task Scheduling via Timeout</h4><p>Two methods, setTimeout(codes, milliseconds) and clearTimeout(timeoutName) are provided to schedule a piece of codes to be executed after a specified milliseconds.</p>var task = setTimeout("alert('Hello')", 10000);<p>The variable task permits you to cancel the scheduled time event before timeout if desires:</p>cancelTimeout(task);<h4>Bitwise Operators</h4><p>JavaScript provides the following bitwise operators are provided for integers (same syntax as Java):</p> <table><tr><th>Operator</th><th>Description</th><th>Example</th><th>Result</th></tr><tr><td><< </td><td>Left bit-shift (padded with 0s) </td><td>bitPattern << number </td><td>  </td></tr><tr><td>>> </td><td>Signed right bit-shift (padded sign-bit) </td><td>bitPattern >> number </td><td>  </td></tr><tr><td>>>> </td><td>Unsigned right bit-shift (padded with 0s) </td><td>bitPattern >>> number </td><td>  </td></tr><tr><td>& </td><td>Bitwise AND </td><td>bitPattern1 & bitPattern2 </td><td>  </td></tr><tr><td>| </td><td>Bitwise OR </td><td>bitPattern1 | bitPattern2 </td><td>  </td></tr><tr><td>~ </td><td>Bitwise NOT (1's compliment) </td><td>~bitPattern </td><td>  </td></tr><tr><td>^ </td><td>Bitwise XOR </td><td>bitPattern1 ^ bitPattern2 </td><td>  </td></tr></table><p>Similarly, the following bitwise operation cum assignment operators are provided: <<=, >>=, >>>=, &=, |=, ^=.</p><h4>Operator Precedence</h4> <table><tr><th>Operator Name</th><th>Operator</th></tr><tr><td>Parentheses, Array index, Dot </td><td>() [] . </td></tr><tr><td>Negation, Increment/Decrement </td><td>! ~ - ++ -- </td></tr><tr><td>Multiply, Divide, Modulus </td><td>* / % </td></tr><tr><td>Addition, Subtraction </td><td>+ - </td></tr><tr><td>Bitwise Shift </td><td><< >> >>> </td></tr><tr><td>Relational </td><td>< <= > >= </td></tr><tr><td>Equality </td><td>== != </td></tr><tr><td>Bitwise AND </td><td>& </td></tr><tr><td>Bitwise XOR </td><td>^ </td></tr><tr><td>Bitwise OR </td><td>| </td></tr><tr><td>Logical AND </td><td>&& </td></tr><tr><td>Logical OR </td><td>|| </td></tr><tr><td>Ternary (Shorthand if-else) </td><td>? : </td></tr><tr><td>Assignment </td><td>= += -= *= /= %= </td></tr><tr><td>Comma (separate parameters) </td><td>, </td></tr></table><h4>Exception Handling: try-catch-finally and throw</h4><h5>throw</h5><p>Use throw to throw an exception as follows:</p>throw expression<p>In JavaScript, throw can throw any types: primitive (string, number, boolean) or object.</p><h5>try-catch-finally</h5><p>The syntax is:</p>try { try-block; } catch (e) { catch-block; } finally { finally-block; }<p>Execution begins at the try-block. If none of the statements in the try-block throws an exception, the catch-block is skipped.</p><p>However, if one of the statement in the try-block throw an exception, the rest of the statements in the try-block is skipped, and execution branches to the catch-block to process the exception. In JavaScript, there is only one catch-block, which catches all the exceptions.</p><p>The optional finally-block is always executed, after try or catch, for performing house keeping task, such as closing the files. The program will continue into the next statement, if it is not terminated.</p><p>The try-catch-finally construct has the following benefits:</p><ol><li>Separating of exception handling logic from the main logic. You do not need to use many if-else in the main logic to check for exception.</li><li>Allow graceful termination of the program, handled by the catch-block.</li><li>....</li></ol><p>Example [TODO]</p><h4>Execute JavaScript Statement from Browser's Address Bar</h4><p>You can issue You can execute JavaScript from Firefox's navigator toolbar or Internet Explorer's address bar, via pseudo-protocol javascript:statement. For example,</p>javascript:alert('Hello'); javascript:alert(document.title);alert('Hello, again') javascript:document.title<p>The statement can access variables and objects on the current document.</p><p>The JavaScript statement used in a javascript: URL should not return any value. For example, alert() does not return a value (or returns undefined). If it returns an explicit value, the browser loads a new page and places the returned value in the body of the page.</p><p>You can use the void operator to stay in the same page. void evaluates its expression, and returns undefined. For example,</p>javascript:void(x=5)<p>You can bookmark the javascript statement (someone called them bookmarklets). For example, you can write a bookmarklet to change the background color of a web page, so that the web page is easier to read.</p>javascript:void(document.body.style.background='#FFF');<h4>Nested Functions and Closure</h4><p>You can nest a function inside a function. The inner function has access to all the properties of the outer function. This becomes complicated if the inner function is returned by the outer function. If multiple calls is made to the outer function, which creates different copies of the inner function, what are the value of the properties of the outer function?</p><p>For example,</p>function outer(x) { let y = 8; let addToOuter = function (z) { console.log('x:' + x + ' y:' + y + ' z:' + z); return x + y + z; }; return addToOuter; } var f1 = outer(3); console.log('sum:' + f1(10)); <span>//x:3 y:8 z:10 //sum: 21</span> console.log('sum:' + f1(20)); <span>//x: 3 y: 8 z: 20 //sum: 31</span> var f2 = outer(9); console.log('sum:' + f2(30)); <span>//x:9 y:8 z:30 //sum: 47</span> console.log('sum:' + f2(40)); <span>//x:9 y:8 z:40 //sum: 57</span> <p>Each invocation of the outer function creates a so-called closure, which is the inner function with a set of variables together with an environment that binds those variables.</p><p>As seen from the above example, the value of x and y in the outer function remains the same for each invocation, in the return inner function. However, each invocation create a new closure with its set of values. A closure is similar to an object instance where the variables' value are already fixed.</p><p>Link To JavaScript/jQuery References & Resources</p><div class='paramage'></div> <div class="contenBreak"></div> <h3 id="which-programing-language-is-used-within-html-documents-to-trigger-interactive-features">Which programing language is used within HTML documents to trigger interactive features?</h3> <div class="blockAnswer_acceptedAnswer"><span class="FCUp0c rQMQod">JavaScript</span> is a programming language mostly used client-side to make webpages interactive.</div> <h3 id="which-of-the-following-are-files-inserted-into-an-html-document-that-control-the-appearance-of-web-pages-including-layout-colors-and-fonts-quizlet">Which of the following are files inserted into an HTML document that control the appearance of web pages including layout colors and fonts quizlet?</h3> <div class="blockAnswer_acceptedAnswer"><span class="FCUp0c rQMQod">Cascading Style Sheets (CSS)</span> are files inserted into an HTML document that control the appearance of web pages including layout, colors, and fonts.</div> <h3 id="what-is-javascript-for-quizlet">What is JavaScript for quizlet?</h3> <div class="blockAnswer_acceptedAnswer">A scripting programming language of the web, invented for the web, run client side by web browsers, that <span class="FCUp0c rQMQod">adds interactivity to a web page</span>. JavaScript is a language that works with and manipulates web pages.</div> <h3 id="what-type-of-email-account-is-more-widely-used">What type of email account is more widely used?</h3> <div class="blockAnswer_acceptedAnswer">Gmail. <span class="FCUp0c rQMQod">Gmail by Google</span> is one of the most popular web clients for email because it's free and easy to use.</div> </p></div> <div class="readmore_content_exists"><button id="readmore_content"><span class="arrow"><span></span></span>Đọc tiếp</button></div> </td></tr></table> <script async src="/dist/js/lazyhtml.min.js" crossorigin="anonymous"></script> <div class="lazyhtml" data-lazyhtml> <script type="text/lazyhtml"> <div class="youtubeVideo"><h3>Video liên quan</h3> <iframe width="560" height="315" src="https://www.youtube.com/embed/eI0jZpLOZME?controls=0" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"allowfullscreen></iframe> </div> </script> </div> <div class="mt-3"> <div class="tags"> </div> </div> <div class="post-tools"> <button data-postid="javascript-is-a-language-often-used-within-html-documents-to-trigger-interactive-features" class="btn btn-answerModalBox"><img class="mr-1" alt="Javascript is a language often used within html documents to trigger interactive features." src="/dist/images/svg/messages_16.svg">Reply</button> <button data-postid="javascript-is-a-language-often-used-within-html-documents-to-trigger-interactive-features" data-vote="up" class="btn btn-doVote"><img class="mr-1" alt="Javascript is a language often used within html documents to trigger interactive features." src="/dist/images/svg/face-smile_16.svg">5</button> <button data-postid="javascript-is-a-language-often-used-within-html-documents-to-trigger-interactive-features" data-vote="down" class="btn btn-doVote"><img class="mr-1" alt="Javascript is a language often used within html documents to trigger interactive features." src="/dist/images/svg/poo_16.svg">0</button> <button class="btn"><img class="mr-1" alt="Javascript is a language often used within html documents to trigger interactive features." src="/dist/images/svg/facebook_16.svg"> Chia sẻ</button> </div> </div><!-- end question-post-body --> </div><!-- end question-post-body-wrap --> </div><!-- end question --> <div id="answers_javascript-is-a-language-often-used-within-html-documents-to-trigger-interactive-features" class="answers"> </div><!-- end answer-wrap --> <div class="entryFooter"> <div class="footerLinkAds"><div style="width:100%; margin:0 auto;"> <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-4987931798153631" data-ad-slot="8199996671"></ins> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script> </div> </div> <div class="footerRelated"><div class="postRelatedWidget"> <h2>Bài Viết Liên Quan</h2> <div class="questions-snippet layoutNews border-top border-top-gray"> <div class="max-width:840px"> <ins class="adsbygoogle" style="display:block" data-ad-format="fluid" data-ad-layout-key="-fb-44+c1-1p-ns" data-ad-client="ca-pub-4987931798153631" data-ad-slot="7655066491"></ins> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script> </div> <div class="media media-card rounded-0 shadow-none mb-0 bg-transparent py-4 px-0 border-bottom border-bottom-gray"> <div class="media-image"> <a href="/luoi-co-mau-den-la-benh-gi-nam-2024"><img src="/dist/images/waiting.svg" width="200px" height="100px" data-orgimg="https://i.ytimg.com/vi/BkvH_eA5B78/hq720.jpg?sqp=-oaymwExCNAFEJQDSFryq4qpAyMIARUAAIhCGAHwAQH4Af4JgALQBYoCDAgAEAEYZSBKKEMwDw==&rs=AOn4CLD8-b0B8DxnGTY_lnWU02eGxxJIQQ" alt="Lưỡi có màu đen là bệnh gì năm 2024"></a> </div> <div class="media-body"> <h5 class="mb-2 fw-medium"><a href="/luoi-co-mau-den-la-benh-gi-nam-2024">Lưỡi có màu đen là bệnh gì năm 2024</a></h5> <p class="mb-2 truncate lh-20 fs-15"></p> <div class="media media-card questionTags user-media px-0 border-bottom-0 pb-0"> <div class="tags"> <a href="/tags/là ai" class="tag-link">là ai</a> </div> </div> </div> </div><!-- end media --> <div class="media media-card rounded-0 shadow-none mb-0 bg-transparent py-4 px-0 border-bottom border-bottom-gray"> <div class="media-image"> <a href="/giai-vo-bai-tap-ngu-van-lop-8-nam-2024"><img src="/dist/images/waiting.svg" width="200px" height="100px" data-orgimg="https://i.ytimg.com/vi/0oG3JCjFX5o/hq720.jpg?sqp=-oaymwEXCNAFEJQDSFryq4qpAwkIARUAAIhCGAE=&rs=AOn4CLC4P7pTJxPU8NusYr_2h3J4uEL56g" alt="Giải vở bài tập ngữ văn lớp 8 năm 2024"></a> </div> <div class="media-body"> <h5 class="mb-2 fw-medium"><a href="/giai-vo-bai-tap-ngu-van-lop-8-nam-2024">Giải vở bài tập ngữ văn lớp 8 năm 2024</a></h5> <p class="mb-2 truncate lh-20 fs-15"></p> <div class="media media-card questionTags user-media px-0 border-bottom-0 pb-0"> <div class="tags"> <a href="/tags/mẹo hay" class="tag-link">mẹo hay</a> <a href="/tags/Khỏe Đẹp" class="tag-link">Khỏe Đẹp</a> <a href="/tags/Bài tập" class="tag-link">Bài tập</a> </div> </div> </div> </div><!-- end media --> <div class="media media-card rounded-0 shadow-none mb-0 bg-transparent py-4 px-0 border-bottom border-bottom-gray"> <div class="media-image"> <a href="/giay-phep-hanh-nghe-y-tieng-anh-la-gi-nam-2024"><img src="/dist/images/waiting.svg" width="200px" height="100px" data-orgimg="https://i.ytimg.com/vi/Ttxi6LHzq_4/hq720.jpg?sqp=-oaymwExCNAFEJQDSFryq4qpAyMIARUAAIhCGAHwAQH4Af4JgALQBYoCDAgAEAEYViBcKGUwDw==&rs=AOn4CLCFDtIuNKq2HX4AfSbIJBqxFktA3A" alt="Giấy phép hành nghề y tiếng anh là gì năm 2024"></a> </div> <div class="media-body"> <h5 class="mb-2 fw-medium"><a href="/giay-phep-hanh-nghe-y-tieng-anh-la-gi-nam-2024">Giấy phép hành nghề y tiếng anh là gì năm 2024</a></h5> <p class="mb-2 truncate lh-20 fs-15"></p> <div class="media media-card questionTags user-media px-0 border-bottom-0 pb-0"> <div class="tags"> <a href="/tags/là ai" class="tag-link">là ai</a> <a href="/tags/Hỏi Đáp" class="tag-link">Hỏi Đáp</a> <a href="/tags/Là gì" class="tag-link">Là gì</a> <a href="/tags/Học Tốt" class="tag-link">Học Tốt</a> <a href="/tags/Tiếng anh" class="tag-link">Tiếng anh</a> </div> </div> </div> </div><!-- end media --> <div class="media media-card rounded-0 shadow-none mb-0 bg-transparent py-4 px-0 border-bottom border-bottom-gray"> <div class="media-image"> <a href="/giai-de-thi-chuyen-toan-vao-lop-10-nam-2024"><img src="/dist/images/waiting.svg" width="200px" height="100px" data-orgimg="https://i.ytimg.com/vi/FOQLMnHCcbU/hq720.jpg?sqp=-oaymwExCNAFEJQDSFryq4qpAyMIARUAAIhCGAHwAQH4Af4JgALQBYoCDAgAEAEYOiBlKFkwDw==&rs=AOn4CLB4YpK24XgC_REWsvZZJGsNg0e5Nw" alt="Giải đề thi chuyên toán vào lớp 10 năm 2024"></a> </div> <div class="media-body"> <h5 class="mb-2 fw-medium"><a href="/giai-de-thi-chuyen-toan-vao-lop-10-nam-2024">Giải đề thi chuyên toán vào lớp 10 năm 2024</a></h5> <p class="mb-2 truncate lh-20 fs-15"></p> <div class="media media-card questionTags user-media px-0 border-bottom-0 pb-0"> <div class="tags"> <a href="/tags/mẹo hay" class="tag-link">mẹo hay</a> </div> </div> </div> </div><!-- end media --> <div class="media media-card rounded-0 shadow-none mb-0 bg-transparent py-4 px-0 border-bottom border-bottom-gray"> <div class="media-image"> <a href="/top-nhung-quoc-gia-gop-cong-vao-nhan-loai-nam-2024"><img src="/dist/images/waiting.svg" width="200px" height="100px" data-orgimg="https://i.ytimg.com/vi/6xpLoQciAUE/hq720.jpg?sqp=-oaymwEXCNAFEJQDSFryq4qpAwkIARUAAIhCGAE=&rs=AOn4CLC1FZjYqh0exl8jjSQpcOrSsu33Lw" alt="Top nhung quoc gia gop cong vao nhan loai năm 2024"></a> </div> <div class="media-body"> <h5 class="mb-2 fw-medium"><a href="/top-nhung-quoc-gia-gop-cong-vao-nhan-loai-nam-2024">Top nhung quoc gia gop cong vao nhan loai năm 2024</a></h5> <p class="mb-2 truncate lh-20 fs-15"></p> <div class="media media-card questionTags user-media px-0 border-bottom-0 pb-0"> <div class="tags"> <a href="/tags/mẹo hay" class="tag-link">mẹo hay</a> <a href="/tags/Top List" class="tag-link">Top List</a> <a href="/tags/Top" class="tag-link">Top</a> </div> </div> </div> </div><!-- end media --> <div class="media media-card rounded-0 shadow-none mb-0 bg-transparent py-4 px-0 border-bottom border-bottom-gray"> <div class="media-image"> <a href="/hieu-ung-tron-bon-buoc-song-fwm-la-gi-nam-2024"><img src="/dist/images/waiting.svg" width="200px" height="100px" data-orgimg="https://i.ytimg.com/vi/jrHa4xU2vqw/hq720.jpg?sqp=-oaymwExCNAFEJQDSFryq4qpAyMIARUAAIhCGAHwAQH4AZQDgALQBYoCDAgAEAEYZSBcKFgwDw==&rs=AOn4CLAi8kR4LOzQrc_WDf8s-GJmphQ3tg" alt="Hiệu ứng trộn bốn bước sóng fwm là gì năm 2024"></a> </div> <div class="media-body"> <h5 class="mb-2 fw-medium"><a href="/hieu-ung-tron-bon-buoc-song-fwm-la-gi-nam-2024">Hiệu ứng trộn bốn bước sóng fwm là gì năm 2024</a></h5> <p class="mb-2 truncate lh-20 fs-15"></p> <div class="media media-card questionTags user-media px-0 border-bottom-0 pb-0"> <div class="tags"> <a href="/tags/là ai" class="tag-link">là ai</a> <a href="/tags/Hỏi Đáp" class="tag-link">Hỏi Đáp</a> <a href="/tags/Là gì" class="tag-link">Là gì</a> </div> </div> </div> </div><!-- end media --> <div class="media media-card rounded-0 shadow-none mb-0 bg-transparent py-4 px-0 border-bottom border-bottom-gray"> <div class="media-image"> <a href="/quy-dinh-cach-ghi-don-vi-tren-nhan-hang-hoa-nam-2024"><img src="/dist/images/waiting.svg" width="200px" height="100px" data-orgimg="https://i.ytimg.com/vi/yOfT80c-_ik/hq720.jpg?sqp=-oaymwEXCNAFEJQDSFryq4qpAwkIARUAAIhCGAE=&rs=AOn4CLB9sGacXJHdi7Aiihx9KfRZ14FUxg" alt="Quy định cách ghi don vi tren nhãn hàng hóa năm 2024"></a> </div> <div class="media-body"> <h5 class="mb-2 fw-medium"><a href="/quy-dinh-cach-ghi-don-vi-tren-nhan-hang-hoa-nam-2024">Quy định cách ghi don vi tren nhãn hàng hóa năm 2024</a></h5> <p class="mb-2 truncate lh-20 fs-15"></p> <div class="media media-card questionTags user-media px-0 border-bottom-0 pb-0"> <div class="tags"> <a href="/tags/mẹo hay" class="tag-link">mẹo hay</a> <a href="/tags/Mẹo Hay" class="tag-link">Mẹo Hay</a> <a href="/tags/Cách" class="tag-link">Cách</a> </div> </div> </div> </div><!-- end media --> <div class="media media-card rounded-0 shadow-none mb-0 bg-transparent py-4 px-0 border-bottom border-bottom-gray"> <div class="media-image"> <a href="/de-thi-thu-mon-toan-tinh-bac-ninh-nam-2024"><img src="/dist/images/waiting.svg" width="200px" height="100px" data-orgimg="https://i.ytimg.com/vi/c5IFwyEw79s/hqdefault.jpg?sqp=-oaymwEjCOADEI4CSFryq4qpAxUIARUAAAAAGAElAADIQj0AgKJDeAE=&rs=AOn4CLD5-Ej6pDQE_Gi7UwQ4D92ycB_h6Q" alt="Đề thi thử môn toán tỉnh bắc ninh năm 2024"></a> </div> <div class="media-body"> <h5 class="mb-2 fw-medium"><a href="/de-thi-thu-mon-toan-tinh-bac-ninh-nam-2024">Đề thi thử môn toán tỉnh bắc ninh năm 2024</a></h5> <p class="mb-2 truncate lh-20 fs-15"></p> <div class="media media-card questionTags user-media px-0 border-bottom-0 pb-0"> <div class="tags"> <a href="/tags/mẹo hay" class="tag-link">mẹo hay</a> </div> </div> </div> </div><!-- end media --> <div class="media media-card rounded-0 shadow-none mb-0 bg-transparent py-4 px-0 border-bottom border-bottom-gray"> <div class="media-image"> <a href="/ke-tam-lang-nguoi-nua-can-la-gi-nam-2024"><img src="/dist/images/waiting.svg" width="200px" height="100px" data-orgimg="https://i.ytimg.com/vi/4NxUYehTBI4/hq720.jpg?sqp=-oaymwExCNAFEJQDSFryq4qpAyMIARUAAIhCGAHwAQH4Af4JgALQBYoCDAgAEAEYZSBYKEQwDw==&rs=AOn4CLDOfCt-3y7SaGLGKXPQp-3DPVH1TQ" alt="Kẻ tám lạng người nửa cân là gì năm 2024"></a> </div> <div class="media-body"> <h5 class="mb-2 fw-medium"><a href="/ke-tam-lang-nguoi-nua-can-la-gi-nam-2024">Kẻ tám lạng người nửa cân là gì năm 2024</a></h5> <p class="mb-2 truncate lh-20 fs-15"></p> <div class="media media-card questionTags user-media px-0 border-bottom-0 pb-0"> <div class="tags"> <a href="/tags/là ai" class="tag-link">là ai</a> <a href="/tags/Hỏi Đáp" class="tag-link">Hỏi Đáp</a> <a href="/tags/Là gì" class="tag-link">Là gì</a> </div> </div> </div> </div><!-- end media --> <div class="media media-card rounded-0 shadow-none mb-0 bg-transparent py-4 px-0 border-bottom border-bottom-gray"> <div class="media-image"> <a href="/hinh-chieu-dung-co-huong-chieu-nhu-the-nao-nam-2024"><img src="/dist/images/waiting.svg" width="200px" height="100px" data-orgimg="https://i.ytimg.com/vi/v0pcbUmEykM/hqdefault.jpg?sqp=-oaymwEjCOADEI4CSFryq4qpAxUIARUAAAAAGAElAADIQj0AgKJDeAE=&rs=AOn4CLDpEnlKoPuRWA1hTp3w6lbmwVCG4g" alt="Hình chiếu đứng có hướng chiếu như thế nào năm 2024"></a> </div> <div class="media-body"> <h5 class="mb-2 fw-medium"><a href="/hinh-chieu-dung-co-huong-chieu-nhu-the-nao-nam-2024">Hình chiếu đứng có hướng chiếu như thế nào năm 2024</a></h5> <p class="mb-2 truncate lh-20 fs-15"></p> <div class="media media-card questionTags user-media px-0 border-bottom-0 pb-0"> <div class="tags"> <a href="/tags/mẹo hay" class="tag-link">mẹo hay</a> <a href="/tags/Hỏi Đáp" class="tag-link">Hỏi Đáp</a> <a href="/tags/Thế nào" class="tag-link">Thế nào</a> </div> </div> </div> </div><!-- end media --> <div class="max-width:840px"> <ins class="adsbygoogle" style="display:block" data-ad-format="fluid" data-ad-layout-key="-fb-44+c1-1p-ns" data-ad-client="ca-pub-4987931798153631" data-ad-slot="7655066491"></ins> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script> </div> <div class="media media-card rounded-0 shadow-none mb-0 bg-transparent py-4 px-0 border-bottom border-bottom-gray"> <div class="media-image"> <a href="/truong-trung-hoc-co-so-binh-dinh-nam-2024"><img src="/dist/images/waiting.svg" width="200px" height="100px" data-orgimg="https://i.ytimg.com/vi/-aWG-YdnJbQ/hq720.jpg?sqp=-oaymwEXCNAFEJQDSFryq4qpAwkIARUAAIhCGAE=&rs=AOn4CLDk2I-3XWi5HlSVrgkCcR26Lhl0JA" alt="Trường trung học cơ sở bình định năm 2024"></a> </div> <div class="media-body"> <h5 class="mb-2 fw-medium"><a href="/truong-trung-hoc-co-so-binh-dinh-nam-2024">Trường trung học cơ sở bình định năm 2024</a></h5> <p class="mb-2 truncate lh-20 fs-15"></p> <div class="media media-card questionTags user-media px-0 border-bottom-0 pb-0"> <div class="tags"> <a href="/tags/mẹo hay" class="tag-link">mẹo hay</a> <a href="/tags/Học Tốt" class="tag-link">Học Tốt</a> <a href="/tags/Học" class="tag-link">Học</a> <a href="/tags/Binhdinh vnedu" class="tag-link">Binhdinh vnedu</a> </div> </div> </div> </div><!-- end media --> <div class="media media-card rounded-0 shadow-none mb-0 bg-transparent py-4 px-0 border-bottom border-bottom-gray"> <div class="media-image"> <a href="/mau-bang-thanh-toan-luong-theo-quyet-dinh-48-nam-2024"><img src="/dist/images/waiting.svg" width="200px" height="100px" data-orgimg="https://i.ytimg.com/vi/_xJZtWmVme8/hq720.jpg?sqp=-oaymwEXCNAFEJQDSFryq4qpAwkIARUAAIhCGAE=&rs=AOn4CLB3jq6kYSU8CFemfS1Lv24oau8U3Q" alt="Mẫu bảng thanh toán lương theo quyết định 48 năm 2024"></a> </div> <div class="media-body"> <h5 class="mb-2 fw-medium"><a href="/mau-bang-thanh-toan-luong-theo-quyet-dinh-48-nam-2024">Mẫu bảng thanh toán lương theo quyết định 48 năm 2024</a></h5> <p class="mb-2 truncate lh-20 fs-15"></p> <div class="media media-card questionTags user-media px-0 border-bottom-0 pb-0"> <div class="tags"> <a href="/tags/mẹo hay" class="tag-link">mẹo hay</a> <a href="/tags/Bảng tính tiền" class="tag-link">Bảng tính tiền</a> </div> </div> </div> </div><!-- end media --> <div class="media media-card rounded-0 shadow-none mb-0 bg-transparent py-4 px-0 border-bottom border-bottom-gray"> <div class="media-image"> <a href="/xuat-huyet-cuc-duoi-tui-thai-la-gi-nam-2024"><img src="/dist/images/waiting.svg" width="200px" height="100px" data-orgimg="https://i.ytimg.com/vi/KmgVpZLpRjo/hq720.jpg?sqp=-oaymwExCNAFEJQDSFryq4qpAyMIARUAAIhCGAHwAQH4Ae4CgALQBYoCDAgAEAEYZSBiKFkwDw==&rs=AOn4CLDbLCVnLmoukgh3IDn8ZtvlZgr0lQ" alt="Xuất huyết cực dưới túi thai là gì năm 2024"></a> </div> <div class="media-body"> <h5 class="mb-2 fw-medium"><a href="/xuat-huyet-cuc-duoi-tui-thai-la-gi-nam-2024">Xuất huyết cực dưới túi thai là gì năm 2024</a></h5> <p class="mb-2 truncate lh-20 fs-15"></p> <div class="media media-card questionTags user-media px-0 border-bottom-0 pb-0"> <div class="tags"> <a href="/tags/là ai" class="tag-link">là ai</a> <a href="/tags/Hỏi Đáp" class="tag-link">Hỏi Đáp</a> <a href="/tags/Là gì" class="tag-link">Là gì</a> </div> </div> </div> </div><!-- end media --> <div class="media media-card rounded-0 shadow-none mb-0 bg-transparent py-4 px-0 border-bottom border-bottom-gray"> <div class="media-image"> <a href="/bieu-hien-cua-tu-lap-la-gi-nam-2024"><img src="/dist/images/waiting.svg" width="200px" height="100px" data-orgimg="https://i.ytimg.com/vi/7HK8JGN9XVY/hq720.jpg?sqp=-oaymwExCNAFEJQDSFryq4qpAyMIARUAAIhCGAHwAQH4Af4JgALQBYoCDAgAEAEYLCBVKH8wDw==&rs=AOn4CLAhSCOMKC2Sy1WYD0jh7Kk5kaI0OA" alt="Biểu hiện của tự lập là gì năm 2024"></a> </div> <div class="media-body"> <h5 class="mb-2 fw-medium"><a href="/bieu-hien-cua-tu-lap-la-gi-nam-2024">Biểu hiện của tự lập là gì năm 2024</a></h5> <p class="mb-2 truncate lh-20 fs-15"></p> <div class="media media-card questionTags user-media px-0 border-bottom-0 pb-0"> <div class="tags"> <a href="/tags/là ai" class="tag-link">là ai</a> <a href="/tags/Hỏi Đáp" class="tag-link">Hỏi Đáp</a> <a href="/tags/Là gì" class="tag-link">Là gì</a> </div> </div> </div> </div><!-- end media --> <div class="media media-card rounded-0 shadow-none mb-0 bg-transparent py-4 px-0 border-bottom border-bottom-gray"> <div class="media-image"> <a href="/cua-hang-hoa-chat-dung-cu-thi-nghiem-nam-2024"><img src="/dist/images/waiting.svg" width="200px" height="100px" data-orgimg="https://i.ytimg.com/vi/iQYaBBKZLZQ/hqdefault.jpg?sqp=-oaymwEjCOADEI4CSFryq4qpAxUIARUAAAAAGAElAADIQj0AgKJDeAE=&rs=AOn4CLACXUi2nqnqtmJvsUumFHQFJZUhSA" alt="Cửa hàng hóa chất dụng cụ thí nghiệm năm 2024"></a> </div> <div class="media-body"> <h5 class="mb-2 fw-medium"><a href="/cua-hang-hoa-chat-dung-cu-thi-nghiem-nam-2024">Cửa hàng hóa chất dụng cụ thí nghiệm năm 2024</a></h5> <p class="mb-2 truncate lh-20 fs-15"></p> <div class="media media-card questionTags user-media px-0 border-bottom-0 pb-0"> <div class="tags"> <a href="/tags/mẹo hay" class="tag-link">mẹo hay</a> </div> </div> </div> </div><!-- end media --> <div class="media media-card rounded-0 shadow-none mb-0 bg-transparent py-4 px-0 border-bottom border-bottom-gray"> <div class="media-image"> <a href="/bai-tap-giao-trinh-han-ngu-quyen-2-pdf-nam-2024"><img src="/dist/images/waiting.svg" width="200px" height="100px" data-orgimg="https://i.ytimg.com/vi/ots-MLtBxxg/hq720.jpg?sqp=-oaymwExCNAFEJQDSFryq4qpAyMIARUAAIhCGAHwAQH4Af4JgALQBYoCDAgAEAEYICBbKH8wDw==&rs=AOn4CLCvWDv10aCgqRW2ALFQDAgrdRwT5g" alt="Bài tập giáo trình hán ngữ quyển 2 pdf năm 2024"></a> </div> <div class="media-body"> <h5 class="mb-2 fw-medium"><a href="/bai-tap-giao-trinh-han-ngu-quyen-2-pdf-nam-2024">Bài tập giáo trình hán ngữ quyển 2 pdf năm 2024</a></h5> <p class="mb-2 truncate lh-20 fs-15"></p> <div class="media media-card questionTags user-media px-0 border-bottom-0 pb-0"> <div class="tags"> <a href="/tags/mẹo hay" class="tag-link">mẹo hay</a> <a href="/tags/Khỏe Đẹp" class="tag-link">Khỏe Đẹp</a> <a href="/tags/Bài tập" class="tag-link">Bài tập</a> </div> </div> </div> </div><!-- end media --> <div class="media media-card rounded-0 shadow-none mb-0 bg-transparent py-4 px-0 border-bottom border-bottom-gray"> <div class="media-image"> <a href="/gia-tri-mac-dinh-cua-phuong-thuc-setdefaultcloseoperation-la-gi-nam-2024"><img src="/dist/images/waiting.svg" width="200px" height="100px" data-orgimg="https://i.ytimg.com/vi/SzcwjeKxjBk/hq720.jpg?sqp=-oaymwEXCNAFEJQDSFryq4qpAwkIARUAAIhCGAE=&rs=AOn4CLBDdL5-rnLzoSarQIFRMgY4XHkO3w" alt="Giá trị mặc định của phương thức setdefaultcloseoperation là gì năm 2024"></a> </div> <div class="media-body"> <h5 class="mb-2 fw-medium"><a href="/gia-tri-mac-dinh-cua-phuong-thuc-setdefaultcloseoperation-la-gi-nam-2024">Giá trị mặc định của phương thức setdefaultcloseoperation là gì năm 2024</a></h5> <p class="mb-2 truncate lh-20 fs-15"></p> <div class="media media-card questionTags user-media px-0 border-bottom-0 pb-0"> <div class="tags"> <a href="/tags/là ai" class="tag-link">là ai</a> <a href="/tags/Hỏi Đáp" class="tag-link">Hỏi Đáp</a> <a href="/tags/Là gì" class="tag-link">Là gì</a> <a href="/tags/Cryto" class="tag-link">Cryto</a> <a href="/tags/Giá " class="tag-link">Giá </a> <a href="/tags/setDefaultCloseOperation là gì?" class="tag-link">setDefaultCloseOperation là gì?</a> <a href="/tags/setLocationRelativeTo là gì?" class="tag-link">setLocationRelativeTo là gì?</a> <a href="/tags/Javax là gì" class="tag-link">Javax là gì</a> </div> </div> </div> </div><!-- end media --> <div class="media media-card rounded-0 shadow-none mb-0 bg-transparent py-4 px-0 border-bottom border-bottom-gray"> <div class="media-image"> <a href="/tap-lam-van-lop-3-tap-2-trang-11-nam-2024"><img src="/dist/images/waiting.svg" width="200px" height="100px" data-orgimg="https://i.ytimg.com/vi/Y7-vHci8-7Q/hq720.jpg?sqp=-oaymwExCNAFEJQDSFryq4qpAyMIARUAAIhCGAHwAQH4Af4JgALQBYoCDAgAEAEYfyA9KBMwDw==&rs=AOn4CLCLtSwETbDPtuhllkkNgRHfyXcDdg" alt="Tập làm văn lớp 3 tập 2 trang 11 năm 2024"></a> </div> <div class="media-body"> <h5 class="mb-2 fw-medium"><a href="/tap-lam-van-lop-3-tap-2-trang-11-nam-2024">Tập làm văn lớp 3 tập 2 trang 11 năm 2024</a></h5> <p class="mb-2 truncate lh-20 fs-15"></p> <div class="media media-card questionTags user-media px-0 border-bottom-0 pb-0"> <div class="tags"> <a href="/tags/mẹo hay" class="tag-link">mẹo hay</a> </div> </div> </div> </div><!-- end media --> <div class="media media-card rounded-0 shadow-none mb-0 bg-transparent py-4 px-0 border-bottom border-bottom-gray"> <div class="media-image"> <a href="/loi-0x00000000709-khi-dat-may-in-mac-dinh-nam-2024"><img src="/dist/images/waiting.svg" width="200px" height="100px" data-orgimg="https://i.ytimg.com/vi/gK45vWuC9hg/hq720.jpg?sqp=-oaymwEXCNAFEJQDSFryq4qpAwkIARUAAIhCGAE=&rs=AOn4CLCqF2HtNDSPVSeIeC_XvG5c_d6JYA" alt="Lỗi 0x00000000709 khi đặt máy in mặc định năm 2024"></a> </div> <div class="media-body"> <h5 class="mb-2 fw-medium"><a href="/loi-0x00000000709-khi-dat-may-in-mac-dinh-nam-2024">Lỗi 0x00000000709 khi đặt máy in mặc định năm 2024</a></h5> <p class="mb-2 truncate lh-20 fs-15"></p> <div class="media media-card questionTags user-media px-0 border-bottom-0 pb-0"> <div class="tags"> <a href="/tags/mẹo hay" class="tag-link">mẹo hay</a> <a href="/tags/Công Nghệ" class="tag-link">Công Nghệ</a> <a href="/tags/Máy" class="tag-link">Máy</a> </div> </div> </div> </div><!-- end media --> <div class="media media-card rounded-0 shadow-none mb-0 bg-transparent py-4 px-0 border-bottom border-bottom-gray"> <div class="media-image"> <a href="/hat-xam-ha-noi-36-pho-phuong-la-gi-nam-2024"><img src="/dist/images/waiting.svg" width="200px" height="100px" data-orgimg="https://i.ytimg.com/vi/DBKWSFqU7HU/hq720.jpg?sqp=-oaymwEXCNAFEJQDSFryq4qpAwkIARUAAIhCGAE=&rs=AOn4CLC4TzDrsrCK3scsfkcj7xHwlHDdgw" alt="Hát xẩm hà nội 36 phố phường là gì năm 2024"></a> </div> <div class="media-body"> <h5 class="mb-2 fw-medium"><a href="/hat-xam-ha-noi-36-pho-phuong-la-gi-nam-2024">Hát xẩm hà nội 36 phố phường là gì năm 2024</a></h5> <p class="mb-2 truncate lh-20 fs-15"></p> <div class="media media-card questionTags user-media px-0 border-bottom-0 pb-0"> <div class="tags"> <a href="/tags/là ai" class="tag-link">là ai</a> <a href="/tags/Hỏi Đáp" class="tag-link">Hỏi Đáp</a> <a href="/tags/Là gì" class="tag-link">Là gì</a> </div> </div> </div> </div><!-- end media --> </div> </div></div> </div> </div> </div><!-- end question-main-bar --> </div><!-- end col-lg-9 --> <div class="postContentRight"> <div class="sidebar"> <div class="ad-card"> <h4 class="text-gray text-uppercase fs-13 pb-3 text-center">Quảng Cáo</h4> <div class="mb-4 mx-auto" style="text-align:center"> <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-4987931798153631" data-ad-slot="8742637402" data-ad-format="auto" data-full-width-responsive="true"> </ins> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script> </div> </div> <div class="card card-item"> <div class="card-body"> <h3 class="fs-17 pb-3">Có thể bạn quan tâm</h3> <div class="divider"><span></span></div> <div class="sidebar-questions pt-3"> <div class="media media-card media--card media--card-2"> <div class="media-body"> <h5><a href="https://hoidapvui.com/giai-toan-lop-5-trang-18-bai-2-nam-2024">Giải toán lớp 5 trang 18 bài 2 năm 2024</a></h5> <small class="meta"> <span class="pr-1">5 ngày trước</span> <span class="pr-1">. bởi</span> <a href="https://hoidapvui.com/author/FledglingGrouping" class="author">FledglingGrouping</a> </small> </div> </div><!-- end media --> <div class="media media-card media--card media--card-2"> <div class="media-body"> <h5><a href="https://hoidapvui.com/bai-kiem-tra-van-1-tiet-tieng-viet-lop-7-nam-2024">Bài kiểm tra văn 1 tiết tiếng việt lớp 7 năm 2024</a></h5> <small class="meta"> <span class="pr-1">5 ngày trước</span> <span class="pr-1">. bởi</span> <a href="https://hoidapvui.com/author/Empty-handedReviewer" class="author">Empty-handedReviewer</a> </small> </div> </div><!-- end media --> <div class="media media-card media--card media--card-2"> <div class="media-body"> <h5><a href="https://hoidapvui.com/bai-tap-ve-thuat-toan-liet-ke-pascal-nam-2024">Bai tập về thuật toán liệt kê pascal năm 2024</a></h5> <small class="meta"> <span class="pr-1">5 ngày trước</span> <span class="pr-1">. bởi</span> <a href="https://hoidapvui.com/author/MotleyMatrix" class="author">MotleyMatrix</a> </small> </div> </div><!-- end media --> <div class="media media-card media--card media--card-2"> <div class="media-body"> <h5><a href="https://hoidapvui.com/cong-nghe-mu-mimo-la-gi-nam-2024">Công nghệ mu mimo là gì năm 2024</a></h5> <small class="meta"> <span class="pr-1">5 ngày trước</span> <span class="pr-1">. bởi</span> <a href="https://hoidapvui.com/author/MaskedArchipelago" class="author">MaskedArchipelago</a> </small> </div> </div><!-- end media --> <div class="media media-card media--card media--card-2"> <div class="media-body"> <h5><a href="https://hoidapvui.com/cac-dang-bai-tap-hoa-10-va-cach-giai-nam-2024">Các dạng bài tập hóa 10 và cách giải năm 2024</a></h5> <small class="meta"> <span class="pr-1">5 ngày trước</span> <span class="pr-1">. bởi</span> <a href="https://hoidapvui.com/author/SadisticRefrigerator" class="author">SadisticRefrigerator</a> </small> </div> </div><!-- end media --> <div class="media media-card media--card media--card-2"> <div class="media-body"> <h5><a href="https://hoidapvui.com/bai-tap-the-duc-giup-tang-can-nhanh-nam-2024">Bài tập thể dục giúp tăng cân nhanh năm 2024</a></h5> <small class="meta"> <span class="pr-1">5 ngày trước</span> <span class="pr-1">. bởi</span> <a href="https://hoidapvui.com/author/YoungRanger" class="author">YoungRanger</a> </small> </div> </div><!-- end media --> <div class="media media-card media--card media--card-2"> <div class="media-body"> <h5><a href="https://hoidapvui.com/tong-hop-cac-loi-xu-phat-giao-thong-2023-nam-2024">Tổng hợp các lỗi xử phạt giao thông 2023 năm 2024</a></h5> <small class="meta"> <span class="pr-1">5 ngày trước</span> <span class="pr-1">. bởi</span> <a href="https://hoidapvui.com/author/CurtFiring" class="author">CurtFiring</a> </small> </div> </div><!-- end media --> <div class="media media-card media--card media--card-2"> <div class="media-body"> <h5><a href="https://hoidapvui.com/dau-sao-y-ban-chinh-tieng-anh-la-gi-nam-2024">Dấu sao y bản chính tiếng anh là gì năm 2024</a></h5> <small class="meta"> <span class="pr-1">5 ngày trước</span> <span class="pr-1">. bởi</span> <a href="https://hoidapvui.com/author/TerritorialFooting" class="author">TerritorialFooting</a> </small> </div> </div><!-- end media --> <div class="media media-card media--card media--card-2"> <div class="media-body"> <h5><a href="https://hoidapvui.com/cac-loi-khong-bat-dc-wifi-cua-laptop-nam-2024">Các lỗi không bắt đc wifi của laptop năm 2024</a></h5> <small class="meta"> <span class="pr-1">5 ngày trước</span> <span class="pr-1">. bởi</span> <a href="https://hoidapvui.com/author/WarmIndecency" class="author">WarmIndecency</a> </small> </div> </div><!-- end media --> <div class="media media-card media--card media--card-2"> <div class="media-body"> <h5><a href="https://hoidapvui.com/giai-toan-dai-so-hinh-hoc-luong-giac-10-nam-2024">_giải toán đại số hình học lượng giác 10 năm 2024</a></h5> <small class="meta"> <span class="pr-1">5 ngày trước</span> <span class="pr-1">. bởi</span> <a href="https://hoidapvui.com/author/DescriptiveMailing" class="author">DescriptiveMailing</a> </small> </div> </div><!-- end media --> </div><!-- end sidebar-questions --> </div> </div><!-- end card --> <div class="card card-item cardTopList"> <div class="card-body"> <h3 class="fs-17 pb-3">Toplist được quan tâm</h3> <div class="divider"><span></span></div> <div class="sidebar-questions pt-3"> <div class="media media-card media--card media--card-2"> <div class="topListNum">#1</div> <div class="media-body"> <h5><a href="https://hoidapvui.com/toplist-top-9-bai-tap-bo-tro-tieng-anh-lop-4-family-and-friends-2023">Top 9 bài tập bổ trợ tiếng anh lớp 4 family and friends 2023</a></h5> <small class="meta text-right">5 tháng trước</small> </div> </div><!-- end media --> <div class="media media-card media--card media--card-2"> <div class="topListNum">#2</div> <div class="media-body"> <h5><a href="https://hoidapvui.com/toplist-top-8-cac-loai-quyet-dinh-ca-biet-2023">Top 8 các loại quyết định cá biệt 2023</a></h5> <small class="meta text-right">5 tháng trước</small> </div> </div><!-- end media --> <div class="media media-card media--card media--card-2"> <div class="topListNum">#3</div> <div class="media-body"> <h5><a href="https://hoidapvui.com/toplist-top-9-xo-so-vung-tau-ngay-25-thang-2-2023">Top 9 xổ số vũng tàu ngày 25 tháng 2 2023</a></h5> <small class="meta text-right">5 tháng trước</small> </div> </div><!-- end media --> <div class="media media-card media--card media--card-2"> <div class="topListNum">#4</div> <div class="media-body"> <h5><a href="https://hoidapvui.com/toplist-top-2-tan-bang-phong-than-phan-2-tap-19-2023">Top 2 tân bảng phong thần phần 2 - tập 19 2023</a></h5> <small class="meta text-right">5 tháng trước</small> </div> </div><!-- end media --> <div class="media media-card media--card media--card-2"> <div class="topListNum">#5</div> <div class="media-body"> <h5><a href="https://hoidapvui.com/toplist-top-8-bieu-hien-cua-su-sang-tao-trong-cuoc-song-2023">Top 8 biểu hiện của sự sáng tạo trong cuộc sống 2023</a></h5> <small class="meta text-right">5 tháng trước</small> </div> </div><!-- end media --> <div class="media media-card media--card media--card-2"> <div class="topListNum">#6</div> <div class="media-body"> <h5><a href="https://hoidapvui.com/toplist-top-7-xet-hoc-ba-dai-hoc-giao-thong-van-tai-2023">Top 7 xét học bạ đại học giao thông vận tải 2023</a></h5> <small class="meta text-right">5 tháng trước</small> </div> </div><!-- end media --> <div class="media media-card media--card media--card-2"> <div class="topListNum">#7</div> <div class="media-body"> <h5><a href="https://hoidapvui.com/toplist-top-7-khu-vuc-khi-hau-gio-mua-chau-a-la-noi-phan-bo-cua-cac-canh-quan-2023">Top 7 khu vực khí hậu gió mùa châu á là nội phân bố của các cảnh quan 2023</a></h5> <small class="meta text-right">5 tháng trước</small> </div> </div><!-- end media --> <div class="media media-card media--card media--card-2"> <div class="topListNum">#8</div> <div class="media-body"> <h5><a href="https://hoidapvui.com/toplist-top-9-the-tich-khoi-lang-tru-khi-biet-dien-tich-day-s6-va-chieu-cao-h4-la-2023">Top 9 thể tích khối lăng trụ khi biết diện tích đáy s=6 và chiều cao h=4 là 2023</a></h5> <small class="meta text-right">5 tháng trước</small> </div> </div><!-- end media --> <div class="media media-card media--card media--card-2"> <div class="topListNum">#9</div> <div class="media-body"> <h5><a href="https://hoidapvui.com/toplist-top-8-anhchi-hay-nhan-xet-ve-quan-niem-day-ma-di-cua-tac-gia-qua-bai-tho-2023">Top 8 anh/chị hãy nhân xét về quan niệm dậy mà đi của tác giả qua bài thơ 2023</a></h5> <small class="meta text-right">5 tháng trước</small> </div> </div><!-- end media --> </div><!-- end sidebar-questions --> </div> </div><!-- end card --> <div class="ad-card"> <h4 class="text-gray text-uppercase fs-14 pb-3 pb-3 text-center">Quảng cáo</h4> <div class="mb-4 mx-auto"> <ins class="adsbygoogle" style="display:inline-block;width:300px;height:600px" data-ad-client="ca-pub-" data-ad-slot="" data-ad-format="auto" data-full-width-responsive="true"></ins> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script> </div> </div> <div class="card card-item"> <div class="card-body"> <h3 class="fs-17 pb-3">Xem Nhiều</h3> <div class="divider"><span></span></div> <div class="sidebar-questions pt-3"> <div class="media media-card media--card media--card-2"> <div class="media-body"> <h5><a href="https://hoidapvui.com/cong-van-chot-so-bao-hiem-xa-hoi-nam-2024">Công văn chốt sổ bảo hiểm xã hội năm 2024</a></h5> <small class="meta"> <span class="pr-1">1 tuần trước</span> <span class="pr-1">. bởi</span> <a href="https://hoidapvui.com/author/RidiculousTerrier" class="author">RidiculousTerrier</a> </small> </div> </div><!-- end media --> <div class="media media-card media--card media--card-2"> <div class="media-body"> <h5><a href="https://hoidapvui.com/lap-hien-va-lap-phap-la-gi-nam-2024">Lập hiến và lập pháp là gì năm 2024</a></h5> <small class="meta"> <span class="pr-1">1 tuần trước</span> <span class="pr-1">. bởi</span> <a href="https://hoidapvui.com/author/BoiledStaging" class="author">BoiledStaging</a> </small> </div> </div><!-- end media --> <div class="media media-card media--card media--card-2"> <div class="media-body"> <h5><a href="https://hoidapvui.com/tap-doan-fpt-co-bao-nhieu-cong-ty-con-nam-2024">Tập đoàn fpt có bao nhiêu công ty con năm 2024</a></h5> <small class="meta"> <span class="pr-1">1 tuần trước</span> <span class="pr-1">. bởi</span> <a href="https://hoidapvui.com/author/TrampledJuncture" class="author">TrampledJuncture</a> </small> </div> </div><!-- end media --> <div class="media media-card media--card media--card-2"> <div class="media-body"> <h5><a href="https://hoidapvui.com/be-left-to-your-own-devices-la-gi-nam-2024">Be left to your own devices là gì năm 2024</a></h5> <small class="meta"> <span class="pr-1">3 ngày trước</span> <span class="pr-1">. bởi</span> <a href="https://hoidapvui.com/author/SuburbanTemplate" class="author">SuburbanTemplate</a> </small> </div> </div><!-- end media --> <div class="media media-card media--card media--card-2"> <div class="media-body"> <h5><a href="https://hoidapvui.com/giai-de-thi-thu-thpt-quoc-gia-2023-mon-van-nam-2024">Giải đề thi thử thpt quốc gia 2023 môn văn năm 2024</a></h5> <small class="meta"> <span class="pr-1">3 ngày trước</span> <span class="pr-1">. bởi</span> <a href="https://hoidapvui.com/author/SolicitousInsanity" class="author">SolicitousInsanity</a> </small> </div> </div><!-- end media --> <div class="media media-card media--card media--card-2"> <div class="media-body"> <h5><a href="https://hoidapvui.com/tong-hop-cac-loi-xu-phat-giao-thong-2023-nam-2024">Tổng hợp các lỗi xử phạt giao thông 2023 năm 2024</a></h5> <small class="meta"> <span class="pr-1">5 ngày trước</span> <span class="pr-1">. bởi</span> <a href="https://hoidapvui.com/author/CurtFiring" class="author">CurtFiring</a> </small> </div> </div><!-- end media --> <div class="media media-card media--card media--card-2"> <div class="media-body"> <h5><a href="https://hoidapvui.com/loi-0x00000000709-khi-dat-may-in-mac-dinh-nam-2024">Lỗi 0x00000000709 khi đặt máy in mặc định năm 2024</a></h5> <small class="meta"> <span class="pr-1">1 ngày trước</span> <span class="pr-1">. bởi</span> <a href="https://hoidapvui.com/author/AlmightyStylus" class="author">AlmightyStylus</a> </small> </div> </div><!-- end media --> <div class="media media-card media--card media--card-2"> <div class="media-body"> <h5><a href="https://hoidapvui.com/dau-sao-y-ban-chinh-tieng-anh-la-gi-nam-2024">Dấu sao y bản chính tiếng anh là gì năm 2024</a></h5> <small class="meta"> <span class="pr-1">5 ngày trước</span> <span class="pr-1">. bởi</span> <a href="https://hoidapvui.com/author/TerritorialFooting" class="author">TerritorialFooting</a> </small> </div> </div><!-- end media --> <div class="media media-card media--card media--card-2"> <div class="media-body"> <h5><a href="https://hoidapvui.com/bai-tap-trac-nghiem-mon-bao-hiem-co-dap-an-nam-2024">Bài tập trắc nghiệm môn bảo hiểm có đáp án năm 2024</a></h5> <small class="meta"> <span class="pr-1">1 tuần trước</span> <span class="pr-1">. bởi</span> <a href="https://hoidapvui.com/author/SlimyComer" class="author">SlimyComer</a> </small> </div> </div><!-- end media --> <div class="media media-card media--card media--card-2"> <div class="media-body"> <h5><a href="https://hoidapvui.com/ck-la-viet-tat-cua-tu-gi-trong-may-mac-nam-2024">Ck là viết tắt của từ gì trong may mặc năm 2024</a></h5> <small class="meta"> <span class="pr-1">1 tuần trước</span> <span class="pr-1">. bởi</span> <a href="https://hoidapvui.com/author/FluffyCylinder" class="author">FluffyCylinder</a> </small> </div> </div><!-- end media --> </div><!-- end sidebar-questions --> </div> </div><!-- end card --> <div class="ad-card"> <h4 class="text-gray text-uppercase fs-14 pb-3 pb-3 text-center">Quảng cáo</h4> <div class="mb-4 mx-auto" style=" text-align: center"> <div id='div-gpt-ad-1657246837997-0' style='min-width: 300px; min-height: 600px;'> <script> googletag.cmd.push(function() { googletag.display('div-gpt-ad-1657246837997-0'); }); </script> </div> </div> </div> </div><!-- end sidebar --> </div><!-- end col-lg-3 --> </div><!-- end row --> </div><!-- end container --> </section><!-- end question-area --> <!-- ================================ END QUESTION AREA ================================= --> <script>var questionId ='javascript-is-a-language-often-used-within-html-documents-to-trigger-interactive-features'</script> <script>var postTime ='2022-10-01T10:00:23.848Z'</script> <script>var siteDomain ='hoidapvui.com'</script> <script type="text/javascript" src="https://hoidapvui.com/dist/js/pages/comment.js"></script> <!-- ================================ END FOOTER AREA ================================= --> <section class="footer-area pt-80px bg-dark position-relative"> <span class="vertical-bar-shape vertical-bar-shape-1"></span> <span class="vertical-bar-shape vertical-bar-shape-2"></span> <span class="vertical-bar-shape vertical-bar-shape-3"></span> <span class="vertical-bar-shape vertical-bar-shape-4"></span> <div class="container"> <div class="row"> <div class="col-lg-3 responsive-column-half"> <div class="footer-item"> <h3 class="fs-18 fw-bold pb-2 text-white">Chúng tôi</h3> <ul class="generic-list-item generic-list-item-hover-underline pt-3 generic-list-item-white"> <li><a href="/about.html">Giới thiệu</a></li> <li><a href="/contact.html">Liên hệ</a></li> <li><a href="/contact.html">Tuyển dụng</a></li> <li><a href="/contact.html">Quảng cáo</a></li> </ul> </div><!-- end footer-item --> </div><!-- end col-lg-3 --> <div class="col-lg-3 responsive-column-half"> <div class="footer-item"> <h3 class="fs-18 fw-bold pb-2 text-white">Điều khoản</h3> <ul class="generic-list-item generic-list-item-hover-underline pt-3 generic-list-item-white"> <li><a href="/privacy-statement.html">Điều khoản hoạt động</a></li> <li><a href="/terms-and-conditions.html">Điều kiện tham gia</a></li> <li><a href="/privacy-statement.html">Quy định cookie</a></li> </ul> </div><!-- end footer-item --> </div><!-- end col-lg-3 --> <div class="col-lg-3 responsive-column-half"> <div class="footer-item"> <h3 class="fs-18 fw-bold pb-2 text-white">Trợ giúp</h3> <ul class="generic-list-item generic-list-item-hover-underline pt-3 generic-list-item-white"> <li><a href="/contact.html">Hướng dẫn</a></li> <li><a href="/contact.html">Loại bỏ câu hỏi</a></li> <li><a href="/contact.html">Liên hệ</a></li> </ul> </div><!-- end footer-item --> </div><!-- end col-lg-3 --> <div class="col-lg-3 responsive-column-half"> <div class="footer-item"> <h3 class="fs-18 fw-bold pb-2 text-white">Mạng xã hội</h3> <ul class="generic-list-item generic-list-item-hover-underline pt-3 generic-list-item-white"> <li><a href="#"><i class="fab fa-facebook-f mr-1"></i> Facebook</a></li> <li><a href="#"><i class="fab fa-twitter mr-1"></i> Twitter</a></li> <li><a href="#"><i class="fab fa-linkedin mr-1"></i> LinkedIn</a></li> <li><a href="#"><i class="fab fa-instagram mr-1"></i> Instagram</a></li> </ul> </div><!-- end footer-item --> </div><!-- end col-lg-3 --> </div><!-- end row --> </div><!-- end container --> <hr class="border-top-gray my-5"> <div class="container"> <div class="row align-items-center pb-4 copyright-wrap"> <div class="col-6"> <a href="//www.dmca.com/Protection/Status.aspx?ID=33e5dca6-f8c5-4c6f-b8e6-a247229d2953" title="DMCA.com Protection Status" class="dmca-badge"> <img src ="https://images.dmca.com/Badges/dmca_protected_sml_120am.png?ID=33e5dca6-f8c5-4c6f-b8e6-a247229d2953" width="123px" height="21px" alt="DMCA.com Protection Status" /></a> <script src="https://images.dmca.com/Badges/DMCABadgeHelper.min.js"> </script> </div> <!-- end col-lg-6 --><div class="col-6"> <div class="copyright-desc text-right fs-14"> <div>Bản quyền © 2021 <a href="https://hoidapvui.com">hoidap<span style="color:#ff0000">vui</span></a> Inc.</div> </div> </div><!-- end col-lg-6 --> </div><!-- end row --> </div><!-- end container --> </section><!-- end footer-area --> <!-- ================================ END FOOTER AREA ================================= --><script> $( document ).ready(function() { setTimeout(showMoreButton, 3000); function showMoreButton(){ let minheight = 1000; minheight = parseInt($("#entryContent").innerHeight())/3; $("#entryContent").css('min-height', minheight).css('max-height', minheight).css('overflow', 'hidden'); $("#readmore_content").click(function(){ $("#entryContent").css('min-height', '').css('max-height', '').css('overflow', ''); $(".readmore_content_exists").css('display', 'none'); }) } }); </script> <!-- template js files --> <!-- start back to top --> <div id="back-to-top" data-toggle="tooltip" data-placement="top" title="Lên đầu trang"> <img alt="" src="/dist/images/svg/arrow-up_20.svg"> </div> <!-- end back to top --> <script src="https://hoidapvui.com/dist/js/bootstrap.bundle.min.js"></script> <script src="https://hoidapvui.com/dist/js/moment.js"></script> <script src="https://hoidapvui.com/dist/js/read-more.min.js"></script> <script src="https://hoidapvui.com/dist/js/main.js?v=6"></script> <!-- Google Tag Manager (noscript) --> <script type="text/javascript"> (function(c,l,a,r,i,t,y){ c[a]=c[a]||function(){(c[a].q=c[a].q||[]).push(arguments)}; t=l.createElement(r);t.async=1;t.src="https://www.clarity.ms/tag/"+i; y=l.getElementsByTagName(r)[0];y.parentNode.insertBefore(t,y); })(window, document, "clarity", "script", "jxuz46z39u"); </script> </body> </html>