My First JavaScript . What Can JavaScript Do? . What Can JavaScript Do? . What Can JavaScript Do? . What Can JavaScript Do? . What Can JavaScript Do? . What Can JavaScript Do? . JavaScript in Body . JavaScript in Head . JavaScript in Body . External JavaScript . External JavaScript . External JavaScript . External JavaScript . My First Web Page . My First Web Page . My First Web Page . My First Web Page . Activate debugging with F12 . JavaScript Statements . JavaScript Statements . JavaScript Statements . JavaScript Statements . JavaScript Statements . JavaScript Statements . JavaScript Numbers . JavaScript Strings . JavaScript Variables . JavaScript Operators . Assigning JavaScript Values . JavaScript Expressions . JavaScript Expressions . JavaScript Expressions . The var Keyword Creates Variables . JavaScript Comments are NOT Executed . JavaScript is Case Sensitive . comments are not executed . comments are not executed . The comments are not executed . The comments are not executed . The comments are not executed . JavaScript Variables . JavaScript Variables . JavaScript Variables . JavaScript Variables . JavaScript Variables . JavaScript Variables . JavaScript Variables . JavaScript Variables . JavaScript Variables . JavaScript Variables . JavaScript Variables . JavaScript Variables . JavaScript Operators . The = Operator . The + Operator . The * Operator . The += Operator . JavaScript Operators . JavaScript Operators . JavaScript Operators . A typical arithmetic operation takes two numbers and produces a new number. . arithmetic operation . The - Operator . The / Operator . The % Operator . The ++ Operator . The -- Operator . Multiplication . Multiplication . many operations . The = Operator . The += Operator . The -= Operator . The *= Operator . The /= Operator . The %= Operator . JavaScript . JavaScript . JavaScript . JavaScript . JavaScript Data Types . JavaScript Strings . JavaScript Strings . JavaScript Numbers . JavaScript Numbers . JavaScript Booleans . JavaScript Arrays . JavaScript Objects . JavaScript typeof . JavaScript typeof . variable with no value is undefined . Variables can be emptied . empty string has both a legal value and a type . Objects can be emptied . Objects can be emptied . Undefined and null are equal in value . JavaScript typeof . JavaScript typeof . JavaScript Functions . JavaScript Functions . JavaScript Functions . JavaScript Functions toCelsius . JavaScript Functions toCelsius . Creating a JavaScript Variable. . Creating a JavaScript Object. . Creating a JavaScript Object. . Creating a JavaScript Object. . Creating and using an object method. . JavaScript Object Methods . The local variable carName cannot be accessed from code outside the function: . A GLOBAL variable can be accessed from any script or function. . Date() . Date() . Click the button to display the date. . JavaScript Strings . JavaScript Strings . JavaScript Strings . JavaScript String Properties . JavaScript Strings . JavaScript Strings . JavaScript Strings . JavaScript Strings . JavaScript Strings . JavaScript Statements . typeof . Never Create Strings as objects. . Never Create Strings as objects. . Never Create Strings as objects. . Never Create Strings as objects. . JavaScript String Methods . JavaScript String Methods . JavaScript String Methods . JavaScript String Methods . JavaScript String Methods . JavaScript String Methods . JavaScript String Methods . JavaScript String Methods . JavaScript String Methods . JavaScript String Methods . JavaScript String Methods . JavaScript String Methods . JavaScript String Methods . JavaScript String Methods . JavaScript String Methods . Convert string to upper case: . Convert string to lower case: . JavaScript String Methods . The charAt() method returns the character at a given position in a string: . Click "Try it" to display the first array element, after a string split. . str.split . JavaScript Numbers . JavaScript Numbers . JavaScript Numbers . JavaScript Numbers . JavaScript Numbers . JavaScript Numbers . JavaScript Numbers . JavaScript Numbers . JavaScript Numbers . JavaScript Numbers . JavaScript Numbers . JavaScript Numbers . JavaScript Numbers . JavaScript Numbers . JavaScript Numbers . JavaScript Numbers . JavaScript Numbers . JavaScript Numbers . JavaScript Numbers . JavaScript Numbers . JavaScript Numbers . JavaScript Numbers . JavaScript Numbers . JavaScript Numbers . JavaScript Numbers . JavaScript Numbers . JavaScript Numbers . JavaScript Numbers . JavaScript Numbers . Never create numbers as objects. . Never create numbers as objects. . Never create numbers as objects. . The JavaScript toString() Method . toExponential . toFixed() . valueOf . JavaScript Number Methods . JavaScript Number Methods . parseInt() converts strings to numbers . parseFloat() converts strings to numbers . MAX_VALUE . MAX_VALUE . JavaScript Arrays . JavaScript Arrays . JavaScript Arrays . JavaScript Arrays . JavaScript Arrays . JavaScript Arrays . JavaScript Objects . JavaScript Arrays . JavaScript Arrays . JavaScript Arrays . JavaScript Arrays . JavaScript Arrays . JavaScript Arrays . JavaScript Arrays . JavaScript Arrays . JavaScript Arrays . JavaScript Arrays . JavaScript Arrays . JavaScript Arrays . JavaScript Arrays . JavaScript Array Methods . toString() . JavaScript Array Methods . join() . JavaScript Array Methods . pop() . JavaScript Array Methods . pop() . JavaScript Array Methods . push() . JavaScript Array Methods . push() . JavaScript Array Methods . shift() . JavaScript Array Methods . shift() . JavaScript Array Methods . unshift() . JavaScript Array Methods . unshift() . JavaScript Array Methods . JavaScript Array Methods . JavaScript Array Methods . JavaScript Array Methods . splice() . JavaScript Array Methods . splice() . JavaScript Array Methods . concat() . JavaScript Array Methods . concat() . JavaScript Array Methods . concat() . JavaScript Array Methods . slice() . JavaScript Array Methods . slice() . JavaScript Array Methods . slice() . JavaScript Array Methods . slice() . JavaScript Array Methods . JavaScript Array Sort . JavaScript Array Sort . JavaScript Array Sort . JavaScript Array Sort . JavaScript Array Sort . JavaScript Array Sort . JavaScript Array Sort . JavaScript Array Sort . JavaScript Array Sort . JavaScript Array Sort . JavaScript Array Sort . JavaScript Array Sort . JavaScript Array Sort . JavaScript Array Sort . getFullYear() . JavaScript getFullYear() . getMonth() . JavaScript getMonth() . getDate() . JavaScript getDate() . getHours() . JavaScript getHours() . getMinutes() . JavaScript getMinutes() . getSeconds() . JavaScript getSeconds() . JavaScript new Date() . JavaScript new Date() . JavaScript new Date() . JavaScript new Date() . JavaScript new Date() . JavaScript new Date() . JavaScript new Date() . JavaScript new Date() . JavaScript new Date() . JavaScript new Date() . JavaScript new Date() . JavaScript new Date() . JavaScript new Date() . JavaScript new Date() . JavaScript new Date() . JavaScript new Date() . JavaScript toString() . JavaScript Date() . JavaScript toDateString() . JavaScript ISO Dates . JavaScript ISO Dates . JavaScript ISO Dates . JavaScript ISO Dates . JavaScript ISO Dates . JavaScript new Date() . JavaScript new Date() . JavaScript new Date() . JavaScript new Date() . JavaScript new Date() . JavaScript new Date() . JavaScript Date.parse() . Date.parse(string) returns milliseconds. . JavaScript getTime() . JavaScript getFullYear() . JavaScript getMonth() . JavaScript getMonth() . JavaScript getDate() . JavaScript getHours() . JavaScript getMinutes() . JavaScript getSeconds() . JavaScript getMilliseconds() . JavaScript getDay() . JavaScript getDay() . JavaScript setFullYear() . JavaScript setFullYear() . JavaScript setMonth() . JavaScript setDate() . JavaScript setDate() . JavaScript setHours() . JavaScript setMinutes() . JavaScript setSeconds() . setFullYear . JavaScript Math.PI . JavaScript Math.round() . JavaScript Math.pow() . JavaScript Math.sqrt() . JavaScript Math.abs() . JavaScript Math.ceil() . JavaScript Math.floor() . JavaScript Math.sin() . JavaScript Math.cos() . JavaScript Math.min() . JavaScript Math.max() . JavaScript Math.random() . JavaScript Math Constants . JavaScript Math.random() . JavaScript Math . JavaScript Math . JavaScript Math . JavaScript Math . JavaScript Math . JavaScript Math . JavaScript Math.random() . JavaScript Math.random() . Display the value of Boolean(10 > 9): . Display the value of 10 > 9: . Boolean . Display the Boolean value of 0: . Display the Boolean value of -0: . Display the Boolean value of "": . Display the Boolean value of undefined: . Display the Boolean value of null: . Display the Boolean value of false: . Display the Boolean value of NaN: . Never create booleans as objects . Never create booleans as objects. . Never create booleans as objects. . Never create booleans as objects. . JavaScript Comparison . JavaScript Comparison . JavaScript Comparison . JavaScript Comparison . JavaScript Comparison . JavaScript Comparison . JavaScript Comparison . JavaScript Comparison . JavaScript Comparison . JavaScript Comparison . JavaScript Comparison . JavaScript Comparison . JavaScript Comparison . JavaScript Comparison . JavaScript Comparison . JavaScript Comparison . Input your age and click the button: . JavaScript Comparison . JavaScript Comparison . JavaScript Comparison . JavaScript Comparison . JavaScript Comparison . JavaScript Comparison . JavaScript Comparison . JavaScript Comparison . JavaScript Comparisons . Display "Good day!" if the hour is less than 18:00: . Click the button to display a time-based greeting: . Click the button to get a time-based greeting: . Random link . getDay() . getDay() . getDay() . getDay() . JavaScript Loops . JavaScript Loops . .length . . . JavaScript Loops . JavaScript while . JavaScript do ... while . cars[i] . cars[i] . A loop with a break. . A loop which will skip the step where i = 3. . cars[i] . The JavaScript typeof Operator . The JavaScript constructor Property . JavaScript Arrays . JavaScript Array Object . JavaScript Date Object . JavaScript Date Object . The JavaScript String() Method . The JavaScript typeof Operator . The JavaScript typeof Operator . operator . Converting false to other types: . Converting true to other types: . Converting the number 0 to other types: . Converting the number 1 to other types: . Converting the string "0" to other types: . Converting the string "000" to other types: . Converting the string "1" to other types: . Converting NaN to other types: . Converting Infinity to other types: . Converting -Infinity to other types: . Converting an empty string to other types: . Converting a numeric string to other types: . Converting a text string to other types: . Converting an empty array to other types: . Converting an array with one numeric element to other types: . Converting an array with two numeric elements to other types: . Converting an array with one string element to other types: . Converting an array with two string element to other types: . Converting a function to other types: . Converting an object to other types: . Converting null to other types: . Converting undefined to other types: . JavaScript Bitwise AND . JavaScript Bitwise OR . JavaScript Bitwise XOR . JavaScript Bitwise NOT . JavaScript Bitwise Left . JavaScript Sign Preserving Bitwise Right. . JavaScript Bitwise Right . JavaScript Convert Decimal to Binary . JavaScript Convert Binary to Decimal . Search a string for "w3Schools", and display the position of the match: . Search a string for "W3Schools", and display the position of the match: . JavaScript String Methods . Search for an "e" in the next paragraph: . Search for an "e" in the next paragraph: . adddlert . Please input a number between 5 and 10: . Please input a number between 5 and 10: . JavaScript Errors . JavaScript Errors . JavaScript Errors . JavaScript Errors . JavaScript Errors . My First Web Page . debugger . Find an element . Find an element . Find an element . Find an element . Find an element . With "use strict": . Global "use strict" declaration. . "use strict" in a function will only cause errors in that function. . With "use strict": . With "use strict": . With "use strict": . With "use strict": . With "use strict": . With "use strict": . With "use strict": . With "use strict": . With "use strict": . With "use strict": . With "use strict": . With "use strict": . With "use strict": . With "use strict": . With "use strict": . My Web Page . Never create strings as objects. . Never create strings as objects. . typeof . typeof . Remove the comment (at the beginning of the lines) to test each case: . My first paragraph . Remove the comment (at the beginning of each line) to test each case: . Setting a default value to a function parameter. . getDay . Boolean(x == 10) . Boolean(x == 10) . Boolean(x == 10) . Boolean(x == y) . Boolean(x === y) . switch(x) . switch(x) . 10 + "5" . x + y . x + y . (x * 10 + y *10) / 10 . "Hello World!" . "Hello World!" . "Hello World!" . "Hello" . power . power . power . power . power . JavaScript does not create a new scope for each code block . Hello . Create Object from JSON String . document.forms . JavaScript Can Validate Input . submit . Enter a number and click OK: . Enter a number and click OK: . Enter a number and click OK: . Creating a JavaScript Variable. . Creating a JavaScript Object. . Creating a JavaScript Object. . Creating a JavaScript Object. . Object() . JavaScript objects are mutable. . There are two different ways to access an object property: . There are two different ways to access an object property: . Object . You can add new properties to existing objects. . You can delete object properties. . Creating and using an object method. . An object method is a function definition stored as a property value. . Object . JavaScript Object Constructors . JavaScript Object Constructors . JavaScript Object Constructors . JavaScript Object Constructors . JavaScript Object Constructors . JavaScript Object Constructors . JavaScript Object Constructors . JavaScript Object Constructors . JavaScript Object Constructors . variables . JavaScript Objects . JavaScript Objects . JavaScript Objects . JavaScript Objects . JavaScript Objects . A function can be stored in a variable: . After a function has been stored in a variable the variable can be used as a function . JavaScript has an built-in function constructor. . return . Functions can be invoked automatically without being called: . Functions can be treated as values: . Functions can be used in expressions. . The arguments.length property returns the number of arguments received by the function: . The toString() method returns the function as a string: . Setting a default value to a function parameter. . Finding the largest number. . Sum of all arguments: . JavaScript Functions . JavaScript Functions . JavaScript Functions . JavaScript Functions . JavaScript Functions . JavaScript Functions . JavaScript Functions . JavaScript Functions . JavaScript Functions . JavaScript Math.max() . JavaScript apply() . A function can access variables defined inside the function: . A function can access variables defined outside the function: . Counting with a global variable. . Counting with a local variable. . Counting with a local variable. . Counting with a local variable. . My First Page . getElementById . Hello World! . Hello World! . Hello World! . Hello World! . form . document.anchors . document.body . document.documentElement . document.embeds . document.forms . document.head . document.images . document.links . document.scripts . document.title . document.write . JavaScript can Change HTML . element.innerHTML . document.getElementById . document.getElementById . document.getElementById . Visibility . My First JavaScript Animation . Animation . My First JavaScript Animation . Animation . changeText . changeText . Click the button to display the date. . Click "Try it" to execute the displayDate() function. . checkCookies . toUpperCase . Mouse Over Me . onmousedown . onmousedown and onmouseup . onload . onfocus . Mouse Events . uses the addEventListener() method to attach a click event to a button. . uses the addEventListener() method to attach a click event to a button. . uses the addEventListener() method to execute a function . uses the addEventListener() method to add two click events to the same button. . uses the addEventListener() method to add many events on the same button. . uses the addEventListener() method on the window object. . pass parameter values when using addEventListener() method.

. difference between bubbling and capturing when adding event listeners . onmousemove event handler . The addEventListener() method is not supported Internet Explorer 8 and earlier versions. . retrieves the text . retrieves the text . retrieves the text . Hello World! . DOM Root Nodes . DOM Root Nodes . The nodeType Property . Creating New HTML Elements (Nodes) . Creating new HTML Elements - insertBefore() . Removing Existing HTML Elements . Removing Existing HTML Elements . JavaScript HTML DOM . JavaScript HTML DOM! . Window Size . Window Screen Width . Window Screen Height . Window Screen Available Width . Window Screen Available Height . Window Screen Color Depth . Window Screen Pixel Depth . The window.location object . The window.location object . The window.location object . The window.location object . The window.location object . The window.location object . The Navigator Object . The Navigator Object . JavaScript Navigator . The Navigator Object . The Navigator Object . The Navigator Object . The Navigator Object . The Navigator Object . The Navigator Object . The Navigator Object . JavaScript Alert . JavaScript Confirm Box . JavaScript Prompt . JavaScript . Click "Try it". Wait 3 seconds, and the page will alert "Hello". . Click "Try it". Wait 3 seconds. The page will alert "Hello". . A script on this page starts this clock: . A script on this page starts this clock: . Another simple timing . A clock created with a timing event . Create a Cookie with JavaScript . XMLHttpRequest Object . The XMLHttpRequest Object . The XMLHttpRequest Object . The XMLHttpRequest Object . The XMLHttpRequest Object . The XMLHttpRequest Object . The XMLHttpRequest Object . The XMLHttpRequest Object . The XMLHttpRequest Object . XMLHttpRequest Object . The XMLHttpRequest Object . The XMLHttpRequest Object . XMLHttpRequest Object . The XMLHttpRequest Object . The XMLHttpRequest Object . The XMLHttpRequest Object . The XMLHttpRequest Object . XMLHttpRequest Object . The XMLHttpRequest Object . The XMLHttpRequest Object . The XMLHttpRequest Object . XMLHttpRequest Object . The XMLHttpRequest Object . XMLHttpRequest Object . XMLHttpRequest Object . XMLHttpRequest Object . XMLHttpRequest Object . A simple AJAX example . The XMLHttpRequest Object . An AJAX example with a callback function . The XMLHttpRequest Object . Retrieve all header information . The XMLHttpRequest Object . Retrieve specific header information . The XMLHttpRequest Object . Load an XML file with AJAX . The XMLHttpRequest Object . Retrieve data from XML file . Retrieve the content of an XML file . The XMLHttpRequest Object . Retrieve the content of a PHP file . The XMLHttpRequest Object . Retrieve the content of an ASP file . The XMLHttpRequest Object . Retrieve content from a database . The XMLHttpRequest Object . Display XML data in an HTML table . Show XML data inside an HTML div element . Navigate through XML nodes . A simple CD catalog application . Convert a JavaScript object into a JSON string, and send it to the server. . Convert a string written in JSON format, into a JavaScript object. . Store and retrieve data from local storage. . Access a JavaScript object: . Access a JavaScript object using the bracket notation: . Modify a JavaScript object: . Modify a JavaScript object using the bracket notation: . How to create a JavaScript object array. . How to create a JavaScript object array. . How to create a JavaScript object array. . How to create a JavaScript object array. . Access a JSON object using dot notation: . Access a JSON object using bracket notation: . How to loop through all properties in a JSON object. . Use bracket notation to access the property values. . How to access nested JSON objects. . How to modify values in a JSON object. . How to modify values in a JSON object using the bracket notation. . How to delete properties of a JSON object. . Access an array value of a JSON object. . Looping through an array using a for in loop: . Loopin through an array using a for loop: . Looping through arrays inside arrays. . " + myObj.cars[i].name + "&l . How to modify an array value of a JSON object. . How to delete properties of an array. . Create Object from JSON String . Use the XMLHttpRequest to get the content of a file. . Content as Array. . Convert a string into a date object. . Convert a string into a date object. . Convert a string into a function. . Create JSON string from a JavaScript object. . Create JSON string from a JavaScript array. . JSON.stringify will convert any date objects into strings. . JSON.stringify will remove any functions from an object. . JSON.stringify will remove any functions from an object. . Get data as JSON from a PHP file on the server. . Get data as JSON from a PHP file, and convert it into a JavaScript array. . Get data as JSON from a PHP file on the server. . Get data as JSON from a PHP file on the server. . Use the HTTP method POST to send data to the PHP file. . Make a table based on JSON data. . Make a table based on the value of a drop down menu. . Make a drop down list based on JSON data. . Request JSON using the script tag . Request JSON using the script tag . Click the Button. . Request JSON using the script tag . Click the Button. . Request JSON using the script tag . Request With a Callback Function . What Can JavaScript Do . What Can JavaScript Do . What Can JavaScript Do . What Can JavaScript Do . What Can JavaScript Do . Paragraph changed . JavaScript in Head . JavaScript in Body . External JavaScript . External JavaScript . External JavaScript . document.write . My First Web Page . document.getElementById . My First Web Page . window.alert . My First Web Page . Activate debugging with F12 . JavaScript Statements . JavaScript Numbers . JavaScript Strings . JavaScript Variables . JavaScript Operators . Assigning JavaScript Values . JavaScript Expressions . JavaScript Expressions . JavaScript Expressions . The var Keyword Creates Variables . JavaScript Comments are NOT Executed . JavaScript is Case Sensitive . JavaScript Statements . JavaScript Statements . JavaScript Statements . JavaScript Statements . JavaScript Statements . JavaScript Statements . . . . . . JavaScript Variables . JavaScript Variables . JavaScript Variables . JavaScript Variables . JavaScript Variables . JavaScript Variables . JavaScript Variables . JavaScript Variables . JavaScript Variables . JavaScript Variables . JavaScript Variables . The + Operator . The - Operator . The * Operator . The / Operator . The % Operator . JavaScript Operators . JavaScript Operators . The = Operator . The += Operator . The -= Operator . The *= Operator . The /= Operator . The %= Operator . JavaScript Operators . JavaScript Operators . JavaScript Operators . JavaScript Operators . JavaScript Operators . JavaScript Strings . JavaScript Numbers . JavaScript Arrays . JavaScript Objects . . JavaScript . JavaScript . JavaScript . JavaScript . . . . . . . . JavaScript Object Methods . A simple function . A function with an argument . A function with an argument 2 . A function that returns a value . JavaScript Functions . A function that converts Fahrenheit to Celsius . JavaScript Functions . A function call without () . JavaScript Functions . An onclick event changes an HTML element . An onclick event changes its own element . An onclick event calls a function . JavaScript Strings . Show some string examples . JavaScript Strings . . Find the length of a string . JavaScript String Properties . JavaScript Strings . JavaScript Statements . Find the position of the first occurrence of a text . JavaScript String Methods . Search for a text in a string and return the text if found . Replace characters in a string - replace() . JavaScript String Methods . Convert string to upper case - toUpperCase() . Convert string to lower case - toLowerCase() . Split a string into an array - split() . Numbers can be written with or without decimals . JavaScript Numbers . Extra large or extra small numbers can be written with exponent notation . JavaScript Numbers . Number are considered accurate only up to 15 digits . JavaScript Numbers . Floating point arithmetic is not always 100% accurate . JavaScript Numbers . But it helps to multiply and divide by 10 . JavaScript Numbers . Constants, preceded by 0x, are interpreted as hexadecimal . JavaScript Numbers . A number divided by a string is not a number . JavaScript Numbers . JavaScript will generate Infinity if you calculate a too large number . JavaScript Numbers . Division by zero generates Infinity . JavaScript Numbers . The toString() method can output numbers as hex, octal, and binary . JavaScript Numbers . JavaScript Math.PI . JavaScript Math.round() . JavaScript Math.pow() . JavaScript Math.sqrt() . JavaScript Math.abs() . JavaScript Math.ceil() . JavaScript Math.floor() . JavaScript Math.sin() . JavaScript Math.cos() . JavaScript Math.max() . JavaScript Math.min() . JavaScript Celcius to Fahrenhet . JavaScript Math.random() . JavaScript Math . JavaScript Math . JavaScript Math . JavaScript Math . JavaScript Math . JavaScript Math . JavaScript Math.random() . JavaScript Math.random() . Use Date() to display today's date and time . JavaScript new Date() . Use getFullYear() display the year . JavaScript getFullYear() . Use getTime() to calculate the number of milliseconds since 1970 . JavaScript getTime() . Use setFullYear() to set a specific date . JavaScript setFullYear() . Use toUTCString() to convert today's date (according to UTC) to a string . JavaScript Date() . Use getDay() to display the weekday as a number . JavaScript getDay() . Use getDay() and an array to display the weekday as a name . JavaScript getDay() . Display a clock . Create an array . JavaScript Arrays . Join two arrays - concat() . JavaScript Array Methods . concat() . Join three arrays - concat() . JavaScript Array Methods . concat() . Join all elements of an array into a string - join() . JavaScript Array Methods& . join() . Remove the last element of an array - pop() . JavaScript Array Methods . pop() . Add new elements to the end of an array - push() . JavaScript Array Methods& . push() . Reverse the order of the elements in an array - reverse() . Remove the first element of an array - shift() . JavaScript Array Methods& . shift() . Select elements from an array - slice() . JavaScript Array Methods& . slice() . Sort an array (alphabetically and ascending) - sort() . JavaScript Array Sort . Sort numbers (numerically and ascending) - sort() . JavaScript Array Sort . Sort numbers (numerically and descending) - sort() . JavaScript Array Sort . Sort numbers (alphabetically and numerically) - sort() . JavaScript Array Sort . Sort numbers in random order - sort() . JavaScript Array Sort . Sort objects by numeric properties - sort() . JavaScript Array Sort . Sort objects by string properties - sort() . JavaScript Array Sort . Add an element to position 2 in an array - splice() . JavaScript Array Methods . splice() . Convert an array to a string - toString() . JavaScript Array Methods& . toString() . Add new elements to the beginning of an array - unshift() . JavaScript Array Methods& . unshift() . Display the typeof all variable types . The JavaScript typeof Operator . Display the constructor of all variable types . The JavaScript constructor Property . Convert a number to a string using String() . The JavaScript String() Method . Convert a number to a string using toString() . The JavaScript toString() Method . Find out if a variable is an array . JavaScript Arrays . Find out if a variable is a date . JavaScript Date Object . Display the value of Boolean(10 > 9) . Display the value of 10 > 9 . Everything with a real value is true . The Boolean value of zero is false . The Boolean value of minus zero is false . The Boolean value of an empty string is false . The Boolean value of undefined is false . The Boolean value of null is false . The Boolean value of false is false . The Boolean value of NaN is false . Assign 5 to x, and display the value of (x == 8) . JavaScript Comparison . Assign 5 to x, and display the value of (x == 5) . JavaScript Comparison . Assign 5 to x, and display the value of (x === 5) . JavaScript Comparison . Assign 5 to x, and display the value of (x === "5") . JavaScript Comparison . Assign 5 to x, and display the value of (x != 8) . JavaScript Comparison . Assign 5 to x, and display the value of (x !== 5) . JavaScript Comparison . Assign 5 to x, and display the value of (x !== "5") . JavaScript Comparison . Assign 5 to x, and display the value of (x > 8) . JavaScript Comparison . Assign 5 to x, and display the value of (x < 8) . JavaScript Comparison . Assign 5 to x, and display the value of (x >= 8) . JavaScript Comparison . Assign 5 to x, and display the value of (x <= 8) . JavaScript Comparison . The if statement . The else statement . The else if statement . Switch statement . For loop . Looping through HTML headers . While loop . JavaScript while . Do While loop . JavaScript do ... while . Break a loop . Break and continue a loop . Use a for...in statement to loop through the elements of an . JavaScript Loops . The try...catch statement . The try...catch statement with a confirm box . The onerror event . Search for an expression in a string . Search for an expression and replace it . JavaScript String Methods . . . . . . JavaScript Object Constructors . . . . . . . . . . . . . . . . . . . . . " + myObj.cars[i].name + "&l . . . Create Object from JSON String . Use the XMLHttpRequest to get the content of a file. . Content as Array. . Convert a string into a date object. . Convert a string into a date object. . Convert a string into a function. . Create JSON string from a JavaScript object. . Create JSON string from a JavaScript array. . JSON.stringify will convert any date objects into strings. . JSON.stringify will remove any functions from an object. . JSON.stringify will remove any functions from an object. . Get data as JSON from a PHP file on the server. . Get data as JSON from a PHP file, and convert it into a JavaScript array. . Get data as JSON from a PHP file on the server. . Get data as JSON from a PHP file on the server. . Use the HTTP method POST to send data to the PHP file. . Make a table based on JSON data. . Make a table based on the value of a drop down menu. . Make a drop down list based on JSON data. . Request JSON using the script tag . A script tag with a src attribute is created and placed in the document . Click the Button. . A script tag with a src attribute is created and placed in the document . Click the Button. . Request With a Callback Function . Display all name/value pairs of cookies in a document . Display the domain name of the server that loaded the document . Display the date and time the document was last modified . Display the URL of the document that loaded the current document . Display the title of a document . Display the full URL of a document . Replace the content of a document . Learning about the HTML DOM is fun!< . Open a new window, and add some content . Hello World!< . Display the number of elements with a specific name . Display the number of elements with a specific tag name . Find the number of anchors in a document . Find the innerHTML of the first anchor in a document . Display the number of links in a document . Display the href attribute of the first link in a document . Find the number of forms in a document . Find the name of the first form in a document . Return the number of images in a document . Return the id of the first image in a document . Change the visibility of an HTML element . Change the background color of an HTML element . Change background color . Disable a button . Find the name of a button . Find the type of a button . Find the value of a button . Find the text displayed on a button . Find the id of the form a button belongs to . Submit a form . Reset a form . Find the value of each element in a form . Find the accepted character set of a form . Find the action attribute of a form . Find the value of the enctype attribute in a form . Find the number of elements in a form . Find the method for sending form data . Find the name of a form . Find the target of a form . Disable and enable a dropdown list . Get the id of the form that contains the dropdown list . Get the number of options in the dropdown list . Turn the dropdown list into a multiline list . Select multiple options in a dropdown list . Display the selected option in a dropdown list . Display all options from a dropdown list . Display the index of the selected option in a dropdown list . Change the text of the selected option . Remove options from a dropdown list . Find the value of the href attribute of a link . Find the value of the hreflang attribute of a link . Find the value of the id attribute a link . Find the value of the rel attribute of a link . Find the value of the target attribute of a link . Find the value of the type attribute of a link . Find the alternate text of an image-map area . Find the coordinates of an area . Find the shape of an area . Find the href of an area . Find the protocol part of the href attribute of an area . Find the hostname part of the href attribute of an area . Find the port number part of the href attribute of an area . Find the pathname part of the href attribute of an area . Find the querystring part of the href attribute of an area . Find the hash part of the href attribute of an area . Find the value of the target attribute of an area . Find the base URL for all relative URLs on a page . Find the base target for all links on a page . Change the background color of an iframe . Find the height of an iframe . Find the value of the name attribute of an iframe . Find the source (src) attribute of an iframe . Change the source (src) attribute of an iframe . Find the alternate text of an image . Find the height of an image . Click to display a high-resolution version of an image . Find the source (src) of an image . Change the source of an image . Change the source of the lightbulb . Find the value of the usemap attribute of an image . Change the width of a table border . Change the padding of a table . Find the innerHTML of a cell . Create a caption for a table . Delete rows in a table . Add rows to a table . Change the content of a table cell . onblur - When a user leaves an input field . onchange - When a user changes the content of an input field . onchange - When a user selects a dropdown value . onfocus - When an input field gets focus . onselect - When input text is selected . onsubmit - When a user clicks the submit button . onreset - When a user clicks the reset button . onkeydown - When a user is pressing/holding down a key . onkeypress - When a user is pressing/holding down a key . onkeyup - When the user releases a key . onkeyup - When the user releases a key . onkeydown vs onkeyup - Both . onmouseover/onmouseout - When the mouse passes over an element . onmousedown/onmouseup - When pressing/releasing a mouse button . onmousedown - When mouse is clicked: Alert which element . onmousedown - When mouse is clicked: Alert which button . onmousemove/onmouseout - When moving the mouse pointer over/out of an image . onmouseover/onmouseout - When moving the mouse over/out of an image . onmouseover an image map . Acting to the onclick event . My First JavaScript . onclick - When button is clicked . ondblclick - . onload - When the page has been loaded . Hello World! . onload - When an image has been loaded . onerror - When an error occurs when loading an image . onunload - When the browser closes the document . Welcome to my Home Page . onresize - When the browser window is resized . What is the keycode of the key pressed? . What are the coordinates of the cursor? . What are the coordinates of the cursor, relative to the screen? . Was the shift key pressed? . Which event type occurred? . Open a new window when clicking on a button . Open a new window and control its appearance . Blur and Focus a new window . Close the new window . Checks whether the new window has been closed or not . Write some text to the source (parent) window . Move the new window relative to its current position . Move the new window to the specified position . Print the current page . Resize a window by the specified pixels . Resize a window to a specified size . Scroll the content by the specified number of pixels . Reserved Words . Scroll the content to a specified position . Reserved Words . The visitor's screen: Width . The visitor's screen: Height . The visitor's screen: Available Width . The visitor's screen: Available Height . The visitor's screen: Color Depth . The visitor's screen: Pixel Depth . Return the hostname and port of the current URL . JavaScript . Return the entire URL of the current page . JavaScript . Return the path name of the current URL . JavaScript . Return the protocol portion of the current URL . JavaScript . Load a new document . JavaScript . Replace the current document . Break out of a frame . Display the number of URLs in the history list . Create a back button on a page . Create a forward button on a page . Load a specific URL from the history list . Is cookies enabled in the visitor's browser? . The Navigator Object . What is the name of the visitor's browser? . JavaScript Navigator . What is the engine name of the visitor's browser? . The Navigator Object . What is the version information of the visitor's browser? . The Navigator Object . What is user agent information of the visitor's browser? . The Navigator Object . What is the platform of the visitor's browser? . The Navigator Object . What is the language of the visitor's browser? . The Navigator Object . Is Java enabled in the visitor's browser? . The Navigator Object . Display an alert box . JavaScript Alert . Demonstrate line breaks in an alert box . JavaScript . Display a confirm box . JavaScript Confirm Box . Display a prompt box . JavaScript Prompt . Simple timing . Another simple timing . Timing event in an infinite loop . Timing event in an infinite loop - with a Stop button . A clock created with a timing event . Set and stop a timer with setInterval() and clearInterval() . Create a welcome cookie





My First JavaScript

<button type="button"
onclick="document.getElementById('demo').innerHTML = Date()">
Click me to display Date and Time.</button>

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

What Can JavaScript Do?

<p id="demo">JavaScript can change HTML content.</p>

<button type="button" onclick='document.getElementById("demo").innerHTML = "Hello JavaScript!"'>Click Me!</button>

What Can JavaScript Do?

<p id="demo">JavaScript can change HTML content.</p>

<button type="button" onclick="document.getElementById('demo').innerHTML = 'Hello JavaScript!'">Click Me!</button>

What Can JavaScript Do?

<p>JavaScript can change HTML attributes.</p>

<p>In this case JavaScript changes the src (source) attribute of an image.</p>

<button onclick="document.getElementById('myImage').src='https://www.w3schools.com/js/pic_bulbon.gif'">Turn on the light</button>

<img id="myImage" src="https://www.w3schools.com/js/pic_bulboff.gif" style="width:100px">

<button onclick="document.getElementById('myImage').src='https://www.w3schools.com/js/pic_bulboff.gif'">Turn off the light</button>

What Can JavaScript Do?

<p id="demo">JavaScript can change the style of an HTML element.</p>

<button type="button" onclick="document.getElementById('demo').style.fontSize='35px'">Click Me!</button>

What Can JavaScript Do?

<p id="demo">JavaScript can hide HTML elements.</p>

<button type="button" onclick="document.getElementById('demo').style.display='none'">Click Me!</button>

What Can JavaScript Do?

<p>JavaScript can show hidden HTML elements.</p>

<p id="demo" style="display:none">Hello JavaScript!</p>

<button type="button" onclick="document.getElementById('demo').style.display='block'">Click Me!</button>

JavaScript in Body

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

<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>

JavaScript in Head

<html>
<head>
<script>
function myFunction() {
    document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>

<body>


<p id="demo">A Paragraph.</p>

<button type="button" onclick="myFunction()">Try it</button>

JavaScript in Body

<p id="demo">A Paragraph.</p>

<button type="button" onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>

External JavaScript

<p id="demo">A Paragraph.</p>

<button type="button" onclick="myFunction()">Try it</button>

<p>(myFunction is stored in an external file called "myScript.js")</p>

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

External JavaScript

<p id="demo">A Paragraph.</p>

<button type="button" onclick="myFunction()">Try it</button>

<p>(myFunction is stored in an external file called "myScript.js")</p>

<script src="https://www.w3schools.com/js/myScript.js"></script>

External JavaScript

<p id="demo">A Paragraph.</p>

<button type="button" onclick="myFunction()">Try it</button>

<p>(myFunction is stored in an external file called "myScript.js")</p>

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

External JavaScript

<p id="demo">A Paragraph.</p>

<button type="button" onclick="myFunction()">Try it</button>

<p>(myFunction is stored in an external file called "myScript.js")</p>

<scrip</pre>t src="myScript.js"></script>


My First Web Page

<p>My First Paragraph.</p>

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

<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>

My First Web Page

<p>My first paragraph.</p>

<script>
document.write(5 + 6);
</script>

My First Web Page

<p>My first paragraph.</p>

<butto</pre>n type="button" onclick="document.write(5 + 6)">Try it</button>


My First Web Page

<p>My first paragraph.</p>

<script>
window.alert(5 + 6);
</script>


Activate debugging with F12

<p>Select "Console" in the debugger menu. Then click Run again.</p>

<script>
console.log(5 + 6);
</script>

JavaScript Statements

<p>A <b>JavaScript program</b> is a list of <b>statements</b> to be executed by a computer.</p>

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

<script>

var x, y, z;  // Statement 1
x = 5;        // Statement 2
y = 6;        // Statement 3
z = x + y;    // Statement 4

document.getElementById("demo").innerHTML =
"The value of z is " + z + ".";  

</script>

JavaScript Statements

<p>In HTML, JavaScript statements are executed by the browser.</p>

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

<script>
document.getElementById("demo").innerHTML = "Hello Dolly.";
</script>

JavaScript Statements

<p>JavaScript statements are separated by semicolons.</p>

<p id="demo1"></p>

<script>
var a, b, c;
a = 1;
b = 2;
c = a + b;
document.getElementById("demo1").innerHTML = c;
</script>

JavaScript Statements

<p>Multiple statements on one line is allowed.</p>

<p id="demo1"></p>

<script>
var a, b, c;
a = 1; b = 2; c = a + b;
document.getElementById("demo1").innerHTML = c;
</script>

JavaScript Statements

<p>
The best place to break a code line is after an operator or a comma.
</p>

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

<script>
document.getElementById("demo").innerHTML =
"Hello Dolly!";
</script>

JavaScript Statements

<p>JavaScript code blocks are written between { and }</p>

<button type="button" onclick="myFunction()">Click Me!</button>

<p id="demo1"></p>
<p id="demo2"></p>

<script>
function myFunction() {
    document.getElementById("demo1").innerHTML = "Hello Dolly!";
    document.getElementById("demo2").innerHTML = "How are you?";
}
</script>

JavaScript Numbers

<p>Number can be written with or without decimals.</p>

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

<script>
document.getElementById("demo").innerHTML = 10.50;
</script>

JavaScript Strings

<p>Strings can be written with double or single quotes.</p>

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

<script>
document.getElementById("demo").innerHTML = 'John Doe';
</script>

JavaScript Variables

<p>In this example, x is defined as a variable.
Then, x is assigned the value of 6:</p>

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

<script>
var x;
x = 6;
document.getElementById("demo").innerHTML = x;
</script>

JavaScript Operators

<p>JavaScript uses arithmetic operators to compute values (just like algebra).</p>

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

<script>
document.getElementById("demo").innerHTML = (5 + 6) * 10;
</script>

Assigning JavaScript Values

<p>In JavaScript the = operator is used to assign values to variables.</p>

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

<script>
var x, y;
x = 5;
y = 6;
document.getElementById("demo").innerHTML = x + y;
</script>

JavaScript Expressions

<p>Expressions compute to values.</p>

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

<script>
document.getElementById("demo").innerHTML = 5 * 10;
</script>

JavaScript Expressions

<p>Expressions compute to values.</p>

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

<script>
var x;
x = 5;
document.getElementById("demo").innerHTML = x * 10;
</script>

JavaScript Expressions

<p>Expressions compute to values.</p>

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

<script>
document.getElementById("demo").innerHTML = "John" + " "  + "Doe";
</script>

The var Keyword Creates Variables

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

<script>
var x, y;
x = 5 + 6;
y = x * 10;
document.getElementById("demo").innerHTML = y;
</script>

JavaScript Comments are NOT Executed

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

<script>
var x;
x = 5;
// x = 6; I will not be executed
document.getElementById("demo").innerHTML = x;
</script>

JavaScript is Case Sensitive

<p>Try change lastName to lastname.</p>

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

<script>
var lastname, lastName;
lastName = "Doe";
lastname = "Peterson";
document.getElementById("demo").innerHTML = lastName;
</script>

comments are not executed

<h1 id="myH"></h1>
<p id="myP"></p>

<script>
// Change heading:
document.getElementById("myH").innerHTML = "My First Page";
// Change paragraph:
document.getElementById("myP").innerHTML = "My first paragraph.";
</script>

<p><st</pre>rong>Note:</strong> The comments are not executed.</p>


comments are not executed

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

<script>
var x = 5;      // Declare x, give it the value of 5
var y = x + 2;  // Declare y, give it the value of x + 2 

document.getElementById("demo").innerHTML = y; // Write y to demo
</script>

<p><strong>Note:</strong> The comments are not executed.</p>

The comments are not executed

<h1 id="myH"></h1>
<p id="myP"></p>

<script>
/*
The code below will change
the heading with id = "myH"
and the paragraph with id = "myp"
in my web page:
*/
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
</script>

<p><strong>Note:</strong> The comment block is not executed.</p>

The comments are not executed

<h1 id="myH"></h1>

<p id="myP"></p>

<script>
//document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
</script>

<p><strong>Note:</strong> The comment is not executed.</p>

The comments are not executed

<h1 id="myH"></h1>

<p id="myP"></p>

<script>
/*
document.getElementById("myH").innerHTML = "Welcome to my Homepage";
document.getElementById("myP").innerHTML = "This is my first paragraph.";
*/
</script>

<p><strong>Note:</strong> The comment-block is not executed.</p>

JavaScript Variables

<p>In this example, x, y, and z are variables.</p>

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

<script>
var x = 5;
var y = 6;
var z = x + y;
document.getElementById("demo").innerHTML =
"The value of z is: " + z;
</script>

</body>
</html>

JavaScript Variables

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

<script>
var price1 = 5;
var price2 = 6;
var total = price1 + price2;
document.getElementById("demo").innerHTML =
"The total is: " + total;
</script>

</body>
</html>

JavaScript Variables

<p>Strings are written with quotes.</p>
<p>Numbers are written without quotes.</p>

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

<script>
var pi = 3.14;
var person = "John Doe";
var answer = 'Yes I am!';

document.getElementById("demo").innerHTML =
pi + "<br>" + person + "<br>" + answer;
</script>

</body>
</html>

JavaScript Variables

<p>Create a variable, assign a value to it, and display it:</p>

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

<script>
var carName = "Volvo";
document.getElementById("demo").innerHTML = carName;
</script>

JavaScript Variables

<p>You can declare many variables in one statement.</p>

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

<script>
var person = "John Doe", carName = "Volvo", price = 200;
document.getElementById("demo").innerHTML = carName;
</script>

</body>
</html>

JavaScript Variables

<p>You can declare many variables in one statement.</p>

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

<script>
var person = "John Doe",
carName = "Volvo",
price = 200;
document.getElementById("demo").innerHTML = carName;
</script>

</body>
</html>

JavaScript Variables

<p>A variable declared without a value will have the value undefined.</p>

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

<script>
var carName;
document.getElementById("demo").innerHTML = carName;
</script>

</body>
</html>

JavaScript Variables

<p>If you re-declare a JavaScript variable, it will not lose its value.</p>

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

<script>
var carName = "Volvo";
var carName;
document.getElementById("demo").innerHTML = carName;
</script>

</body>
</html>

JavaScript Variables

<p>The result of adding 5 + 2 + 3:</p>

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

<script>
var x = 5 + 2 + 3;
document.getElementById("demo").innerHTML = x;
</script>

JavaScript Variables

<p>The result of adding "John" + " " + "Doe":</p>

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

<script>
var x = "John" + " " + "Doe";
document.getElementById("demo").innerHTML = x;
</script>

JavaScript Variables

<p>The result of adding "5" + 2 + 3:</p>

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

<script>
x = "5" + 2 + 3;
document.getElementById("demo").innerHTML = x;
</script>

JavaScript Variables

<p>The result of adding 2 + 3 + "5":</p>

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

<script>
var x = 2 + 3 + "5"
document.getElementById("demo").innerHTML = x;
</script>

JavaScript Operators

<p>x = 5, y = 2, calculate z = x + y, and display z:</p>

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

<script>
var x = 5;
var y = 2;
var z = x + y;
document.getElementById("demo").innerHTML = z;
</script>

The = Operator

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

<script>
var x = 10;
document.getElementById("demo").innerHTML = x;
</script>

The + Operator

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

<script>
var x = 5;
var y = 2;
var z = x + y;
document.getElementById("demo").innerHTML = z;
</script>

The * Operator

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

<script>
var x = 5;
var y = 2;
var z = x * y;
document.getElementById("demo").innerHTML = z;
</script>

The += Operator

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

<script>
var x = 10;
x += 5;
document.getElementById("demo").innerHTML = x;
</script>

JavaScript Operators

<p>The + operator concatenates (adds) strings.</p>

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

<script>
var txt1 = "John";
var txt2 = "Doe";
document.getElementById("demo").innerHTML = txt1 + " " + txt2;
</script>

JavaScript Operators

<p>The assignment operator += can concatenate strings.</p>

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

<script>
txt1 = "What a very ";
txt1 += "nice day";
document.getElementById("demo").innerHTML = txt1;
</script>

JavaScript Operators

<p>Adding a number and a string, returns a string.</p>

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

<script>
var x = 5 + 5;
var y = "5" + 5;
var z = "Hello" + 5;
document.getElementById("demo").innerHTML =
x + "<br>" + y + "<br>" + z;
</script>

A typical arithmetic operation takes two numbers and produces a new number.

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

<script>
var x = 100 + 50;
document.getElementById("demo").innerHTML = x;
</script>

h2>A typical arithmetic operation takes two numbers (or variables) and produces a new number.</h2>
<p id="demo"></p>

<script>
var a = 100;
var b = 50;
var x = a + b;
document.getElementById("demo").innerHTML = x;
</script>

arithmetic operation

<p>A typical arithmetic operation takes two numbers (or expressions) and produces a new number.</p>

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

<script>
var a = 3;
var x = (100 + 50) * a;
document.getElementById("demo").innerHTML = x;
</script>

The - Operator

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

<script>
var x = 5;
var y = 2;
var z = x - y;
document.getElementById("demo").innerHTML = z
</script>

The / Operator

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

<script>
var x = 5;
var y = 2;
var z = x / y;
document.getElementById("demo").innerHTML = z;
</script>

The % Operator

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

<script>
var x = 5;
var y = 2;
var z = x % y;
document.getElementById("demo").innerHTML = z;
</script>

The ++ Operator

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

<script>
var x = 5;
x++;
var z = x;
document.getElementById("demo").innerHTML = z;
</script>

The -- Operator

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

<script>
var x = 5;
x--;
var z = x;
document.getElementById("demo").innerHTML = z;
</script>

Multiplication

<p>Multiplication has precedence over addition.</p>

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

<script>
document.getElementById("demo").innerHTML = 100 + 50 * 3;
</script>

Multiplication

<p>Multiplication has precedence over addition.</p>
<p>But parenthesis has precedence over multiplication.</p>

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

<script>
document.getElementById("demo").innerHTML = (100 + 50) * 3;
</script>


many operations

<p>When many operations has the same precedence, they are computed from left to right.</p>

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

<script>
document.getElementById("demo").innerHTML = 100 + 50 - 3;
</script>


The = Operator

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

<script>
var x = 10;
document.getElementById("demo").innerHTML = x;
</script>

The += Operator

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

<script>
var x = 10;
x += 5;
document.getElementById("demo").innerHTML = x;
</script>

The -= Operator

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

<script>
var x = 10;
x -= 5;
document.getElementById("demo").innerHTML = x;
</script>

The *= Operator

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

<script>
var x = 10;
x *= 5;
document.getElementById("demo").innerHTML = x;
</script>

The /= Operator

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

<script>
var x = 10;
x /= 5;
document.getElementById("demo").innerHTML = x;
</script>

The %= Operator

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

<script>
var x = 10;
x %= 5;
document.getElementById("demo").innerHTML = x;
</script>

JavaScript

<p>When adding a number and a string, JavaScript will treat the number as a string.</p>

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

<script>
var x = 16 + "Volvo";
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

JavaScript

<p>When adding a string and a number, JavaScript will treat the number as a string.</p>

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

<script>
var x = "Volvo" + 16;
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

JavaScript

<p>JavaScript evaluates expressions from left to right. Different sequences can produce different results:</p>

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

<script>
var x = 16 + 4 + "Volvo";
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

JavaScript

<p>JavaScript evaluates expressions from left to right. Different sequences can produce different results:</p>

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

<script>
var x = "Volvo" + 16 + 4;
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

JavaScript Data Types

<p>JavaScript has dynamic types. This means that the same variable can be used to hold different data types:</p>

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

<script>
var x;               // Now x is undefined
x = 5;               // Now x is a Number
x = "John";          // Now x is a String

document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

JavaScript Strings

<p>Strings are written with quotes. You can use single or double quotes:</p>

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

<script>
var carName1 = "Volvo XC60";
var carName2 = 'Volvo XC60';

document.getElementById("demo").innerHTML =
carName1 + "<br>" + 
carName2; 
</script>

</body>
</html>

JavaScript Strings

<p>You can use quotes inside a string, as long as they don't match the quotes surrounding the string:</p>

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

<script>
var answer1 = "It's alright";
var answer2 = "He is called 'Johnny'";
var answer3 = 'He is called "Johnny"';

document.getElementById("demo").innerHTML =
answer1 + "<br>" + 
answer2 + "<br>" + 
answer3;
</script>

</body>
</html>

JavaScript Numbers

<p>Numbers can be written with, or without decimals:</p>

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

<script>
var x1 = 34.00;
var x2 = 34;
var x3 = 3.14;

document.getElementById("demo").innerHTML =
x1 + "<br>" + x2 + "<br>" + x3;
</script>

</body>
</html>

JavaScript Numbers

<p>Extra large or extra small numbers can be written with scientific (exponential) notation:</p>

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

<script>
var y = 123e5;
var z = 123e-5;

document.getElementById("demo").innerHTML =
y + "<br>" + z;
</script>

</body>
</html>

JavaScript Booleans

<p>Booleans can have two values: true or false:</p>

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

<script>
var x = 5;
var y = 5;
var z = 6;
document.getElementById("demo").innerHTML =
(x == y) + "<br>" + (x == z);
</script>

</body>
</html>

JavaScript Arrays

<p>Array indexes are zero-based, which means the first item is [0].</p>

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

<script>
var cars = ["Saab","Volvo","BMW"];

document.getElementById("demo").innerHTML = cars[0];
</script>

</body>
</html>

JavaScript Objects

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

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

document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>

JavaScript typeof

<p>The typeof operator returns the type of a variable or an expression.</p>

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

<script>
document.getElementById("demo").innerHTML = 
typeof "" + "<br>" +
typeof "John" + "<br>" + 
typeof "John Doe";
</script>
</body>
</html>



JavaScript typeof

<p>The typeof operator returns the type of a variable or an expression.</p>

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

<script>
document.getElementById("demo").innerHTML = 
typeof 0 + "<br>" + 
typeof 314 + "<br>" +
typeof 3.14 + "<br>" +
typeof (3) + "<br>" +
typeof (3 + 4);
</script>

</body>
</html>



variable with no value is undefined

<p>The value (and the data type) of a variable with no value is <b>undefined</b>.</p>

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

<script>
var car;
document.getElementById("demo").innerHTML =
car + "<br>" + typeof car;
</script>

Variables can be emptied

<p>Variables can be emptied if you set the value to <b>undefined</b>.</p>

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

<script>
var car = "Volvo";
car = undefined;
document.getElementById("demo").innerHTML =
car + "<br>" + typeof car;
</script>

empty string has both a legal value and a type

<p>An empty string has both a legal value and a type:</p>

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

<script>
var car = "";
document.getElementById("demo").innerHTML =
"The value is: " +
car + "<br>" +
"The type is: " + typeof car;
</script>

</body>
</html>

Objects can be emptied

<p>Objects can be emptied by setting the value to <b>null</b>.</p>

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

<script>
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
person = null;
document.getElementById("demo").innerHTML = typeof person;
</script>

Objects can be emptied

<p>Objects can be emptied by setting the value to <b>undefined</b>.</p>

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

<script>
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
person = undefined;
document.getElementById("demo").innerHTML = person;
</script>

Undefined and null are equal in value

<p>Undefined and null are equal in value but different in type:</p>

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

<script>
document.getElementById("demo").innerHTML =
typeof undefined + "<br>" +
typeof null + "<br><br>" +
(null === undefined) + "<br>" +
(null == undefined);
</script>

JavaScript typeof

<p>The typeof operator returns the type of a variable or an expression.</p>

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

<script>
document.getElementById("demo").innerHTML = 
typeof "john" + "<br>" + 
typeof 3.14 + "<br>" +
typeof true + "<br>" +
typeof false + "<br>" +
typeof x;
</script>

</body>
</html>



JavaScript typeof

<p>The typeof operator returns object for both objects, arrays, and null.</p>
<p>The typeof operator does not return object for functions.</p>

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

<script>
document.getElementById("demo").innerHTML = 
typeof {name:'john', age:34} + "<br>" +
typeof [1,2,3,4] + "<br>" +
typeof null + "<br>" +
typeof function myFunc(){};
</script>

</body>
</html>



JavaScript Functions

<p>This example calls a function which performs a calculation, and returns the result:</p>

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

<script>
function myFunction(p1, p2) {
    return p1 * p2;
}
document.getElementById("demo").innerHTML = myFunction(4, 3);
</script>

JavaScript Functions

<p>This example calls a function which performs a calculation and returns the result:</p>

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

<script>
var x = myFunction(4, 3);
document.getElementById("demo").innerHTML = x;

function myFunction(a, b) {
    return a * b;
}
</script>

JavaScript Functions

<p>This example calls a function to convert from Fahrenheit to Celsius:</p>
<p id="demo"></p>

<script>
function toCelsius(f) {
    return (5/9) * (f-32);
}
document.getElementById("demo").innerHTML = toCelsius(77);
</script>

JavaScript Functions toCelsius

<p>Accessing a function without () will return the function definition instead of the function result:</p>
<p id="demo"></p>

<script>
function toCelsius(f) {
    return (5/9) * (f-32);
}
document.getElementById("demo").innerHTML = toCelsius;
</script>

JavaScript Functions toCelsius

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

<script>
document.getElementById("demo").innerHTML =
"The temperature is " + toCelsius(77) + " Celsius";

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

</body>
</html>



Creating a JavaScript Variable.

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

<script>
var car = "Fiat";
document.getElementById("demo").innerHTML = car;
</script>

Creating a JavaScript Object.

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

<script>
var car = {type:"Fiat", model:"500", color:"white"};
document.getElementById("demo").innerHTML = car.type;
</script>

Creating a JavaScript Object.

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

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

document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>

Creating a JavaScript Object.

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

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

document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>

====
There are two different ways to access an object property: 
</p>
<p>You can use person.property or person["property"].</p>

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

<script>
var person = {
    firstName: "John",
    lastName : "Doe",
    id       :  5566
};
document.getElementById("demo").innerHTML =
person.firstName + " " + person.lastName;
</script>

</body>
</html>


====
There are two different ways to access an object property: 
</p>
<p>You can use person.property or person["property"].</p>

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

<script>
var person = {
    firstName: "John",
    lastName : "Doe",
    id       :  5566
};
document.getElementById("demo").innerHTML =
person["firstName"] + " " + person["lastName"];
</script>

</body>
</html>

Creating and using an object method.

<p>An object method is a function definition, stored as a property value.</p>

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

<script>
var person = {
    firstName: "John",
    lastName : "Doe",
    id       : 5566,
    fullName : function() {
       return this.firstName + " " + this.lastName;
    }
};

document.getElementById("demo").innerHTML = person.fullName();
</script>

JavaScript Object Methods

<p>If you access an object method without (), it will return the function definition:</p>

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

<script>
var person = {
    firstName: "John",
    lastName : "Doe",
    id       : 5566,
    fullName : function() {
       return this.firstName + " " + this.lastName;
    }
};

document.getElementById("demo").innerHTML = person.fullName;
</script>

The local variable carName cannot be accessed from code outside the function:

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

<script>
myFunction();
document.getElementById("demo").innerHTML =
"The type of carName is " + typeof carName;

function myFunction() {
    var carName = "Volvo";
}
</script>

</body>
</html>

A GLOBAL variable can be accessed from any script or function.

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

<script>
var carName = "Volvo";
myFunction();

function myFunction() {
    document.getElementById("demo").innerHTML =
    "I can display " + carName;
}
</script>

</body>
</html>


====
If you assign a value to a variable that has not been declared,
it will automatically become a GLOBAL variable:
</p>

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

<script>
myFunction();

// code here can use carName as a global variable
document.getElementById("demo").innerHTML = "I can display " + carName;

function myFunction() {
    carName = "Volvo";
}
</script>

</body>
</html>


====
In HTML, all global variables will become window variables.
</p>

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

<script>
var carName = "Volvo";

// code here can use window.carName
document.getElementById("demo").innerHTML = "I can display " + window.carName;
</script>

</body>
</html>

Date()

<button onclick="document.getElementById('demo').innerHTML=Date()">The time is?</button>

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

Date()

<button onclick="this.innerHTML=Date()">The time is?</button>

Click the button to display the date.

<button onclick="displayDate()">The time is?</button>

<script>
function displayDate() {
    document.getElementById("demo").innerHTML = Date();
}
</script>

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

JavaScript Strings

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

<script>
var x = "John Doe";  // String written inside quotes
document.getElementById("demo").innerHTML = x;
</script>

JavaScript Strings

<p>Strings are written inside quotes. You can use single or double quotes:</p>

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

<script>

var carName1 = "Volvo XC60"; // Double quotes
var carName2 = 'Volvo XC60'; // Single quotes

document.getElementById("demo").innerHTML =
carName1 + " " + carName2; 

</script>

</body>
</html>

JavaScript Strings

<p>You can use quotes inside a string, as long as they don't match the quotes surrounding the string.</p>

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

<script>

var answer1 = "It's alright";
var answer2 = "He is called 'Johnny'";
var answer3 = 'He is called "Johnny"'; 

document.getElementById("demo").innerHTML =
answer1 + "<br>" + answer2 + "<br>" + answer3; 

</script>

</body>
</html>

JavaScript String Properties

<p>The length property returns the length of a string:</p>

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

<script>
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
document.getElementById("demo").innerHTML = txt.length;
</script>

</body>
</html>

JavaScript Strings

<p>The escape sequence \" inserts a double quote in a string.</p>

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

<script>

var x = "We are the so-called \"Vikings\" from the north.";
document.getElementById("demo").innerHTML = x; 

</script>

</body>
</html>

JavaScript Strings

<p>The escape sequence \' inserts a single quote in a string.</p>

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

<script>

var x = 'It\'s alright.';
document.getElementById("demo").innerHTML = x; 

</script>

</body>
</html>

JavaScript Strings

<p>The escape sequence \\ inserts a backslash in a string.</p>

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

<script>

var x = "The character \\ is called backslash.";
document.getElementById("demo").innerHTML = x; 

</script>

</body>
</html>

JavaScript Strings

<p>
You can break a code line within a text string with a backslash.
</p>

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

<script>
document.getElementById("demo").innerHTML = "Hello \
Dolly!";
</script>

JavaScript Strings

<p>
The safest way to break a code line in a string is using string addition.
</p>

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

<script>
document.getElementById("demo").innerHTML = "Hello " +
"Dolly!";
</script>

JavaScript Statements

<p id="demo">You cannot break a code line with a \ backslash.</p>

<script>
document.getElementById("demo").innerHTML = \
"Hello Dolly.";
</script>

typeof

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

<script>
var x = "John";              // x is a string
var y = new String("John");  // y is an object

document.getElementById("demo").innerHTML =
typeof x + "<br>" + typeof y;
</script>

Never Create Strings as objects.

<p>Strings and objects cannot be safely compared.</p>

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

<script>
var x = "John";              // x is a string
var y = new String("John");  // y is an object
document.getElementById("demo").innerHTML = (x==y);
</script>


Never Create Strings as objects.

<p>Strings and objects cannot be safely compared.</p>

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

<script>
var x = "John";              // x is a string
var y = new String("John");  // y is an object
document.getElementById("demo").innerHTML = (x===y);
</script>


Never Create Strings as objects.

<p>JavaScript objects cannot be compared.</p>

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

<script>
var x = new String("John");  // x is an object
var y = new String("John");  // y is an object
document.getElementById("demo").innerHTML = (x==y);
</script>


Never Create Strings as objects.

<p>JavaScript objects cannot be compared.</p>

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

<script>
var x = new String("John");  // x is an object
var y = new String("John");  // y is an object
document.getElementById("demo").innerHTML = (x===y);
</script>


JavaScript String Methods

<p>The indexOf() method returns the position of the first occurrence of a specified text:</p>

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

<script>
var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate");
document.getElementById("demo").innerHTML = pos;
</script>

</body>
</html>

JavaScript String Methods

<p>The lastIndexOf() method returns the position of the last occurrence of a specified text:</p>

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

<script>
var str = "Please locate where 'locate' occurs!";
var pos = str.lastIndexOf("locate");
document.getElementById("demo").innerHTML = pos;
</script>

</body>
</html>

JavaScript String Methods

<p>The indexOf() method accepts a second parameter as the starting position for the search:</p>

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

<script>
var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate",15);
document.getElementById("demo").innerHTML = pos;
</script>

</body>
</html>

JavaScript String Methods

<p>The search() method returns the position of the first occurrence of a specified text in a string:</p>

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

<script>
var str = "Please locate where 'locate' occurs!";
var pos = str.search("locate");
document.getElementById("demo").innerHTML = pos;
</script>

</body>
</html>

JavaScript String Methods

<p>The slice() method extract a part of a string
and returns the extracted parts in a new string:</p>

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

<script>
var str = "Apple, Banana, Kiwi";
var res = str.slice(7,13);
document.getElementById("demo").innerHTML = res; 
</script>

</body>
</html>

JavaScript String Methods

<p>The slice() method extract a part of a string
and returns the extracted parts in a new string:</p>

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

<script>
var str = "Apple, Banana, Kiwi";
var res = str.slice(-12,-6);
document.getElementById("demo").innerHTML = res;
</script>

</body>
</html>

JavaScript String Methods

<p>The slice() method extract a part of a string
and returns the extracted parts in a new string:</p>

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

<script>
var str = "Apple, Banana, Kiwi";
var res = str.slice(7);
document.getElementById("demo").innerHTML = res;
</script>

</body>
</html>

JavaScript String Methods

<p>The slice() method extract a part of a string
and returns the extracted parts in a new string:</p>

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

<script>
var str = "Apple, Banana, Kiwi";
var res = str.slice(-12) 
document.getElementById("demo").innerHTML = res;
</script>

</body>
</html>

JavaScript String Methods

<p>The substr() method extract a part of a string
and returns the extracted parts in a new string:</p>

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

<script>
var str = "Apple, Banana, Kiwi";
var res = str.substring(7,13);
document.getElementById("demo").innerHTML = res;
</script>

</body>
</html>

JavaScript String Methods

<p>The substr() method extract a part of a string
and returns the extracted parts in a new string:</p>

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

<script>
var str = "Apple, Banana, Kiwi";
var res = str.substr(7,6);
document.getElementById("demo").innerHTML = res;
</script>

</body>
</html>

JavaScript String Methods

<p>Replace "Microsoft" with "W3Schools" in the paragraph below:</p>

<button onclick="myFunction()">Try it</button>

<p id="demo">Please visit Microsoft!</p>

<script>
function myFunction() {
    var str = document.getElementById("demo").innerHTML; 
    var txt = str.replace("Microsoft","W3Schools");
    document.getElementById("demo").innerHTML = txt;
}
</script>

</body>
</html>

JavaScript String Methods

<p>Replace "Microsoft" with "W3Schools" in the paragraph below:</p>

<button onclick="myFunction()">Try it</button>

<p id="demo">Please visit Microsoft and Microsoft!</p>

<script>
function myFunction() {
    var str = document.getElementById("demo").innerHTML; 
    var txt = str.replace("Microsoft","W3Schools");
    document.getElementById("demo").innerHTML = txt;
}
</script>

</body>
</html>

JavaScript String Methods

<p>Replace "Microsoft" with "W3Schools" in the paragraph below:</p>

<button onclick="myFunction()">Try it</button>

<p id="demo">Please visit Microsoft!</p>

<script>
function myFunction() {
    var str = document.getElementById("demo").innerHTML; 
    var txt = str.replace("MICROSOFT","W3Schools");
    document.getElementById("demo").innerHTML = txt;
}
</script>

<p>The example does not work because MICROSOFT is written with upper case letters."</p>

</body>
</html>

JavaScript String Methods

<p>Replace "Microsoft" with "W3Schools" in the paragraph below:</p>

<button onclick="myFunction()">Try it</button>

<p id="demo">Please visit Microsoft!</p>

<script>
function myFunction() {
    var str = document.getElementById("demo").innerHTML; 
    var txt = str.replace(/MICROSOFT/i,"W3Schools");
    document.getElementById("demo").innerHTML = txt;
}
</script>

</body>
</html>

JavaScript String Methods

<p>Replace all occurrences of "Microsoft" with "W3Schools" in the paragraph below:</p>

<button onclick="myFunction()">Try it</button>

<p id="demo">Please visit Microsoft and Microsoft!</p>

<script>
function myFunction() {
    var str = document.getElementById("demo").innerHTML; 
    var txt = str.replace(/Microsoft/g,"W3Schools");
    document.getElementById("demo").innerHTML = txt;
}
</script>

</body>
</html>

Convert string to upper case:

<button onclick="myFunction()">Try it</button>

<p id="demo">Hello World!</p>

<script>
function myFunction() {
    var text = document.getElementById("demo").innerHTML;
    document.getElementById("demo").innerHTML = text.toUpperCase();
}
</script>

</body>
</html>

Convert string to lower case:

<button onclick="myFunction()">Try it</button>

<p id="demo">Hello World!</p>

<script>
function myFunction() {
    var text = document.getElementById("demo").innerHTML;
    document.getElementById("demo").innerHTML = text.toLowerCase();
}
</script>

</body>
</html>

JavaScript String Methods

<p>The concat() method joins two or more strings:</p>

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

<script>
var text1 = "Hello";
var text2 = "World!";
var text3 = text1.concat(" ",text2);
document.getElementById("demo").innerHTML = text3;
</script>

</body>
</html>

The charAt() method returns the character at a given position in a string:

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

<script>
var str = "HELLO WORLD";
document.getElementById("demo").innerHTML = str.charAt(0);
</script>
</body>
</html>

h2>The charCodeAt() method returns the unicode of the character at a given position in a string:</h2>
<p id="demo"></p>

<script>
var str = "HELLO WORLD";
document.getElementById("demo").innerHTML = str.charCodeAt(0);
</script>
</body>
</html>

Click "Try it" to display the first array element, after a string split.

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var str = "a,b,c,d,e,f";
    var arr = str.split(",");
    document.getElementById("demo").innerHTML = arr[0];
}
</script>

</body>
</html>

str.split

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

<script>
var str = "Hello";
var arr = str.split("");
var text = "";
var i;
for (i = 0; i < arr.length; i++) {
    text += arr[i] + "<br>"
}
document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>



JavaScript Numbers

<p>Numbers can be written with or without decimals:</p>

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

<script>
var x = 3.14;
var y = 3;
document.getElementById("demo").innerHTML = x + "<br>" + y;
</script>

JavaScript Numbers

<p>Extra large or extra small numbers can be written with scientific (exponent) notation:</p>

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

<script>
var x = 123e5;
var y = 123e-5;
document.getElementById("demo").innerHTML = x + "<br>" + y;
</script>

JavaScript Numbers

<p>Integers (numbers without a period or exponent notation) are accurate up to 15 digits:</p>

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

<script>
var x = 999999999999999;
var y = 9999999999999999;
document.getElementById("demo").innerHTML = x + "<br>" + y;
</script>

</body>
</html>

JavaScript Numbers

<p>Floating point arithmetic is not always 100% accurate.</p>

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

<script>
var x = 0.2 + 0.1;
document.getElementById("demo").innerHTML = "0.2 + 0.1 = " + x;
</script>

</body>
</html>

JavaScript Numbers

<p>Floating point arithmetic is not always 100% accurate:</p>
<p id="demo1"></p>

<p>But it helps to multiply and divide:</p>

<p id="demo2"></p>

<script>
var x = 0.2 + 0.1;
document.getElementById("demo1").innerHTML = "0.2 + 0.1 = " + x;
var y = (0.2*10 + 0.1*10) / 10;
document.getElementById("demo2").innerHTML = "0.2 + 0.1 = " + y;
</script>

</body>
</html>

JavaScript Numbers

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

<script>
var x = 10;
var y = 20;
var z = x + y;
document.getElementById("demo").innerHTML = z;
</script>

</body>
</html>

JavaScript Numbers

<p>If you add two strings, the result will be a string:</p>

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

<script>
var x = "10";
var y = "20";
var z = x + y;
document.getElementById("demo").innerHTML = z;
</script>

</body>
</html>

JavaScript Numbers

<p>If you add a number and a string, the result will be a string:</p>

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

<script>
var x = 10;
var y = "20";
var z = x + y;
document.getElementById("demo").innerHTML = z;
</script>

</body>
</html>

JavaScript Numbers

<p>If you add a string and a number, the result will be a string:</p>

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

<script>
var x = "10";
var y = 20;
document.getElementById("demo").innerHTML =
"The result is: " + x + y;
</script>

</body>
</html>

JavaScript Numbers

<p>A common mistake is to expect this result to be 30:</p>

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

<script>
var x = 10;
var y = 20;
document.getElementById("demo").innerHTML =
"The result is: " + x + y;
</script>

</body>
</html>

JavaScript Numbers

<p>A common mistake is to expect this result to be 102030:</p>

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

<script>
var x = 10;
var y = 20;
var z = "30";
var result = x + y + z;
document.getElementById("demo").innerHTML = result;
</script>

</body>
</html>

JavaScript Numbers

<p>JavaScript will try to convert strings to numbers in numeric operations:</p>

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

<script>
var x = "100";
var y = "10";
var z = x / y;   
document.getElementById("demo").innerHTML = z;
</script>

JavaScript Numbers

<p>JavaScript will try to convert strings to numbers in numeric operations:</p>

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

<script>
var x = "100";
var y = "10";
var z = x * y;   
document.getElementById("demo").innerHTML = z;
</script>

JavaScript Numbers

<p>JavaScript will try to convert strings to numbers in numeric operations:</p>

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

<script>
var x = "100";
var y = "10";
var z = x - y;   
document.getElementById("demo").innerHTML = z;
</script>

JavaScript Numbers

<p>JavaScript will concatenate (not add) to strings:</p>

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

<script>
var x = "100";
var y = "10";
var z = x + y;   
document.getElementById("demo").innerHTML = z;
</script>

JavaScript Numbers

<p>A number divided by a non-numeric string becomes NaN (Not a Number):</p>

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

<script>
document.getElementById("demo").innerHTML = 100 / "Apple";
</script>

JavaScript Numbers

<p>A number divided by a numeric string becomes a number:</p>

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

<script>
document.getElementById("demo").innerHTML = 100 / "10";
</script>

JavaScript Numbers

<p>You can use the global JavaScript function isNaN() to find out if a value is a number:</p>

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

<script>
var x = 100 / "Apple";
document.getElementById("demo").innerHTML = isNaN(x);
</script>

JavaScript Numbers

<p>If you use NaN in a mathematical operation, the result will also be NaN:</p>

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

<script>
var x = NaN;
var y = 5;
document.getElementById("demo").innerHTML = x + y;
</script>

JavaScript Numbers

<p>If you use NaN in a mathematical operation, the result can be a concatenation:</p>

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

<script>
var x = NaN;
var y = "5";
document.getElementById("demo").innerHTML = x + y;
</script>

JavaScript Numbers

<p>The typeof NaN is number:</p>

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

<script>
var x = NaN;
document.getElementById("demo").innerHTML = typeof x;
</script>

</body>
</html>

JavaScript Numbers

<br>

JavaScript Numbers

<p>Infinity is returned if you calculate a number outside the largest possible number:</p> <p id="demo"></p> <script> var myNumber = 2; var txt = ""; while (myNumber != Infinity) { myNumber = myNumber * myNumber; txt = txt + myNumber + "<br>"; } document.getElementById("demo").innerHTML = txt; </script> </body> </html>

JavaScript Numbers

<p>Division by zero generates Infinity;</p>

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

<script>
var x = 2/0;
var y = -2/0;
document.getElementById("demo").innerHTML = x + "<br>" + y;
</script>

</body>
</html>

JavaScript Numbers

<p>Infinity is a number:</p>

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

<script>
var x = Infinity;
document.getElementById("demo").innerHTML = typeof x;
</script>

</body>
</html>

JavaScript Numbers

<p>Numeric constants, preceded by 0x, are interpreted as hexadecimal:</p>

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

<script>
var x = 0xFF;
document.getElementById("demo").innerHTML = "0xFF = " + x;
</script>

</body>
</html>

JavaScript Numbers

<p>The toString() method can output numbers as base 16 (hex), base 8 (octal), or base 2 (binary).</p>

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

<script>
var myNumber = 128;
document.getElementById("demo").innerHTML = "128 = " + 
myNumber + " Decimal, " +
myNumber.toString(16) + " Hexadecimal, " +
myNumber.toString(8) + " Octal, " +
myNumber.toString(2) + " Binary."
</script>

JavaScript Numbers

<br>

JavaScript Numbers

<p>Numbers can be typeof number or typeof object.</p> <p>There is no need to create numbers as objects.</p> <p id="demo"></p> <script> var x = 123; var y = new Number(123); document.getElementById("demo").innerHTML = typeof x + "<br>" + typeof y; </script>

Never create numbers as objects.

<p>Numbers and objects cannot be safely compared.</p>

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

<script>
var x = 500;              // x is a number
var y = new Number(500);  // y is an object
document.getElementById("demo").innerHTML = (x==y);
</script>


Never create numbers as objects.

<p>Numbers and objects cannot be safely compared.</p>

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

<script>
var x = 500;              // x is a number
var y = new Number(500);  // y is an object
document.getElementById("demo").innerHTML = (x===y);
</script>


Never create numbers as objects.

<p>JavaScript objects cannot be compared.</p>

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

<script>
var x = new Number(500);  // x is an object
var y = new Number(500);  // y is an object
document.getElementById("demo").innerHTML = (x==y);
</script>


The JavaScript toString() Method

<p>The toString() method converts a number to a string.</p>

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

<script>
var x = 123;
document.getElementById("demo").innerHTML =
    x.toString() + "<br>" +
   (123).toString() + "<br>" +
   (100 + 23).toString();
</script>

toExponential

<br>

<p>The toExponential() method returns a string, with the number rounded and written using exponential notation.</p>

<p>An optional parameter defines the number of digits behind the decimal point.</p>

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

<script>
var x = 9.656;
document.getElementById("demo").innerHTML =
    x.toExponential() + "<br>" + 
    x.toExponential(2) + "<br>" + 
    x.toExponential(4) + "<br>" + 
    x.toExponential(6);
</script>


toFixed()

<br>

<p>The toFixed() method rounds a number to a given number of digits.</p>
<p>For working with money, toFixed(2) is perfect.</p>

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

<script>
var x = 9.656;
document.getElementById("demo").innerHTML =
    x.toFixed(0) + "<br>" +
    x.toFixed(2) + "<br>" +
    x.toFixed(4) + "<br>" +
    x.toFixed(6);
</script>

h2>The toPrecision() method returns a string, with a number written with a specified length:</h2>
<p id="demo"></p>

<script>
var x = 9.656;
document.getElementById("demo").innerHTML = 
    x.toPrecision() + "<br>" +
    x.toPrecision(2) + "<br>" +
    x.toPrecision(4) + "<br>" +
    x.toPrecision(6);    
</script>

valueOf

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

<script>
var x = 123;

document.getElementById("demo").innerHTML = 
    x.valueOf() + "<br>" +
    (123).valueOf() + "<br>" +
    (100 + 23).valueOf();
</script>


JavaScript Number Methods

<p>The JavaScript function Number() converts variables to numbers:</p>

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

<script>
document.getElementById("demo").innerHTML = 
    Number(true) + "<br>" +
    Number(false) + "<br>" +
    Number("  10") + "<br>" +
    Number("10  ") + "<br>" +
    Number("10 6") + "<br>" + 
    Number("John");
</script>

</body>
</html>

JavaScript Number Methods

<p>The JavaScript function Number() can convert a date to a number:</p>

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

<script>
var x = new Date("2017-09-30");
document.getElementById("demo").innerHTML = Number(x); 
</script>

</body>
</html>

parseInt() converts strings to numbers

<br>

<p>The global JavaScript function parseInt() converts strings to numbers:</p>

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

<script>
document.getElementById("demo").innerHTML = 
    parseInt("10") + "<br>" +
    parseInt("10.33") + "<br>" +
    parseInt("10 6") + "<br>" +    
    parseInt("10 years") + "<br>" +    
    parseInt("years 10");    
</script>

</body>
</html>



parseFloat() converts strings to numbers

<br>

<p>The global JavaScript function parseFloat() converts strings to numbers:</p>

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

<script>
document.getElementById("demo").innerHTML = 
    parseFloat("10") + "<br>" +
    parseFloat("10.33") + "<br>" +
    parseFloat("10 6") + "<br>" +    
    parseFloat("10 years") + "<br>" +
    parseFloat("years 10");        
</script>

</body>
</html>



MAX_VALUE

<br>

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

<script>
document.getElementById("demo").innerHTML = Number.MAX_VALUE;
</script>


MAX_VALUE

<br>

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

<script>
var x = 6;
document.getElementById("demo").innerHTML = x.MAX_VALUE;
</script>


JavaScript Arrays

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

<script>
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
</script>

</body>
</html>

JavaScript Arrays

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

<script>
var cars = [
    "Saab",
    "Volvo",
    "BMW"
];
document.getElementById("demo").innerHTML = cars;
</script>

</body>
</html>

JavaScript Arrays

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

<script>
var cars = new Array("Saab", "Volvo", "BMW");
document.getElementById("demo").innerHTML = cars;
</script>

</body>
</html>

JavaScript Arrays

<p>JavaScript array elements are accesses using numeric indexes (starting from 0).</p>

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

<script>
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars[0];
</script>

</body>
</html>

JavaScript Arrays

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

<script>
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
</script>

</body>
</html>

JavaScript Arrays

<p>Arrays use numbers to access its elements.</p>

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

<script>
var person = ["John", "Doe", 46];
document.getElementById("demo").innerHTML = person[0];
</script>

</body>
</html

JavaScript Objects

<p>JavaScript uses names to access object properties.</p>
<p id="demo"></p>

<script>
var person = {firstName:"John", lastName:"Doe", age:46};
document.getElementById("demo").innerHTML = person["firstName"];
</script>

</body>
</html


JavaScript Arrays

<p>The length property returns the length of an array.</p>

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

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.length;
</script>


JavaScript Arrays

<p>The best way to loop through an array is using a standard for loop:</p>

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

<script>
var fruits, text, fLen, i;

fruits = ["Banana", "Orange", "Apple", "Mango"];
fLen = fruits.length;
text = "<ul>";
for (i = 0; i < fLen; i++) {
    text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";
document.getElementById("demo").innerHTML = text;
</script>

JavaScript Arrays

<p>The push method appends a new element to an array.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;

function myFunction() {
    fruits.push("Lemon");
    document.getElementById("demo").innerHTML = fruits;
}
</script>

JavaScript Arrays

<p>The length property provides an easy way to append new elements to an array without using the push() method.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;

function myFunction() {
    fruits[fruits.length] = "Lemon";
    document.getElementById("demo").innerHTML = fruits;
}
</script>

JavaScript Arrays

<p>Adding elements with high indexes can create undefined "holes" in an array.</p>

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

<script>
var fruits, text, fLen, i;
fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[6] = "Lemon";

fLen = fruits.length;
text = "";
for (i = 0; i < fLen; i++) {
    text += fruits[i] + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>

JavaScript Arrays

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

<script>
var person = [];
person[0] = "John";
person[1] = "Doe";
person[2] = 46; 
document.getElementById("demo").innerHTML =
person[0] + " " + person.length;
</script>

</body>
</html>

JavaScript Arrays

<p>If you use a named index when accessing an array, JavaScript will redefine the array to a standard object, and some array methods and properties will produce undefined or incorrect results.</p>

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

<script>
var person = [];
person["firstName"] = "John";
person["lastName"] = "Doe";
person["age"] = 46; 
document.getElementById("demo").innerHTML =
person[0] + " " + person.length;
</script>

</body>
</html>

JavaScript Arrays

<p>Avoid using new Array(). Use [] instead.</p>

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

<script>
//var points = new Array(40, 100, 1, 5, 25, 10);
var points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = points[0];    
</script>

JavaScript Arrays

<p>Avoid using new Array().</p>

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

<script>
var points = new Array(40);
document.getElementById("demo").innerHTML = points[0];    
</script>

JavaScript Arrays

<p>The typeof operator, when used on an array, returns object:</p>

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

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = typeof fruits;
</script>

JavaScript Arrays

<p>The new ECMASCRIPT 5 method isArray returns true when used on an array:</p>

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

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = Array.isArray(fruits);
</script>

JavaScript Arrays

<p>This "home made" isArray() function returns true when used on an array:</p>

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

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = isArray(fruits);

function isArray(myArray) {
    return myArray.constructor.toString().indexOf("Array") > -1;
}
</script>

JavaScript Arrays

<p>The instanceof operator returns true when used on an array:</p>

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

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits instanceof Array;
</script>

JavaScript Array Methods


toString()

<p>The toString() method returns an array as a comma separated string:</p> <p id="demo"></p> <script> var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo").innerHTML = fruits.toString(); </script>

JavaScript Array Methods


join()

<p>The join() method joins array elements into a string.</p> <p>It this example we have used " * " as a separator between the elements:</p> <p id="demo"></p> <script> var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo").innerHTML = fruits.join(" * "); </script>

JavaScript Array Methods


pop()

<p>The pop() method removes the last element from an array.</p> <p id="demo1"></p> <p id="demo2"></p> <script> var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo1").innerHTML = fruits; fruits.pop(); document.getElementById("demo2").innerHTML = fruits; </script>

JavaScript Array Methods


pop()

<p>The pop() method removes the last element from an array.</p> <p>The return value of the pop() method is the removed item.</p> <p id="demo1"></p> <p id="demo2"></p> <p id="demo3"></p> <script> var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo1").innerHTML = fruits; document.getElementById("demo2").innerHTML = fruits.pop(); document.getElementById("demo3").innerHTML = fruits; </script>

JavaScript Array Methods


push()

<p>The push() method appends a new element to an array.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo").innerHTML = fruits; function myFunction() { fruits.push("Kiwi"); document.getElementById("demo").innerHTML = fruits; } </script>

JavaScript Array Methods


push()

<p>The push() method returns the new array length.</p> <button onclick="myFunction()">Try it</button> <p id="demo1"></p> <p id="demo2"></p> <script> var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo1").innerHTML = fruits; function myFunction() { document.getElementById("demo2").innerHTML = fruits.push("Kiwi"); document.getElementById("demo1").innerHTML = fruits; } </script>

JavaScript Array Methods


shift()

<p>The shift() method removes the first element of an array (and "shifts" all other elements to the left):</p> <p id="demo1"></p> <p id="demo2"></p> <script> var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo1").innerHTML = fruits; fruits.shift(); document.getElementById("demo2").innerHTML = fruits; </script>

JavaScript Array Methods


shift()

<p>The shift() method returns the element that was shifted out.</p> <p id="demo1"></p> <p id="demo2"></p> <p id="demo3"></p> <script> var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo1").innerHTML = fruits; document.getElementById("demo2").innerHTML = fruits.shift(); document.getElementById("demo3").innerHTML = fruits; </script>

JavaScript Array Methods


unshift()

<p>The unshift() method adds new elements to the beginning of an array.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo").innerHTML = fruits; function myFunction() { fruits.unshift("Lemon"); document.getElementById("demo").innerHTML = fruits; } </script>

JavaScript Array Methods


unshift()

<p>The unshift() method returns the length of the new array:</p> <p id="demo1"></p> <p id="demo2"></p> <p id="demo3"></p> <script> var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo1").innerHTML = fruits; document.getElementById("demo2").innerHTML = fruits.unshift("Lemon"); document.getElementById("demo3").innerHTML = fruits; </script> <p><b>Note:</b> The unshift() method does not work properly in Internet Explorer 8 and earlier, the values will be inserted, but the return value will be <em>undefined</em>.</p>

JavaScript Array Methods

<p>Array elements are accessed using their index number:</p>

<p id="demo1"></p>
<p id="demo2"></p>

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits;
fruits[0] = "Kiwi";
document.getElementById("demo2").innerHTML = fruits;
</script>

JavaScript Array Methods

<p>The length property provides an easy way to append new elements to an array without using the push() method.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;

function myFunction() {
    fruits[fruits.length] = "Kiwi";
    document.getElementById("demo").innerHTML = fruits;
}
</script>

JavaScript Array Methods

<p>Deleting elements leaves undefined holes in an array.</p>

<p id="demo1"></p>
<p id="demo2"></p>

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML =
"The first fruit is: " + fruits[0];
delete fruits[0];
document.getElementById("demo2").innerHTML =
"The first fruit is: " + fruits[0];
</script>

JavaScript Array Methods


splice()

<p>The splice() method adds new elements to an array.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo").innerHTML = fruits; function myFunction() { fruits.splice(2, 0, "Lemon", "Kiwi"); document.getElementById("demo").innerHTML = fruits; } </script>

JavaScript Array Methods


splice()

<p>The splice() methods can be used to remove array elements.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo").innerHTML = fruits; function myFunction() { fruits.splice(0, 1); document.getElementById("demo").innerHTML = fruits; } </script>

JavaScript Array Methods


concat()

<p>The concat() method is used to merge (concatenate) arrays:</p> <p id="demo"></p> <script> var myGirls = ["Cecilie", "Lone"]; var myBoys = ["Emil", "Tobias", "Linus"]; var myChildren = myGirls.concat(myBoys); document.getElementById("demo").innerHTML = myChildren; </script>

JavaScript Array Methods


concat()

<p>The concat() method is used to merge (concatenate) arrays:</p> <p id="demo"></p> <script> var arr1 = ["Cecilie", "Lone"]; var arr2 = ["Emil", "Tobias", "Linus"]; var arr3 = ["Robin", "Morgan"]; var myChildren = arr1.concat(arr2, arr3); document.getElementById("demo").innerHTML = myChildren; </script>

JavaScript Array Methods


concat()

<p>The concat() method can also merge values to arrays:</p> <p id="demo"></p> <script> var arr1 = ["Cecilie", "Lone"]; var myChildren = arr1.concat(["Emil", "Tobias", "Linus"]); document.getElementById("demo").innerHTML = myChildren; </script>

JavaScript Array Methods


slice()

<p>This example slices out a part of an array starting from array element 1 ("Orange"):</p> <p id="demo"></p> <script> var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"]; var citrus = fruits.slice(1); document.getElementById("demo").innerHTML = fruits + "<br><br>" + citrus; </script>

JavaScript Array Methods


slice()

<p>This example slices out a part of an array starting from array element 3 ("Apple")</p> <p id="demo"></p> <script> var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"]; var citrus = fruits.slice(3); document.getElementById("demo").innerHTML = fruits + "<br><br>" + citrus; </script>

JavaScript Array Methods


slice()

<p>When the slice() method is given two arguments, it selects array elements from the start argument, and up to (but not included) the end argument:</p> <p id="demo"></p> <script> var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"]; var citrus = fruits.slice(1,3); document.getElementById("demo").innerHTML = fruits + "<br><br>" + citrus; </script>

JavaScript Array Methods


slice()

<p>This example slices out a part of an array starting from array element 2 ("Lemon"):</p> <p id="demo"></p> <script> var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"]; var citrus = fruits.slice(2); document.getElementById("demo").innerHTML = fruits + "<br><br>" + citrus; </script>

JavaScript Array Methods

<p>JavaScript automatically converts an array to a comma separated string when a simple value is expected:</p>

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

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;
</script>

JavaScript Array Sort

<p>The sort() method sorts an array alphabetically.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;

function myFunction() {
    fruits.sort();
    document.getElementById("demo").innerHTML = fruits;
}
</script>

JavaScript Array Sort

<p>The sort() method sorts an array alphabetically.</p>
<p>The reverse() method reverts the elements.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;

function myFunction() {
    fruits.sort();
    fruits.reverse();
    document.getElementById("demo").innerHTML = fruits;
}
</script>

JavaScript Array Sort

<p>Click the button to sort the array in ascending order.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
var points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = points;    

function myFunction() {
    points.sort(function(a, b){return a - b});
    document.getElementById("demo").innerHTML = points;
}
</script>

JavaScript Array Sort

<p>Click the button to sort the array in descending order.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
var points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = points;

function myFunction() {
    points.sort(function(a, b){return b - a});
    document.getElementById("demo").innerHTML = points;
}
</script>

</body>
</html>

JavaScript Array Sort

<p>Click the buttons to sort the array alphabetically or numerically.</p>

<button onclick="myFunction1()">Sort Alphabetically</button>
<button onclick="myFunction2()">Sort Numerically</button>

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

<script>
var points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = points;    

function myFunction1() {
    points.sort();
    document.getElementById("demo").innerHTML = points;
}
function myFunction2() {
    points.sort(function(a, b){return a - b});
    document.getElementById("demo").innerHTML = points;
}
</script>

JavaScript Array Sort

<p>Click the button (again and again) to sort the array in random order.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
var points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = points;    

function myFunction() {
    points.sort(function(a, b){return 0.5 - Math.random()});
    document.getElementById("demo").innerHTML = points;
}
</script>

JavaScript Array Sort

<p>The lowest number is <span id="demo"></span>.</p>

<script>
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a-b});
document.getElementById("demo").innerHTML = points[0];
</script>

</body>
</html>

JavaScript Array Sort

<p>The highest number is <span id="demo"></span>.</p>

<script>
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b-a});
document.getElementById("demo").innerHTML = points[0];
</script>

</body>
</html>

JavaScript Array Sort

<p>The highest number is <span id="demo"></span>.</p>

<script>
var points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = myArrayMax(points);

function myArrayMax(arr) {
    return Math.max.apply(null, arr);
}
</script>

</body>
</html>

JavaScript Array Sort

<p>The lowest number is <span id="demo"></span>.</p>

<script>
var points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = myArrayMin(points);

function myArrayMin(arr) {
    return Math.min.apply(null, arr);
}
</script>

</body>
</html>

JavaScript Array Sort

<p>The highest number is <span id="demo"></span>.</p>

<script>
var points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = myArrayMax(points);

function myArrayMax(arr) {
    var len = arr.length
    var max = -Infinity;
    while (len--) {
      if (arr[len] > max) {
        max = arr[len];
      }
    }
    return max;
}
</script>

</body>
</html>

JavaScript Array Sort

<p>The lowest number is <span id="demo"></span>.</p>

<script>
var points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = myArrayMin(points);

function myArrayMin(arr) {
    var len = arr.length
    var min = Infinity;
    while (len--) {
      if (arr[len] < min) {
        min = arr[len];
      }
    }
    return min;
}
</script>

</body>
</html>

JavaScript Array Sort

<p>Click the buttons to sort car objects on age.</p>

<button onclick="myFunction()">Sort</button>

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

<script>
var cars = [
{type:"Volvo", year:2016},
{type:"Saab", year:2001},
{type:"BMW", year:2010}]

displayCars();

function myFunction() {
    cars.sort(function(a, b){return a.year - b.year});
    displayCars();
}

function displayCars() {
  document.getElementById("demo").innerHTML =
  cars[0].type + " " + cars[0].year + "<br>" +
  cars[1].type + " " + cars[1].year + "<br>" +
  cars[2].type + " " + cars[2].year;
}
</script>

JavaScript Array Sort

<p>Click the buttons to sort car objects on type.</p>

<button onclick="myFunction()">Sort</button>

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

<script>
var cars = [
{type:"Volvo", year:2016},
{type:"Saab", year:2001},
{type:"BMW", year:2010}]

displayCars();

function myFunction() {
    cars.sort(function(a, b){
        var x = a.type.toLowerCase();
        var y = b.type.toLowerCase();
        if (x < y) {return -1;}
        if (x > y) {return 1;}
        return 0;
    });
    displayCars();
}

function displayCars() {
  document.getElementById("demo").innerHTML =
  cars[0].type + " " + cars[0].year + "<br>" +
  cars[1].type + " " + cars[1].year + "<br>" +
  cars[2].type + " " + cars[2].year;
}
</script>

getFullYear()

Year: <script>document.write(xxx.getFullYear())</script>
<br>

JavaScript getFullYear()

<p>The getFullYear() method returns the full year of a date:</p> <p id="demo"></p> <script> var d = new Date(); document.getElementById("demo").innerHTML = d.getFullYear(); </script>

getMonth()

Month: <script>document.write(xxx.getMonth()+1)</script>
<br>

JavaScript getMonth()

<p>The getMonth() method returns the month of a date as a number (0-11):</p> <p id="demo"></p> <script> var d = new Date(); document.getElementById("demo").innerHTML = d.getMonth(); </script>

getDate()

Day: <script>document.write(xxx.getDate())</script>
<br>

JavaScript getDate()

<p>The getDate() method returns the day of a date as a number (1-31):</p> <p id="demo"></p> <script> var d = new Date(); document.getElementById("demo").innerHTML = d.getDate(); </script>

getHours()

Hours: <script>document.write(xxx.getHours())</script>
<br>

JavaScript getHours()

<p>The getHours() method returns the hours of a date as a number (0-23):</p> <p id="demo"></p> <script> var d = new Date(); document.getElementById("demo").innerHTML = d.getHours(); </script>

getMinutes()

Minutes <script>document.write(xxx.getMinutes())</script>
<br>

JavaScript getMinutes()

<p>The getMinutes() method returns the minutes of a date as a number (0-59):</p> <p id="demo"></p> <script> var d = new Date(); document.getElementById("demo").innerHTML = d.getMinutes(); </script>

getSeconds()

Seconds: <script>document.write(xxx.getSeconds())</script>
<br>

JavaScript getSeconds()

<p>The getSeconds() method returns the seconds of a date as a number (0-59):</p> <p id="demo"></p> <script> var d = new Date(); document.getElementById("demo").innerHTML = d.getSeconds(); </script>

JavaScript new Date()

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

<script>
var d = new Date();
document.getElementById("demo").innerHTML = d;
</script>

JavaScript new Date()

<p>Using new Date(), creates a new date object with the current date and time:</p>

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

<script>
var d = new Date();
document.getElementById("demo").innerHTML = d;
</script>

JavaScript new Date()

<p>Using new Date(7 numbers), creates a new date object with the specified date and time:</p>

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

<script>
var d = new Date(2018, 11, 24, 10, 33, 30, 0);
document.getElementById("demo").innerHTML = d;
</script>

JavaScript new Date()

<p>6 numbers specify year, month, day, hour, ninute and second:</p>

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

<script>
var d = new Date(2018, 11, 24, 10, 33, 30);
document.getElementById("demo").innerHTML = d;
</script>

JavaScript new Date()

<p>5 numbers specify year, month, day, hour, and minute:</p>

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

<script>
var d = new Date(2018, 11, 24, 10, 33);
document.getElementById("demo").innerHTML = d;
</script>

JavaScript new Date()

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

<script>
var d = new Date(2018, 11, 24, 10);
document.getElementById("demo").innerHTML = d;
</script>

JavaScript new Date()

<p>3 numbers specify year, month, and day:</p>

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

<script>
var d = new Date(2018, 11, 24);
document.getElementById("demo").innerHTML = d;
</script>

JavaScript new Date()

<p>2 numbers specify year and  month:</p>

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

<script>
var d = new Date(2018, 11);
document.getElementById("demo").innerHTML = d;
</script>

JavaScript new Date()

<p>One parameter will be interpreted as new Date(milliseconds).</p>

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

<script>
var d = new Date(2018);
document.getElementById("demo").innerHTML = d;
</script>

JavaScript new Date()

<p>Two digit years will be interpreted as 19xx:</p>

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

<script>
var d = new Date(99, 11, 24);
document.getElementById("demo").innerHTML = d;
</script>

JavaScript new Date()

<p>One digit years will be interpreted as 19xx:</p>

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

<script>
var d = new Date(9, 11, 24);
document.getElementById("demo").innerHTML = d;
</script>

JavaScript new Date()

<p>A Date object can be created with a specified date and time:</p>

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

<script>
var d = new Date("October 13, 2014 11:13:00");
document.getElementById("demo").innerHTML = d;
</script>

JavaScript new Date()

<p>Using new Date(milliseconds), creates a new date object as January 1, 1970, 00:00:00 Universal Time (UTC) plus the milliseconds:</p>

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

<script>
var d = new Date(0);
document.getElementById("demo").innerHTML = d;
</script>

JavaScript new Date()

<p>100000000000 milliseconds from Jan 1, 1970, is approximately Mar 3, 1973:</p>

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

<script>
var d = new Date(100000000000);
document.getElementById("demo").innerHTML = d;
</script>

JavaScript new Date()

<p>100000000000 milliseconds from Jan 1, 1970, is approximately Oct 31, 1966:</p>

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

<script>
var d = new Date(-100000000000);
document.getElementById("demo").innerHTML = d;
</script>

JavaScript new Date()

<p>Using new Date(milliseconds), creates a new date object as January 1, 1970, 00:00:00 Universal Time (UTC) plus the milliseconds:</p>

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

<script>
var d = new Date(86400000);
document.getElementById("demo").innerHTML = d;
</script>

<p>One day (24 hours) is 86,400,000 milliseconds.</p>

JavaScript toString()

<p>The toString() method converts a date to a string:</p>

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

<script>
var d = new Date();
document.getElementById("demo").innerHTML = d.toString();
</script>

JavaScript Date()

<p>The toUTCString() method converts a date to a UTC string (a date display standard):</p>

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

<script>
var d = new Date();
document.getElementById("demo").innerHTML = d.toUTCString();
</script>

JavaScript toDateString()

<p>The toDateString() method converts a date to a date string:</p>

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

<script>
var d = new Date();
document.getElementById("demo").innerHTML = d.toDateString();
</script>

JavaScript ISO Dates

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

<script>
var d = new Date("2015-03-25");
document.getElementById("demo").innerHTML = d;
</script>

JavaScript ISO Dates

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

<script>
var d = new Date("2015-03"); 
document.getElementById("demo").innerHTML = d;
</script>

JavaScript ISO Dates

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

<script>
var d = new Date("2015");
document.getElementById("demo").innerHTML = d;
</script>

JavaScript ISO Dates

<p>Separate date and time with a capital T.</p>

<p>Indicate UTC time with a capital Z.</p>

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

<script>
var d = new Date("2015-03-25T12:00:00Z");
document.getElementById("demo").innerHTML = d;
</script>

JavaScript ISO Dates

<p>Modify the time relative to UTC by adding +HH:MM or subtraction -HH:MM to the time.</p>

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

<script>
document.getElementById("demo").innerHTML =
new Date("2015-03-25T12:00:00-06:00");
</script>

JavaScript new Date()

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

<script>
var d = new Date("03/25/2015");
document.getElementById("demo").innerHTML = d;
</script>

JavaScript new Date()

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

<script>
var d = new Date("Mar 25 2015");
document.getElementById("demo").innerHTML = d;
</script>

JavaScript new Date()

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

<script>
var d = new Date("25 Mar 2015");
document.getElementById("demo").innerHTML = d;
</script>

JavaScript new Date()

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

<script>
var d = new Date("January 25 2015");
document.getElementById("demo").innerHTML = d;
</script>

JavaScript new Date()

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

<script>
var d = new Date("Jan 25 2015");
document.getElementById("demo").innerHTML = d;
</script>

JavaScript new Date()

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

<script>
var d = new Date("JANUARY, 25, 2015");
document.getElementById("demo").innerHTML = d;
</script>

JavaScript Date.parse()

<p>Date.parse() returns the number of milliseconds between the date and January 1, 1970:</p>

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

<script>
var msec = Date.parse("March 21, 2012");
document.getElementById("demo").innerHTML = msec;
</script>

Date.parse(string) returns milliseconds.

<p>You can use the return value to convert the string to a date object:</p>

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

<script>
var msec = Date.parse("March 21, 2012");
var d = new Date(msec);
document.getElementById("demo").innerHTML = d;
</script>


JavaScript getTime()

<p>The internal clock in JavaScript counts from midnight January 1, 1970.</p>
<p>The getTime() function returns the number of milliseconds since then:</p>

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

<script>
var d = new Date();
document.getElementById("demo").innerHTML = d.getTime();
</script>

JavaScript getFullYear()

<p>The getFullYear() method returns the full year of a date:</p>

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

<script>
var d = new Date();
document.getElementById("demo").innerHTML = d.getFullYear();
</script>

JavaScript getMonth()

<p>The getMonth() method returns the month of a date as a number (0-11):</p>

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

<script>
var d = new Date();
document.getElementById("demo").innerHTML = d.getMonth();
</script>

JavaScript getMonth()

<p>The getMonth() method returns the month as a number:</p>

<p>You can use an array to display the name of the month:</p>

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

<script>
var d = new Date();
var months = ["January","February","March","April","May","June","July","August","September","October","November","December"];
document.getElementById("demo").innerHTML = months[d.getMonth()];
</script>

JavaScript getDate()

<p>The getDate() method returns the day of a date as a number (1-31):</p>

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

<script>
var d = new Date();
document.getElementById("demo").innerHTML = d.getDate();
</script>

JavaScript getHours()

<p>The getHours() method returns the hours of a date as a number (0-23):</p>

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

<script>
var d = new Date();
document.getElementById("demo").innerHTML = d.getHours();
</script>

JavaScript getMinutes()

<p>The getMinutes() method returns the minutes of a date as a number (0-59):</p>

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

<script>
var d = new Date();
document.getElementById("demo").innerHTML = d.getMinutes();
</script>

JavaScript getSeconds()

<p>The getSeconds() method returns the seconds of a date as a number (0-59):</p>

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

<script>
var d = new Date();
document.getElementById("demo").innerHTML = d.getSeconds();
</script>

JavaScript getMilliseconds()

<p>The getMilliseconds() method returns the milliseconds of a date as a number (0-999):</p>

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

<script>
var d = new Date();
document.getElementById("demo").innerHTML = d.getMilliseconds();
</script>

JavaScript getDay()

<p>The getDay() method returns the weekday as a number:</p>

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

<script>
var d = new Date();
document.getElementById("demo").innerHTML = d.getDay();
</script>

JavaScript getDay()

<p>The getDay() method returns the weekday as a number:</p>

<p>You can use an array to display the name of the weekday:</p>

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

<script>
var d = new Date();
var days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
document.getElementById("demo").innerHTML = days[d.getDay()];
</script>

JavaScript setFullYear()

<p>The setFullYear() method sets the year of a date object:</p>

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

<script>
var d = new Date();
d.setFullYear(2020);
document.getElementById("demo").innerHTML = d;
</script>

JavaScript setFullYear()

<p>The setFullYear() method can optionally set month and day.</p>
<p>Please note that month counts from 0. December is month 11:</p>

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

<script>
var d = new Date();
d.setFullYear(2020, 11, 3);
document.getElementById("demo").innerHTML = d;
</script>

JavaScript setMonth()

<p>The setMonth() method sets the mont of a date object.</p>
<p>Note that months count from 0. December is month 11:</p>

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

<script>
var d = new Date();
d.setMonth(11);
document.getElementById("demo").innerHTML = d;
</script>

JavaScript setDate()

<p>The setDate() method sets the day of a date object:</p>

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

<script>
var d = new Date();
d.setDate(15);
document.getElementById("demo").innerHTML = d;
</script>

JavaScript setDate()

<p>The setDate() method can be used to add days to a date.</p>

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

<script>
var d = new Date();
d.setDate(d.getDate() + 50);
document.getElementById("demo").innerHTML = d;
</script>

JavaScript setHours()

<p>The setHours() method sets the hours of a date object:</p>

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

<script>
var d = new Date();
d.setHours(22);
document.getElementById("demo").innerHTML = d;
</script>

JavaScript setMinutes()

<p>The setMinutes() method sets the minutes of a date object (0-59):</p>

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

<script>
var d = new Date();
d.setMinutes(30);
document.getElementById("demo").innerHTML = d;
</script>

JavaScript setSeconds()

<p>The setSeconds() method sets the seconds of a date object (0-59):</p>

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

<script>
var d = new Date();
d.setSeconds(30);
document.getElementById("demo").innerHTML = d;
</script>

setFullYear

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

<script>
var today, someday, text;
today = new Date();
someday = new Date();
someday.setFullYear(2100, 0, 14);

if (someday > today) {
    text = "Today is before January 14, 2100.";
} else {
    text = "Today is after January 14, 2100.";
}
document.getElementById("demo").innerHTML = text;
</script>


JavaScript Math.PI

<p>Math.PI returns the ratio of a circle's circumference to its diameter:</p>

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

<script>
document.getElementById("demo").innerHTML = Math.PI;
</script>

JavaScript Math.round()

<p>Math.round(x) returns the value of x rounded to its nearest integer:</p>

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

<script>
document.getElementById("demo").innerHTML = Math.round(4.4);
</script>

JavaScript Math.pow()

<p>Math.pow(x,y) returns the value of x to the power of y:</p>

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

<script>
document.getElementById("demo").innerHTML = Math.pow(8,2);
</script>

JavaScript Math.sqrt()

<p>Math.sqrt(x) returns the square root of x:</p>

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

<script>
document.getElementById("demo").innerHTML = Math.sqrt(64);
</script>

JavaScript Math.abs()

<p>Math.abs(x) returns the absolute (positive) value of x:</p>


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

<script>
document.getElementById("demo").innerHTML = Math.abs(-4.4);
</script>

JavaScript Math.ceil()

<p>Math.ceil() rounds a number <strong>up</strong> to its nearest integer:</p>


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

<script>
document.getElementById("demo").innerHTML = Math.ceil(4.4);
</script>

JavaScript Math.floor()

<p>Math.floor(x) returns the value of x rounded <strong>down</strong> to its nearest integer:</p>

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

<script>
document.getElementById("demo").innerHTML = Math.floor(4.7);
</script>

JavaScript Math.sin()

<p>Math.sin(x) returns the sin of x (given in radians):</p>
<p>Angle in radians = (angle in degrees) * PI / 180.</p>

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

<script>
document.getElementById("demo").innerHTML = 
"The sine value of 90 degrees is " + Math.sin(90 * Math.PI / 180);
</script>

JavaScript Math.cos()

<p>Math.cos(x) returns the cosin of x (given in radians):</p>
<p>Angle in radians = (angle in degrees) * PI / 180.</p>

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

<script>
document.getElementById("demo").innerHTML = 
"The cosine value of 0 degrees is " + Math.cos(0 * Math.PI / 180);
</script>

JavaScript Math.min()

<p>Math.min() returns the lowest value in a list of arguments:</p>

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

<script>
document.getElementById("demo").innerHTML =
Math.min(0, 150, 30, 20, -8, -200);
</script>

JavaScript Math.max()

<p>Math.max() returns the highest value in a list of arguments.</p>

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

<script>
document.getElementById("demo").innerHTML =
Math.max(0, 150, 30, 20, -8, -200);
</script>

JavaScript Math.random()

<p>Math.random() returns a random number between 0 and 1:</p>

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

<script>
document.getElementById("demo").innerHTML = Math.random();
</script>

JavaScript Math Constants

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

<script>
document.getElementById("demo").innerHTML = 
"<p><b>Math.E:</b> " + Math.E + "</p>" +
"<p><b>Math.PI:</b> " + Math.PI + "</p>" +
"<p><b>Math.SQRT2:</b> " + Math.SQRT2 + "</p>" +
"<p><b>Math.SQRT1_2:</b> " + Math.SQRT1_2 + "</p>" +
"<p><b>Math.LN2:</b> " + Math.LN2 + "</p>" +
"<p><b>Math.LN10:</b> " + Math.LN10 + "</p>" +
"<p><b>Math.LOG2E:</b> " + Math.LOG2E + "</p>" +
"<p><b>Math.Log10E:</b> " + Math.LOG10E + "</p>";
</script>

JavaScript Math.random()

<p>Math.random() returns a random number between 0 (included) and 1 (excluded):</p>

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

<script>
document.getElementById("demo").innerHTML = Math.random();
</script>

JavaScript Math

<p>Math.floor(Math.random() * 10) returns a random integer between 0 and 9 (both included).</p>

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

<script>
document.getElementById("demo").innerHTML =
Math.floor(Math.random() * 10);
</script>

JavaScript Math

<p>Math.floor(Math.random() * 11) returns a random integer between 0 and 10 (both included).</p>

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

<script>
document.getElementById("demo").innerHTML =
Math.floor(Math.random() * 11);
</script>

JavaScript Math

<p>Math.floor(Math.random() * 100)) returns a random integer between 0 and 99 (both included).</p>

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

<script>
document.getElementById("demo").innerHTML =
Math.floor(Math.random() * 100);
</script>

JavaScript Math

<p>Math.floor() used with Math.random() * 101 returns a random integer between 0 and 100.</p>

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

<script>
document.getElementById("demo").innerHTML =
Math.floor(Math.random() * 101);
</script>

JavaScript Math

<p>Math.floor(Math.random() * 10) + 1) returns a random integer between 1 and 10 (both included).</p>

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

<script>
document.getElementById("demo").innerHTML =
Math.floor(Math.random() * 10) + 1;
</script>

JavaScript Math

<p>Math.floor(Math.random() * 100) + 1) returns a random integer between 1 and 100 (both included).</p>

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

<script>
document.getElementById("demo").innerHTML =
Math.floor(Math.random() * 100) + 1;
</script>

JavaScript Math.random()

<p>Every time you click the button, getRndInteger(min, max) returns a random number between 0 (included) and 10 (excluded):</p>

<button onclick="document.getElementById('demo').innerHTML = getRndInteger(0,10)">Click Me</button>

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

<script>
function getRndInteger(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
}
</script>

JavaScript Math.random()

<p>Every time you click the button, getRndInteger(min, max) returns a random number between 1 and 10 (both included):</p>

<button onclick="document.getElementById('demo').innerHTML = getRndInteger(1,10)">Click Me</button>

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

<script>
function getRndInteger(min, max) {
    return Math.floor(Math.random() * (max - min + 1) ) + min;
}
</script>

Display the value of Boolean(10 > 9):

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    document.getElementById("demo").innerHTML = Boolean(10 > 9);
}
</script>

Display the value of 10 > 9:

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    document.getElementById("demo").innerHTML = 10 > 9;
}
</script>

Boolean

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

<script>
var b1 = Boolean(100);
var b2 = Boolean(3.14);
var b3 = Boolean(-15);
var b4 = Boolean("Hello");
var b5 = Boolean('false');
var b6 = Boolean(1 + 7 + 3.14);

document.getElementById("demo").innerHTML =
"100 is " + b1 + "<br>" +
"3.14 is " + b2 + "<br>" +
"-15 is " + b3 + "<br>" +
"Any (not empty) string is " + b4 + "<br>" +
"Even the string 'false' is " + b5 + "<br>" +
"Any expression (except zero) is " + b6;
</script>


Display the Boolean value of 0:

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = 0;
    document.getElementById("demo").innerHTML = Boolean(x);
}
</script>

Display the Boolean value of -0:

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = -0;
    document.getElementById("demo").innerHTML = Boolean(x);
}
</script>

Display the Boolean value of "":

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = "";
    document.getElementById("demo").innerHTML = Boolean(x);
}
</script>

Display the Boolean value of undefined:

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x;
    document.getElementById("demo").innerHTML = Boolean(x);
}
</script>

Display the Boolean value of null:

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = null;
    document.getElementById("demo").innerHTML = Boolean(x);
}
</script>

Display the Boolean value of false:

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = false;
    document.getElementById("demo").innerHTML = Boolean(x);
}
</script>

Display the Boolean value of NaN:

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = 10 / "H";
    document.getElementById("demo").innerHTML = Boolean(x);
}
</script>

Never create booleans as objects

<br>

<p>Never create booleans as objects.</p>
<p>Booleans and objects cannot be safely compared.</p>

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

<script>
var x = false;               // x is a boolean
var y = new Boolean(false);  // y is an object
document.getElementById("demo").innerHTML =
typeof x + "<br>" + typeof y;
</script>


Never create booleans as objects.

<p>Booleans and objects cannot be safely compared.</p>

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

<script>
var x = false;               // x is a boolean
var y = new Boolean(false);  // y is an object
document.getElementById("demo").innerHTML = (x==y);
</script>


Never create booleans as objects.

<p>Booleans and objects cannot be safely compared.</p>

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

<script>
var x = false;               // x is a number
var y = new Boolean(false);  // y is an object
document.getElementById("demo").innerHTML = (x===y);
</script>


Never create booleans as objects.

<p>Booleans and objects cannot be safely compared.</p>

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

<script>
var x = new Boolean(false);  // x is an object
var y = new Boolean(false);  // y is an object
document.getElementById("demo").innerHTML = (x==y);
</script>


JavaScript Comparison

<p>Assign 5 to x, and display the value of the comparison (x == 8):</p>

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

<script>
var x = 5;
document.getElementById("demo").innerHTML = (x == 8);
</script>

JavaScript Comparison

<p>Assign 5 to x, and display the value of the comparison (x == 5):</p>

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

<script>
var x = 5;
document.getElementById("demo").innerHTML = (x == 5);
</script>


JavaScript Comparison

<p>Assign 5 to x, and display the value of the comparison (x == 5):</p>

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

<script>
var x = 5;
document.getElementById("demo").innerHTML = (x == "5");
</script>


JavaScript Comparison

<p>Assign 5 to x, and display the value of the comparison (x === 5):</p>

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

<script>
var x = 5;
document.getElementById("demo").innerHTML = (x === 5);
</script>


JavaScript Comparison

<p>Assign 5 to x, and display the value of the comparison (x === "5").</p>

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

<script>
var x = 5;
document.getElementById("demo").innerHTML = (x === "5");
</script>


JavaScript Comparison

<p>Assign 5 to x, and display the value of the comparison (x != 8).</p>

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

<script>
var x = 5;
document.getElementById("demo").innerHTML = (x != 8);
</script>


JavaScript Comparison

<p>Assign 5 to x, and display the value of the comparison (x !== 5):</p>

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

<script>
var x = 5;
document.getElementById("demo").innerHTML = (x !== 5);
</script>


JavaScript Comparison

<p>Assign 5 to x, and display the value of the comparison (x !== "5"):</p>

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

<script>
var x = 5;
document.getElementById("demo").innerHTML = (x !== "5");
</script>


JavaScript Comparison

<p>Assign 5 to x, and display the value of the comparison (x !== 8):</p>

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

<script>
var x = 5;
document.getElementById("demo").innerHTML = (x !== 8);
</script>


JavaScript Comparison

<p>Assign 5 to x, and display the value of the comparison (x > 8).</p>
 
<p id="demo"></p>

<script>
var x = 5;
document.getElementById("demo").innerHTML = (x > 8);
</script>


JavaScript Comparison

<p>Assign 5 to x, and display the value of the comparison (x < 8).</p>

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

<script>
var x = 5;
document.getElementById("demo").innerHTML = (x < 8);
</script>


JavaScript Comparison

<p>Assign 5 to x, and display the value of the comparison (x >= 8).</p>

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

<script>
var x = 5;
document.getElementById("demo").innerHTML = (x >= 8);
</script>


JavaScript Comparison

<p>Assign 5 to x, and display the value of the comparison (x <= 8).</p>

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

<script>
var x = 5;
document.getElementById("demo").innerHTML = (x <= 8);
</script>


JavaScript Comparison

<p>The AND operator (&&) returns true if both expressions are true, otherwise it returns false.</p>

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

<script>
var x = 6;
var y = 3;

document.getElementById("demo").innerHTML = 
(x < 10 && y > 1) + "<br>" + 
(x < 10 && y < 1);
</script>


JavaScript Comparison

<p>The OR operator (||) returns true if one or both expressions are true, otherwise it returns false.</p>

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

<script>
var x = 6;
var y = 3;

document.getElementById("demo").innerHTML = 
(x == 5 || y == 5) + "<br>" + 
(x == 6 || y == 0) + "<br>" + 
(x == 0 || y == 3) + "<br>" + 
(x == 6 || y == 3);
</script>


JavaScript Comparison

<p>The NOT operator (!) returns true for false statements and false for true statements.</p>

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

<script>
var x = 6;
var y = 3;

document.getElementById("demo").innerHTML = 
!(x === y) + "<br>" + 
!(x > y);
</script>


Input your age and click the button:

<input id="age" value="18" />

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var age, voteable;
    age = document.getElementById("age").value;
    voteable = (age < 18) ? "Too young":"Old enough";
    document.getElementById("demo").innerHTML = voteable + " to vote.";
}
</script>

JavaScript Comparison

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

<script>
document.getElementById("demo").innerHTML = 2 < 12;
</script>


JavaScript Comparison

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

<script>
document.getElementById("demo").innerHTML = 2 < "12";
</script>


JavaScript Comparison

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

<script>
document.getElementById("demo").innerHTML = 2 < "John";
</script>


JavaScript Comparison

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

<script>
document.getElementById("demo").innerHTML = 2 > "John";
</script>


JavaScript Comparison

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

<script>
document.getElementById("demo").innerHTML = 2 == "John";
</script>


JavaScript Comparison

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

<script>
document.getElementById("demo").innerHTML = "2" < "12";
</script>


JavaScript Comparison

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

<script>
document.getElementById("demo").innerHTML = "2" > "12";
</script>


JavaScript Comparison

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

<script>
document.getElementById("demo").innerHTML = "2" == "12";
</script>


JavaScript Comparisons

<p>Input your age and click the button:</p>

<input id="age" value="18" />

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var age, voteable;
    age = Number(document.getElementById("age").value);
    if (isNaN(age)) {
        voteable = "Input is not a number";
    } else {
        voteable = (age < 18) ? "Too young" : "Old enough";
    }
    document.getElementById("demo").innerHTML = voteable;
}
</script>

Display "Good day!" if the hour is less than 18:00:

<p id="demo">Good Evening!</p>

<script>
if (new Date().getHours() < 18) {
    document.getElementById("demo").innerHTML = "Good day!";
}
</script>

Click the button to display a time-based greeting:

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var hour = new Date().getHours(); 
    var greeting;
    if (hour < 18) {
        greeting = "Good day";
    } else {
        greeting = "Good evening";
    }
    document.getElementById("demo").innerHTML = greeting;
}
</script>

Click the button to get a time-based greeting:

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var greeting;
    var time = new Date().getHours();
    if (time < 10) {
        greeting = "Good morning";
    } else if (time < 20) {
        greeting = "Good day";
    } else {
        greeting = "Good evening";
    }
document.getElementById("demo").innerHTML = greeting;
}
</script>

Random link

<br>

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

<script>
if (Math.random() < 0.5) {
    text = "<a href='https://w3schools.com'>Visit W3Schools</a>";
} else {
    text = "<a href='https://wwf.org'>Visit WWF</a>";
}
document.getElementById("demo").innerHTML = text;
</script>


getDay()

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

<script>
var day;
switch (new Date().getDay()) {
    case 0:
        day = "Sunday";
        break;
    case 1:
        day = "Monday";
        break;
    case 2:
        day = "Tuesday";
        break;
    case 3:
        day = "Wednesday";
        break;
    case 4:
        day = "Thursday";
        break;
    case 5:
        day = "Friday";
        break;
    case  6:
        day = "Saturday";
}
document.getElementById("demo").innerHTML = "Today is " + day;
</script>


getDay()

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

<script>
var text;
switch (new Date().getDay()) {
    case 6:
        text = "Today is Saturday";
        break;
    case 0:
        text = "Today is Sunday";
        break;
    default:
        text = "Looking forward to the Weekend";
}
document.getElementById("demo").innerHTML = text;
</script>


getDay()

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

<script>
var text;
switch (new Date().getDay()) {
    default:
        text = "Looking forward to the Weekend";
        break;
    case 6:
        text = "Today is Saturday";
        break;
    case 0:
        text = "Today is Sunday";
}
document.getElementById("demo").innerHTML = text;
</script>


getDay()

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

<script>
var text;
switch (new Date().getDay()) {
    case 4:
    case 5:
        text = "Soon it is Weekend";
        break;
    case 0:
    case 6:
        text = "It is Weekend";
        break;
    default:
        text = "Looking forward to the Weekend";
}
document.getElementById("demo").innerHTML = text;
</script>


JavaScript Loops

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

<script>
var cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"];
var text = "";
var i;
for (i = 0; i < cars.length; i++) {
    text += cars[i] + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>

JavaScript Loops

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

<script>
var text = "";
var i;
for (i = 0; i < 5; i++) {
    text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>

.length

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

<script>
var cars = ["BMW", "Volvo", "Saab", "Ford"];
var i, len, text;
for (i = 0, len = cars.length, text = ""; i < len; i++) {
    text += cars[i] + "<br>";
}

document.getElementById("demo").innerHTML = text;
</script>


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

<script>
var cars = ["BMW", "Volvo", "Saab", "Ford"];
var i = 2;
var len = cars.length;
var text = "";

for (; i < len; i++) {
    text += cars[i] + "<br>";
}

document.getElementById("demo").innerHTML = text;
</script>


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

<script>
var cars = ["BMW", "Volvo", "Saab", "Ford"];

var i = 0;
var len = cars.length;
var text = "";

for (; i < len; ) {
    text += cars[i] + "<br>";
    i++;
}
document.getElementById("demo").innerHTML = text;
</script>


JavaScript Loops

<p>The for/in statement loops through the properties of an object.</p>

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

<script>
var txt = "";
var person = {fname:"John", lname:"Doe", age:25}; 
var x;
for (x in person) {
    txt += person[x] + " ";
}
document.getElementById("demo").innerHTML = txt;
</script>

JavaScript while

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

<script>
var text = "";
var i = 0;
while (i < 10) {
    text += "<br>The number is " + i;
    i++;
}
document.getElementById("demo").innerHTML = text;
</script>

JavaScript do ... while

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

<script>
var text = ""
var i = 0;

do {
    text += "<br>The number is " + i;
    i++;
}
while (i < 10);  

document.getElementById("demo").innerHTML = text;
</script>

cars[i]

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

<script>
var cars = ["BMW", "Volvo", "Saab", "Ford"];
var i = 0;
var text = "";
for (;cars[i];) {
    text += cars[i] + "<br>";
    i++;
}
document.getElementById("demo").innerHTML = text;
</script>


cars[i]

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

<script>
var cars = ["BMW", "Volvo", "Saab", "Ford"];
var i = 0;
var text = "";
while (cars[i]) {
    text += cars[i] + "<br>";
    i++;
}
document.getElementById("demo").innerHTML = text;
</script>


A loop with a break.

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

<script>
var text = "";
var i;
for (i = 0; i < 10; i++) {
    if (i === 3) { break; }
    text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>

A loop which will skip the step where i = 3.

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

<script>
var text = "";
var i;
for (i = 0; i < 10; i++) {
    if (i === 3) { continue; }
    text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>

cars[i]

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

<script>
var cars = ["BMW", "Volvo", "Saab", "Ford"];
var text = "";

list: {
    text += cars[0] + "<br>"; 
    text += cars[1] + "<br>"; 
    text += cars[2] + "<br>"; 
    break list;
    text += cars[3] + "<br>"; 
    text += cars[4] + "<br>"; 
    text += cars[5] + "<br>"; 
}

document.getElementById("demo").innerHTML = text;
</script>


The JavaScript typeof Operator

<p>The typeof operator returns the type of a variable, object, function or expression.</p>

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

<script>
document.getElementById("demo").innerHTML = 
    typeof "john" + "<br>" +
    typeof 3.14 + "<br>" +
    typeof NaN + "<br>" +
    typeof false + "<br>" +
    typeof [1,2,3,4] + "<br>" +
    typeof {name:'john', age:34} + "<br>" +
    typeof new Date() + "<br>" +
    typeof function () {} + "<br>" +
    typeof myCar + "<br>" +
    typeof null;
</script>

</body>
</html>

The JavaScript constructor Property

<p>The constructor property returns the constructor function for a variable or an 
object.</p>

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

<script>
document.getElementById("demo").innerHTML = 
    "john".constructor + "<br>" +
    (3.14).constructor + "<br>" +
    false.constructor + "<br>" +
    [1,2,3,4].constructor + "<br>" +
    {name:'john', age:34}.constructor + "<br>" +
    new Date().constructor + "<br>" +
    function () {}.constructor;
</script>

</body>
</html>

JavaScript Arrays

<p>This "home made" isArray() function returns true when used on an array:</p>

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

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = isArray(fruits);

function isArray(myArray) {
    return myArray.constructor.toString().indexOf("Array") > -1;
}
</script>

JavaScript Array Object

<p>This "home made" isArray() function returns true when used on an array:</p>

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

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = isArray(fruits);

function isArray(myArray) {
    return myArray.constructor === Array;
}
</script>


JavaScript Date Object

<p>This "home made" isDate() function returns true when used on an date:</p>

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

<script>
var myDate = new Date();
document.getElementById("demo").innerHTML = isDate(myDate);

function isDate(myDate) {
    return myDate.constructor.toString().indexOf("Date") > -1;
}
</script>


JavaScript Date Object

<p>This "home made" isDate() function returns true when used on an date:</p>

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

<script>
var myDate = new Date();
document.getElementById("demo").innerHTML = isDate(myDate);

function isDate(myDate) {
    return myDate.constructor === Date;
}
</script>


The JavaScript String() Method

<p>The String() method can convert a number to a string.</p>

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

<script>
var x = 123;
document.getElementById("demo").innerHTML =
  String(x) + "<br>" +
  String(123) + "<br>" +
  String(100 + 23);
</pre></script>

The JavaScript typeof Operator

<p>The typeof operator returns the type of a variable or expression.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var y = "5";
    var x = + y;
    document.getElementById("demo").innerHTML =
    typeof y + "<br>" + typeof x;
}
</script>

</body>
</html>

The JavaScript typeof Operator

<p>The typeof operator returns the type of a variable or expression.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var y = "John";
    var x = + y;
    document.getElementById("demo").innerHTML =
    typeof x + "<br>" + x;
}
</script>

</body>
</html>

operator

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

<script>
var x = [];
document.getElementById("demo").innerHTML =
(5 + null) + "<br>"  +
("5" + null) + "<br>" +
("5" + 2) + "<br>" +
("5" - 2) + "<br>" +
("5" * "2") + "<br>" +
("5" / "2") + "<br>"
</script>

</body>
</html>

Converting false to other types:

<p id="demo" style="font-family:courier"></p>

<script>
var x = false;
document.getElementById("demo").innerHTML =
"Number : " + Number(x) + "<br>" +
"String : " + String(x) + "<br>" +
"Boolean: " + Boolean(x);
</script>

</body>
</html>

Converting true to other types:

<p id="demo" style="font-family:courier"></p>

<script>
var x = true;
document.getElementById("demo").innerHTML =
"Number : " + Number(x) + "<br>" +
"String : " + String(x) + "<br>" +
"Boolean: " + Boolean(x);
</script>

</body>
</html>

Converting the number 0 to other types:

<p id="demo" style="font-family:courier"></p>

<script>
var x = 0;
document.getElementById("demo").innerHTML =
"Number : " + Number(x) + "<br>" +
"String : " + String(x) + "<br>" +
"Boolean: " + Boolean(x);
</script>

</body>
</html>

Converting the number 1 to other types:

<p id="demo" style="font-family:courier"></p>

<script>
var x = 1;
document.getElementById("demo").innerHTML =
"Number : " + Number(x) + "<br>" +
"String : " + String(x) + "<br>" +
"Boolean: " + Boolean(x);
</script>

</body>
</html>

Converting the string "0" to other types:

<p id="demo" style="font-family:courier"></p>

<script>
var x = "0";
document.getElementById("demo").innerHTML =
"Number : " + Number(x) + "<br>" +
"String : " + String(x) + "<br>" +
"Boolean: " + Boolean(x);
</script>

</body>
</html>

Converting the string "000" to other types:

<p id="demo" style="font-family:courier"></p>

<script>
var x = "000";
document.getElementById("demo").innerHTML =
"Number : " + Number(x) + "<br>" +
"String : " + String(x) + "<br>" +
"Boolean: " + Boolean(x);
</script>

</body>
</html>

Converting the string "1" to other types:

<p id="demo" style="font-family:courier"></p>

<script>
var x = 1;
document.getElementById("demo").innerHTML =
"Number : " + Number(x) + "<br>" +
"String : " + String(x) + "<br>" +
"Boolean: " + Boolean(x);
</script>

</body>
</html>

Converting NaN to other types:

<p id="demo" style="font-family:courier"></p>

<script>
var x = NaN;
document.getElementById("demo").innerHTML =
"Number : " + Number(x) + "<br>" +
"String : " + String(x) + "<br>" +
"Boolean: " + Boolean(x);
</script>

</body>
</html>

Converting Infinity to other types:

<p id="demo" style="font-family:courier"></p>

<script>
var x = Infinity;
document.getElementById("demo").innerHTML =
"Number : " + Number(x) + "<br>" +
"String : " + String(x) + "<br>" +
"Boolean: " + Boolean(x);
</script>

</body>
</html>

Converting -Infinity to other types:

<p id="demo" style="font-family:courier"></p>

<script>
var x = -Infinity;
document.getElementById("demo").innerHTML =
"Number : " + Number(x) + "<br>" +
"String : " + String(x) + "<br>" +
"Boolean: " + Boolean(x);
</script>

</body>
</html>

Converting an empty string to other types:

<p id="demo" style="font-family:courier"></p>

<script>
var x = "";
document.getElementById("demo").innerHTML =
"Number : " + Number(x) + "<br>" +
"String : " + String(x) + "<br>" +
"Boolean: " + Boolean(x);
</script>

</body>
</html>

Converting a numeric string to other types:

<p id="demo" style="font-family:courier"></p>

<script>
var x = "20";
document.getElementById("demo").innerHTML =
"Number : " + Number(x) + "<br>" +
"String : " + String(x) + "<br>" +
"Boolean: " + Boolean(x);
</script>

</body>
</html>

Converting a text string to other types:

<p id="demo" style="font-family:courier"></p>

<script>
var x = "twenty";
document.getElementById("demo").innerHTML =
"Number : " + Number(x) + "<br>" +
"String : " + String(x) + "<br>" +
"Boolean: " + Boolean(x);
</script>

</body>
</html>

Converting an empty array to other types:

<p id="demo" style="font-family:courier"></p>

<script>
var x = [];
document.getElementById("demo").innerHTML =
"Number : " + Number(x) + "<br>" +
"String : " + String(x) + "<br>" +
"Boolean: " + Boolean(x);
</script>

</body>
</html>

Converting an array with one numeric element to other types:

<p id="demo" style="font-family:courier"></p>

<script>
var x = [20];
document.getElementById("demo").innerHTML =
"Number : " + Number(x) + "<br>" +
"String : " + String(x) + "<br>" +
"Boolean: " + Boolean(x);
</script>

</body>
</html>

Converting an array with two numeric elements to other types:

<p id="demo" style="font-family:courier"></p>

<script>
var x = [10,20];
document.getElementById("demo").innerHTML =
"Number : " + Number(x) + "<br>" +
"String : " + String(x) + "<br>" +
"Boolean: " + Boolean(x);
</script>

</body>
</html>

Converting an array with one string element to other types:

<p id="demo" style="font-family:courier"></p>

<script>
var x = ["twenty"];
document.getElementById("demo").innerHTML =
"Number : " + Number(x) + "<br>" +
"String : " + String(x) + "<br>" +
"Boolean: " + Boolean(x);
</script>

</body>
</html>

Converting an array with two string element to other types:

<p id="demo" style="font-family:courier"></p>

<script>
var x = ["ten","twenty"];
document.getElementById("demo").innerHTML =
"Number : " + Number(x) + "<br>" +
"String : " + String(x) + "<br>" +
"Boolean: " + Boolean(x);
</script>

</body>
</html>

Converting a function to other types:

<p id="demo" style="font-family:courier"></p>

<script>
var x = function(){};
document.getElementById("demo").innerHTML =
"Number : " + Number(x) + "<br>" +
"String : " + String(x) + "<br>" +
"Boolean: " + Boolean(x);
</script>

</body>
</html>

Converting an object to other types:

<p id="demo" style="font-family:courier"></p>

<script>
var x = {};
document.getElementById("demo").innerHTML =
"Number : " + Number(x) + "<br>" +
"String : " + String(x) + "<br>" +
"Boolean: " + Boolean(x);
</script>

</body>
</html>

Converting null to other types:

<p id="demo" style="font-family:courier"></p>

<script>
var x = null;
document.getElementById("demo").innerHTML =
"Number : " + Number(x) + "<br>" +
"String : " + String(x) + "<br>" +
"Boolean: " + Boolean(x);
</script>

</body>
</html>

Converting undefined to other types:

<p id="demo" style="font-family:courier"></p>

<script>
var x = undefined;
document.getElementById("demo").innerHTML =
"Number : " + Number(x) + "<br>" +
"String : " + String(x) + "<br>" +
"Boolean: " + Boolean(x);
</script>

</body>
</html>

JavaScript Bitwise AND

<p id="demo">My First Paragraph.</p>

<script>
document.getElementById("demo").innerHTML = 5 & 1;
</script>

JavaScript Bitwise OR

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

<script>
document.getElementById("demo").innerHTML = 5 | 1;
</script>

JavaScript Bitwise XOR

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

<script>
document.getElementById("demo").innerHTML = 5 ^ 1;
</script>

JavaScript Bitwise NOT

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

<script>
document.getElementById("demo").innerHTML = ~ 5;
</script>

JavaScript Bitwise Left

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

<script>
document.getElementById("demo").innerHTML = 5 < 1;
</script>

JavaScript Sign Preserving Bitwise Right.

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

<script>
document.getElementById("demo").innerHTML = -5 > 1;
</script>

JavaScript Bitwise Right

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

<script>
document.getElementById("demo").innerHTML = 5 > 1;
</script>

JavaScript Convert Decimal to Binary

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

<script>
document.getElementById("demo").innerHTML = dec2bin(-5);
function dec2bin(dec){
    return (dec > 0).toString(2);
}
</script>

JavaScript Convert Binary to Decimal

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

<script>
document.getElementById("demo").innerHTML = bin2dec(101);
function bin2dec(bin){
    return parseInt(bin, 2).toString(10);
}
</script>

Search a string for "w3Schools", and display the position of the match:

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var str = "Visit W3Schools!"; 
    var n = str.search(/w3Schools/i);
    document.getElementById("demo").innerHTML = n;
}
</script>

</body>
</html>

Search a string for "W3Schools", and display the position of the match:

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var str = "Visit W3Schools!"; 
    var n = str.search("W3Schools");
    document.getElementById("demo").innerHTML = n;
}
</script>

</body>
</html>

JavaScript String Methods

<p>Replace "microsoft" with "W3Schools" in the paragraph below:</p>

<button onclick="myFunction()">Try it</button>

<p id="demo">Please visit Microsoft and Microsoft!</p>

<script>
function myFunction() {
    var str = document.getElementById("demo").innerHTML; 
    var txt = str.replace(/microsoft/i,"W3Schools");
    document.getElementById("demo").innerHTML = txt;
}
</script>

</body>
</html>

Search for an "e" in the next paragraph:

<p id="p01">The best things in life are free!</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    text = document.getElementById("p01").innerHTML; 
    document.getElementById("demo").innerHTML = /e/.test(text);
}
</script>

Search for an "e" in the next paragraph:

<p id="p01">The best things in life are free!</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    text = document.getElementById("p01").innerHTML; 
    document.getElementById("demo").innerHTML = /e/.exec(text);
}

</script>

adddlert

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

<script>
try {
    adddlert("Welcome guest!");
}
catch(err) {
    document.getElementById("demo").innerHTML = err.message;
}
</script>

Please input a number between 5 and 10:

<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>
<p id="message"></p>

<script>
function myFunction() {
    var message, x;
    message = document.getElementById("message");
    message.innerHTML = "";
    x = document.getElementById("demo").value;
    try { 
        if(x == "")  throw "empty";
        if(isNaN(x)) throw "not a number";
        x = Number(x);
        if(x < 5)    throw "too low";
        if(x > 10)   throw "too high";
    }
    catch(err) {
        message.innerHTML = "Input is " + err;
    }
}
</script>

</body>
</html>


Please input a number between 5 and 10:

<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>

<p id="message"></p>

<script>
function myFunction() {
    var message, x;
    message = document.getElementById("message");
    message.innerHTML = "";
    x = document.getElementById("demo").value;
    try { 
        if(x == "")  throw "is empty";
        if(isNaN(x)) throw "is not a number";
        x = Number(x);
        if(x > 10)   throw "is too high";
        if(x < 5)    throw "is too low";
    }
    catch(err) {
        message.innerHTML = "Input " + err;
    }
    finally {
        document.getElementById("demo").value = "";
    }
}
</script>

</body>
</html>


JavaScript Errors

<p>You cannot set the number of significant digits of a number to 500:</p>

<p id="demo">

<script>
var num = 1;
try {
    num.toPrecision(500);
}
catch(err) {
    document.getElementById("demo").innerHTML = err.name;
}
</script>

JavaScript Errors

<p>You cannot use the value of a non-existing variable:</p>

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

<script>
var x;
try {
    x = y + 1;
}
catch(err) {
    document.getElementById("demo").innerHTML = err.name;
}
</script>

JavaScript Errors

<p>You cannot evaluate code that contains a syntax error:</p>

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

<script>
try {
    eval("alert('Hello)");
}
catch(err) {
    document.getElementById("demo").innerHTML = err.name;
}
</script>

JavaScript Errors

<p>You cannot convert a number to upper case:</p>

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

<script>
var num = 1;
try {
    num.toUpperCase();
}
catch(err) {
    document.getElementById("demo").innerHTML = err.name;
}
</script>

JavaScript Errors

<p>Some characters cannot be URI decoded:</p>

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

<script>
try {
    decodeURI("%%%");
}
catch(err) {
    document.getElementById("demo").innerHTML = err.name;
}
</script>

My First Web Page

<p>
Activate debugging in your browser (Chrome, IE, Firefox) with F12, and select "Console" in the debugger menu.
</p>

<script>
a = 5;
b = 6;
c = a + b;
console.log(c);
</script>

debugger

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

<p>With the debugger turned on, the code below should stop executing before it executes the third line.</p>

<script>
var x = 15 * 5;
debugger;
document.getElementById("demo").innerHTML = x;
</script>


Find an element

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

<script>
x = 5; // Assign 5 to x

elem = document.getElementById("demo"); // Find an element 
elem.innerHTML = x;                     // Display x in the element

var x; // Declare x
</script>


Find an element

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

<script>
var x; // Declare x
x = 5; // Assign 5 to x

elem = document.getElementById("demo"); // Find an element 
elem.innerHTML = x;                     // Display x in the element
</script>


Find an element

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

<script>
var x = 5; // Initialize x
var y = 7; // Initialize y

elem = document.getElementById("demo"); // Find an element 
elem.innerHTML = x + " " + y;           // Display x and y

</script>


Find an element

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

<script>
var x = 5;  // Initialize x

elem = document.getElementById("demo");            // Find an element 
elem.innerHTML = "x is " + x + " and y is " + y;    // Display x and y

var y = 7;  // Initialize y
</script>


Find an element

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

<script>
var x = 5; // Initialize x
var y;     // Declare y

elem = document.getElementById("demo"); // Find an element 
elem.innerHTML = x + " " + y;           // Display x and y

y = 7;     // Assign 7 to y

</script>


With "use strict":

<h3>Using a variable without declaring it, is not allowed.</h3>

<p>Activate debugging in your browser (F12) to see the error report.</p>

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


Global "use strict" declaration.

<p>Activate debugging in your browser (F12) to see the error report.</p>

<script>
"use strict";
myFunction();

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

"use strict" in a function will only cause errors in that function.

<p>Activate debugging in your browser (F12) to see the error report.</p>

<script>
x = 3.14;        // This will not cause an error.
myFunction();

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

With "use strict":

<h3>Using a variable without declaring it, is not allowed.</h3>

<p>Activate debugging in your browser (F12) to see the error report.</p>

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


With "use strict":

<h3>Using an object without declaring it, is not allowed.</h3>

<p>Activate debugging in your browser (F12) to see the error report.</p>

<script>
"use strict";
x = {p1:10, p2:20};   // This will cause an error (x is not defined).
</script>


With "use strict":

<h3>Deleting a variable (or object) is not allowed.</h3>

<p>Activate debugging in your browser (F12) to see the error report.</p>

<script>
"use strict";
var x = 3.14;
delete x;       // This will cause an error 
</script>


With "use strict":

<h3>Deleting a function is not allowed.</h3>

<p>Activate debugging in your browser (F12) to see the error report.</p>

<script>
"use strict";
function x(p1, p2) {}; 
delete x;                // This will cause an error 
</script>


With "use strict":

<h3>Duplicating a parameter name is not allowed.</h3>

<p>Activate debugging in your browser (F12) to see the error report.</p>

<script>
"use strict";
function x(p1, p1) {};   // This will cause an error 
</script>


With "use strict":

<h3>Octal numeric literals are not allowed.</h3>

<p>Activate debugging in your browser (F12) to see the error report.</p>

<script>
"use strict";
var x = 010;   // This will cause an error 
</script>


With "use strict":

<h3>Octal escape characters are not allowed.</h3>

<p>Activate debugging in your browser (F12) to see the error report.</p>

<script>
"use strict";
var x = "\010";   // This will cause an error 
</script>


With "use strict":

<h3>Writing to a read-only property is not allowed.</h3>

<p>Activate debugging in your browser (F12) to see the error report.</p>

<script>
"use strict";
var obj = {};
Object.defineProperty(obj, "x", {value:0, writable:false});

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


With "use strict":

<h3>Writing to a get-only property is not allowed.</h3>

<p>Activate debugging in your browser (F12) to see the error report.</p>

<script>
"use strict";
var obj = {get x() {return 0} };

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


With "use strict":

<h3>Deleting an udeletable property is not allowed.</h3>

<p>Activate debugging in your browser (F12) to see the error report.</p>

<script>
"use strict";
delete Object.prototype;   // This will cause an error 
</script>


With "use strict":

<h3>The string "eval" cannot be used as a variable.</h3>

<p>Activate debugging in your browser (F12) to see the error report.</p>

<script>
"use strict";
var eval = 3.14;   // This will cause an error 
</script>


With "use strict":

<h3>The string "arguments" cannot be used as a variable.</h3>

<p>Activate debugging in your browser (F12) to see the error report.</p>

<script>
"use strict";
var arguments = 3.14;   // This will cause an error 
</script>


With "use strict":

<h3>The with statement is not allowed.</h3>

<p>Activate debugging in your browser (F12) to see the error report.</p>

<script>
"use strict";
with (Math){x = cos(2)};   // This will cause an error 
</script>


With "use strict":

<h3>For security reasons, eval() is not allowed to create variables in the scope from which it was called.</h3>

<p>Activate debugging in your browser (F12) to see the error report.</p>

<script>
"use strict";
eval ("var x = 2");
alert (x);          // This will cause an error 
</script>


With "use strict":

<h3>Future reserved keywords are not allowed in strict mode.</h3>

<p>Activate debugging in your browser (F12) to see the error report.</p>

<script>
"use strict";
var public = 1500;   // This will cause an error 
</script>


My Web Page

<p>
The best place to break a code line is after an operator or a comma.
</p>

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

<script>
document.getElementById("demo").innerHTML =
    "Hello Dolly.";
</script>

Never create strings as objects.

<p>Strings and objects cannot be safely compared.</p>

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

<script>
var x = "John";              // x is a string
var y = new String("John");  // y is an object
document.getElementById("demo").innerHTML = x===y;
</script>


Never create strings as objects.

<p>JavaScript cannot compare objects.</p>

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

<script>
var x = new String("John"); 
var y = new String("John");
document.getElementById("demo").innerHTML = x==y;
</script>


typeof

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

<script>
var x1 = {};
var x2 = "";
var x3 = 0;
var x4 = false;
var x5 = [];
var x6 = /()/;
var x7 = function(){};

document.getElementById("demo").innerHTML =
"x1: " + typeof x1 + "<br>" +
"x2: " + typeof x2 + "<br>" +
"x3: " + typeof x3 + "<br>" +
"x4: " + typeof x4 + "<br>" +
"x5: " + typeof x5 + "<br>" +
"x6: " + typeof x6 + "<br>" +
"x7: " + typeof x7 + "<br>";
</script>


typeof

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

<script>
var x = "Hello";
var x = 5;
document.getElementById("demo").innerHTML = typeof x;
</script>

</body>
</html>


Remove the comment (at the beginning of the lines) to test each case:

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

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

document.getElementById("demo").innerHTML = x.valueOf() + " " + typeof x;
</script>

</body>
</html

My first paragraph

<p id="demo">My first paragraph.</p>

<script>
document.getElementById("demo").innerHTML = "Hello" - "Dolly";
</script>


Remove the comment (at the beginning of each line) to test each case:

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

<script>
var x;
//x = (0 == "");     // true
//x = (1 == "1");    // true
//x = (1 == true);   // true
//x = (0 === "");    // false
//x = (1 === "1");   // false
//x = (1 === true);  // false
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html

Setting a default value to a function parameter.

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

<script>
function myFunction(x, y) {
    if (y === undefined) {
        y = 0;
    }    
    return x * y;
}
document.getElementById("demo").innerHTML = myFunction(4);
</script>

</body>
</html>



getDay

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

<script>
var day;
switch (new Date().getDay()) {
    case 0:
        day = "Sunday";
        break;
    case 1:
        day = "Monday";
        break;
    case 2:
        day = "Tuesday";
        break;
    case 3:
        day = "Wednesday";
        break;
    case 4:
        day = "Thursday";
        break;
    case 5:
        day = "Friday";
        break;
    case  6:
        day = "Saturday";
        break;
    default:
         day = "unknown";
}
document.getElementById("demo").innerHTML = "Today is " + day;
</script>


Boolean(x == 10)

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

<script>
var x = 0;
document.getElementById("demo").innerHTML = Boolean(x == 10);
</script>


Boolean(x == 10)

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

<script>
var x = 0;
document.getElementById("demo").innerHTML = Boolean(x = 10);
</script>


Boolean(x == 10)

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

<script>
var x = 0;
document.getElementById("demo").innerHTML = Boolean(x = 0);
</script>


Boolean(x == y)

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

<script>
var x = 10;
var y = "10";
document.getElementById("demo").innerHTML = Boolean(x == y);
</script>


Boolean(x === y)

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

<script>
var x = 10;
var y = "10";
document.getElementById("demo").innerHTML = Boolean(x === y);
</script>


switch(x)

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

<script>
var x = 10;
switch(x) {
    case 10: alert("Hello");
}
</script>


switch(x)

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

<script>
var x = 10;
switch(x) {
    case "10": alert("Hello");
}
</script>


10 + "5"

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

<script>
var x = 10 + "5";
document.getElementById("demo").innerHTML = x;
</script>


x + y

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

<script>
var x = 10;
var y = "5";
var z = x + y;
document.getElementById("demo").innerHTML = z;
</script>


x + y

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

<script>
var x = 0.1;
var y = 0.2;
var z = x + y;
document.getElementById("demo").innerHTML = z;
</script>

</body>
</html


(x * 10 + y *10) / 10

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

<script>
var x = 0.1;
var y = 0.2;
var z = (x * 10 + y *10) / 10;
document.getElementById("demo").innerHTML = z;
</script>

</body>
</html


"Hello World!"

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

<script>
document.getElementById("demo").innerHTML =
"Hello World!";
</script>


"Hello World!"

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

<script>
document.getElementById("demo").innerHTML = "Hello 
World!";
</script>


"Hello World!"

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

<script>
document.getElementById("demo").innerHTML = "Hello \
World!";
</script>


"Hello"

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

<script>
var x = 5;
if (x == 19);
{
document.getElementById("demo").innerHTML = "Hello";
}
</script>


power

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

<script>
document.getElementById("demo").innerHTML = myFunction(55);
function myFunction(a) {
    var power = 10
    return a * power
}
</script>


power

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

<script>
document.getElementById("demo").innerHTML = myFunction(55);
function myFunction(a) {
    var power = 10;
    return a * power;
}
</script>


power

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

<script>
document.getElementById("demo").innerHTML = myFunction(55);
function myFunction(a) {
    var
    power = 10;
    return a * power;
}
</script>


power

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

<script>
document.getElementById("demo").innerHTML = myFunction(55);
function myFunction(a) {
    var
    power = 10;
    return
    a * power;
}
</script>


power

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

<script>
document.getElementById("demo").innerHTML = myFunction(55);
function myFunction(a) {
    var
    power = 10;
    return;
    a * power;
}
</script>


JavaScript does not create a new scope for each code block

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

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

<script>
for (var i = 0; i < 10; i++) {
    // some code
}
document.getElementById("demo").innerHTML = i;
</script>

Hello

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

<script>
var obj;
obj = document.getElementById("demo");
obj.innerHTML = " Hello";
</script>


Create Object from JSON String

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

<script>
var text = '{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';

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

document.forms

<head>
<script>
function validateForm() {
    var x = document.forms["myForm"]["fname"].value;
    if (x == "") {
        alert("Name must be filled out");
        return false;
    }
}
</script>
</head>
<body>

<form name="myForm" action="/action_page.php"
onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>


JavaScript Can Validate Input

<p>Please input a number between 1 and 10:</p>

<input id="numb">

<button type="button" onclick="myFunction()">Submit</button>

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

<script>
function myFunction() {
    var x, text;

    // Get the value of the input field with id="numb"
    x = document.getElementById("numb").value;

    // If x is Not a Number or less than one or greater than 10
    if (isNaN(x) || x < 1 || x > 10) {
        text = "Input not valid";
    } else {
        text = "Input OK";
    }
    document.getElementById("demo").innerHTML = text;
}
</script>

submit

<form action="/action_page.php" method="post">
  <input type="text" name="fname" required>
  <input type="submit" value="Submit">
</form>

<p>If you click submit, without filling out the text field,
your browser will display an error message.</p>


Enter a number and click OK:

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

<p>If the number is less than 100 or greater than 300, an error message will be displayed.</p>

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

<script>
function myFunction() {
    var inpObj = document.getElementById("id1");
    if (!inpObj.checkValidity()) {
        document.getElementById("demo").innerHTML = inpObj.validationMessage;
    } else {
        document.getElementById("demo").innerHTML = "Input OK";
    } 
} 
</script>

Enter a number and click OK:

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

<p>If the number is greater than 100 (the input's max attribute), an error message will be displayed.</p>

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

<script>
function myFunction() {
    var txt = "";
    if (document.getElementById("id1").validity.rangeOverflow) {
        txt = "Value too large";
    } else {
        txt = "Input OK";
    } 
    document.getElementById("demo").innerHTML = txt;
}
</script>

</body>
</html>

Enter a number and click OK:

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

<p>If the number is less than 100 (the input's min attribute), an error message will be displayed.</p>

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

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

</body>
</html>

Creating a JavaScript Variable.

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

<script>
var person = "John Doe";
document.getElementById("demo").innerHTML = person;
</script>

Creating a JavaScript Object.

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

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

document.getElementById("demo").innerHTML =
person.firstName + " " + person.lastName;
</script>

Creating a JavaScript Object.

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

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

document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>

Creating a JavaScript Object.

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

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

document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>

Object()

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

<script>
var person = new Object();
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue"; 

document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>


JavaScript objects are mutable.

<p>Any changes to a copy of an object will also change the original.</p>

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

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

var x = person;
x.age = 10;

document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>


There are two different ways to access an object property:

<p>You can use .property or ["property"].</p>

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

<script>
var person = {
    firstname:"John",
    lastname:"Doe",
    age:50,
    eyecolor:"blue"
};
document.getElementById("demo").innerHTML =
person.firstname + " is " + person.age + " years old.";
</script>


There are two different ways to access an object property:

<p>You can use .property or ["property"].</p>

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

<script>
var person = {
    firstname:"John",
    lastname:"Doe",
    age:50,
    eyecolor:"blue"
};
document.getElementById("demo").innerHTML =
person["firstname"] + " is " + person["age"] + " years old.";
</script>


Object

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

<script>
var txt = "";
var person = {fname:"John", lname:"Doe", age:25}; 
var x;
for (x in person) {
    txt += person[x] + " ";
}
document.getElementById("demo").innerHTML = txt;
</script>


You can add new properties to existing objects.

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

<script>
var person = {
    firstname:"John",
    lastname:"Doe",
    age:50,
    eyecolor:"blue"
};
person.nationality = "English";
document.getElementById("demo").innerHTML =
person.firstname + " is " + person.nationality + ".";
</script>

You can delete object properties.

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

<script>
var person = {
    firstname:"John",
    lastname:"Doe",
    age:50,
    eyecolor:"blue"
};
delete person.age;
document.getElementById("demo").innerHTML =
person.firstname + " is " + person.age + " years old.";
</script>

Creating and using an object method.

<p>A method is actually a function definition stored as a property value.</p>

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

<script>
var person = {
    firstName: "John",
    lastName : "Doe",
    id       : 5566,
    fullName : function() {
       return this.firstName + " " + this.lastName;
    }
};

docume</pre>nt.getElementById("demo").innerHTML = person.fullName();
</script>

An object method is a function definition stored as a property value.

<p>If you access it without (), it will return the function definition:</p>

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

<script>
var person = {
    firstName: "John",
    lastName : "Doe",
    id       : 5566,
    fullName : function() {
       return this.firstName + " " + this.lastName;
    }
};

docume</pre>nt.getElementById("demo").innerHTML = person.fullName;
</script>

Object

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

<script>
var person = {
    firstName: "John",
    lastName : "Doe",
    id       : 5566,
};
person.name = function() {
    return this.firstName + " " + this.lastName;
};

document.getElementById("demo").innerHTML =
"My father is " + person.name(); 
</script>

JavaScript Object Constructors

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

<script>

// Constructor function for Person objects
function Person(first, last, age, eye) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eye;
}

// Create a Person object
var myFather = new Person("John", "Doe", 50, "blue");

// Display age
document.getElementById("demo").innerHTML =
"My father is " + myFather.age + "."; 

</script>

JavaScript Object Constructors

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

<script>

// Constructor function for Person objects
function Person(first, last, age, eye) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eye;
}

// Create two Person objects
var myFather = new Person("John", "Doe", 50, "blue");
var myMother = new Person("Sally", "Rally", 48, "green");

// Display age
document.getElementById("demo").innerHTML =
"My father is " + myFather.age + ". My mother is " + myMother.age + "."; 

</script>

JavaScript Object Constructors

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

<script>

// Constructor function for Person objects
function Person(first, last, age, eye) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eye;
}

// Create 2 Person objects
var myFather = new Person("John", "Doe", 50, "blue");
var myMother = new Person("Sally", "Rally", 48, "green");

// Add nationality to first object
myFather.nationality = "English";

// Diplay nationality 
document.getElementById("demo").innerHTML =
"My father is " + myFather.nationality; 

</script>

JavaScript Object Constructors

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

<script>

// Constructor function for Person objects
function Person(first, last, age, eye) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eye;
}

// Create 2 Person objects
var myFather = new Person("John", "Doe", 50, "blue");
var myMother = new Person("Sally", "Rally", 48, "green");

// Add a name method to first object
myFather.name = function() {
    return this.firstName + " " + this.lastName;
};

// Display full name
document.getElementById("demo").innerHTML =
"My father is " + myFather.name(); 
</script>

JavaScript Object Constructors

<p>You cannot add a new property to a constructor function.</p>

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

<script>

// Constructor function for Person objects
function Person(first, last, age, eye) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eye;
}

// You can NOT add a new property to a constructor function
Person.nationality = "English";

// Create 2 Person objects
var myFather = new Person("John", "Doe", 50, "blue");
var myMother = new Person("Sally", "Rally", 48, "green");

// Diplay nationality
document.getElementById("demo").innerHTML =
"The nationality of my father is " + myFather.nationality; 
</script>

JavaScript Object Constructors

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

<script>

// Constructor function for Person objects
function Person(first, last, age, eye) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eye;
    this.nationality = "English";
}

// Create 2 Person objects
var myFather = new Person("John", "Doe", 50, "blue");
var myMother = new Person("Sally", "Rally", 48, "green");

// Display nationality
document.getElementById("demo").innerHTML =
"My father is " + myFather.nationality + ". My mother is " + myMother.nationality; 
</script>

JavaScript Object Constructors

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

<script>

// Constructor function for Person objects
function Person(first, last, age, eye) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eye;
    this.name = function() {
        return this.firstName + " " + this.lastName
    };
}

// Create a Person object
var myFather = new Person("John", "Doe", 50, "blue");

// Display full name
document.getElementById("demo").innerHTML =
"My father is " + myFather.name(); 

</script>

JavaScript Object Constructors

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

<script>

// Constructor function for Person objects
function Person(firstName,lastName,age,eyeColor) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
    this.eyeColor = eyeColor;
    this.changeName = function (name) {
        this.lastName = name;
    }
}
// Create a Person object
var myMother = new Person("Sally","Rally",48,"green");

// Change last name
myMother.changeName("Doe");

// Diplay last name
document.getElementById("demo").innerHTML =
"My mother's last name is " + myMother.lastName;
</script>

JavaScript Object Constructors

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

<script>
var x1 = new Object();   // A new Object object
var x2 = new String();   // A new String object
var x3 = new Number();   // A new Number object
var x4 = new Boolean();  // A new Boolean object
var x5 = new Array();    // A new Array object
var x6 = new RegExp();   // A new RegExp object
var x7 = new Function(); // A new Function object
var x8 = new Date();     // A new Date object

// Display the type of all objects
document.getElementById("demo").innerHTML =
"x1: " + typeof x1 + "<br>" +
"x2: " + typeof x2 + "<br>" +
"x3: " + typeof x3 + "<br>" +
"x4: " + typeof x4 + "<br>" +
"x5: " + typeof x5 + "<br>" +
"x6: " + typeof x6 + "<br>" +
"x7: " + typeof x7 + "<br>" +
"x8: " + typeof x8 + "<br>";
</script>

<p>There is no need to use String(), Number(), Boolean(), Array(), and RegExp()</p>

<p>Rea</pre>d the JavaScript tutorials.</p>


variables

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

<script>
var x1 = {};        // object
var x2 = "";        // string 
var x3 = 0;         // number
var x4 = false;     // boolean
var x5 = [];        // object (not array)
var x6 = /()/;      // object
var x7 = function(){};  // function

// Display the type of all
document.getElementById("demo").innerHTML =
"x1: " + typeof x1 + "<br>" +
"x2: " + typeof x2 + "<br>" +
"x3: " + typeof x3 + "<br>" +
"x4: " + typeof x4 + "<br>" +
"x5: " + typeof x5 + "<br>" +
"x6: " + typeof x6 + "<br>" +
"x7: " + typeof x7 + "<br>";
</script>

JavaScript Objects

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

<script>
function Person(first, last, age, eye) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eye;
}

var myFather = new Person("John", "Doe", 50, "blue");
var myMother = new Person("Sally", "Rally", 48, "green");

document.getElementById("demo").innerHTML =
"My father is " + myFather.age + ". My mother is " + myMother.age; 
</script>

JavaScript Objects

<p>You cannot add a new property to a constructor function.</p>

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

<script>
function Person(first, last, age, eye) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eye;
}
Person.nationality = "English";

var myFather = new Person("John", "Doe", 50, "blue");
var myMother = new Person("Sally", "Rally", 48, "green");

document.getElementById("demo").innerHTML =
"The nationality of my father is " + myFather.nationality; 
</script>

JavaScript Objects

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

<script>
function Person(first, last, age, eye) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eye;
    this.nationality = "English";
}

var myFather = new Person("John", "Doe", 50, "blue");
var myMother = new Person("Sally", "Rally", 48, "green");

document.getElementById("demo").innerHTML =
"My father is " + myFather.nationality + ". My mother is " + myMother.nationality; 
</script>

JavaScript Objects

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

<script>
function Person(first, last, age, eye) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eye;
}
Person.prototype.nationality = "English";

var myFather = new Person("John", "Doe", 50, "blue");
document.getElementById("demo").innerHTML =
"My father is " + myFather.nationality; 
</script>

JavaScript Objects

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

<script>
function Person(first, last, age, eye) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eye;
}
Person.prototype.name = function() {
    return this.firstName + " " + this.lastName
};

var myFather = new Person("John", "Doe", 50, "blue");
document.getElementById("demo").innerHTML =
"My father is " + myFather.name(); 
</script>

A function can be stored in a variable:

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

<script>
var x = function (a, b) {return a * b};
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>



After a function has been stored in a variable the variable can be used as a function

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

<script>
var x = function (a, b) {return a * b};
document.getElementById("demo").innerHTML = x(4, 3);
</script>

</body>
</html>

JavaScript has an built-in function constructor.

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

<script>
var myFunction = new Function("a", "b", "return a * b");
document.getElementById("demo").innerHTML = myFunction(4, 3);
</script>


return

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

<script>
var myFunction = function (a, b) {return a * b}
document.getElementById("demo").innerHTML = myFunction(4, 3);
</script>


Functions can be invoked automatically without being called:

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

<script>
(function () {
    document.getElementById("demo").innerHTML = "Hello! I called myself";
})();
</script>

</body>
</html>

Functions can be treated as values:

<p>x = myFunction(4,3) or x = 12</p>
<p>In both cases, x becomes a number with the value of 12.</p>
<p id="demo"></p>

<script>
function myFunction(a, b) {
    return a * b;
}
var x = myFunction(4, 3);
document.getElementById("demo").innerHTML = x;
</script>


Functions can be used in expressions.

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

<script>
function myFunction(a, b) {
    return a * b;
}
var x = myFunction(4, 3) * 2;
document.getElementById("demo").innerHTML = x;
</script>


The arguments.length property returns the number of arguments received by the function:

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

<script>
function myFunction(a, b) {
    return arguments.length;
}
document.getElementById("demo").innerHTML = myFunction(4, 3);
</script>

The toString() method returns the function as a string:

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

<script>
function myFunction(a, b) {
    return a * b;
}
document.getElementById("demo").innerHTML = myFunction.toString();
</script>

Setting a default value to a function parameter.

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

<script>
function myFunction(x, y) {
    if (y === undefined) {
        y = 0;
    }    
    return x * y;
}
document.getElementById("demo").innerHTML = myFunction(4);
</script>

</body>
</html>



Finding the largest number.

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

<script>
function findMax() {
    var i;
    var max = -Infinity;
    for(i = 0; i < arguments.length; i++) {
        if (arguments[i] > max) {
            max = arguments[i];
        }
    }
    return max;
} 
document.getElementById("demo").innerHTML = findMax(4, 5, 6);
</script>

</body>
</html>



Sum of all arguments:

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

<script>
function sumAll() {
    var i;
    var sum = 0;
    for(i = 0; i < arguments.length; i++) {
        sum += arguments[i];
    }
    return sum;
} 
document.getElementById("demo").innerHTML =
sumAll(1, 123, 500, 115, 44, 88);
</script>

</body>
</html>



JavaScript Functions

<p>The global function (myFunction) returns the product of the arguments (a ,b):</p>

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

<script>
function myFunction(a, b) {
    return a * b;
}
document.getElementById("demo").innerHTML = myFunction(10, 2); 
</script>

</body>
</html>

JavaScript Functions

<p>Global functions automatically become window methods. Invocing myFunction() is the same as invocong window.myFunction().</p>

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

<script>
function myFunction(a, b) {
    return a * b;
}
document.getElementById("demo").innerHTML = window.myFunction(10, 2); 
</script>

</body>
</html>

JavaScript Functions

<p>In HTML the value of <b>this</b>, in a global function, is the window object.</p>

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

<script>
var x = myFunction();
function myFunction() {
    return this;
}
document.getElementById("demo").innerHTML = x; 
</script>

</body>
</html>

JavaScript Functions

<p>myObject.fullName() will return John Doe:</p>

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

<script>
var myObject = {
    firstName:"John",
    lastName: "Doe",
    fullName: function() {
        return this.firstName + " " + this.lastName;
    }
}
document.getElementById("demo").innerHTML = myObject.fullName(); 
</script>

</body>
</html>

JavaScript Functions

<p>The value of <b>this</b>, in an object method, is the owner object.</p>

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

<script>
var myObject = {
    firstName:"John",
    lastName: "Doe",
    fullName: function() {
        return this;
    }
}
document.getElementById("demo").innerHTML = myObject.fullName();
</script>

</body>
</html>

JavaScript Functions

<p>In this example, myFunction is a function constructor:</p>

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

<script>
function myFunction(arg1, arg2) {
    this.firstName = arg1;
    this.lastName  = arg2;
}

var x = new myFunction("John","Doe")
document.getElementById("demo").innerHTML = x.firstName; 
</script>

</body>
</html>

JavaScript Functions

<p>This example creates an object with 3 properties (firstName, lastName, fullName).</p>
<p>The fullName property is a method:</p> 

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

<script>
var myObject = {
    firstName:"John",
    lastName: "Doe",
    fullName: function() {
        return this.firstName + " " + this.lastName;
    }
}
x = myObject.fullName();
document.getElementById("demo").innerHTML = x; 
</script>

</body>
</html>

JavaScript Functions

<p>This <strong>call()</strong> example uses the fullName method of person on myObject:</p>

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

<script>
var person = {
    firstName:"John",
    lastName: "Doe",
    fullName: function() {
        return this.firstName + " " + this.lastName;
    }
}
var myObject = {
    firstName:"Mary",
    lastName: "Doe",
}
x = person.fullName.call(myObject); 
document.getElementById("demo").innerHTML = x; 
</script>

</body>
</html>



JavaScript Functions

<p>This <strong>apply()</strong> example uses the fullName method of person on myObject:</p>

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

<script>
var person = {
    firstName:"John",
    lastName: "Doe",
    fullName: function() {
        return this.firstName + " " + this.lastName;
    }
}
var myObject = {
    firstName:"Mary",
    lastName: "Doe",
}
x = person.fullName.apply(myObject); 
document.getElementById("demo").innerHTML = x; 
</script>

</body>
</html>



JavaScript Math.max()

<p>This example returns the highest number in a list of number arguments:</p>

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

<script>
document.getElementById("demo").innerHTML = Math.max(1,2,3); 
</script>

</body>
</html>

JavaScript apply()

<p>This example returns the highest number in an array of numbers:</p>

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

<script>
document.getElementById("demo").innerHTML = Math.max.apply(null,[1,2,3]); 
</script>

</body>
</html>


A function can access variables defined inside the function:

<button type="button" onclick="myFunction()">Click Me!</button>

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

<script>
function myFunction() {
    var a = 4;
    document.getElementById("demo").innerHTML = a * a;
} 

</script>

A function can access variables defined outside the function:

<button type="button" onclick="myFunction()">Click Me!</button>

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

<script>
var a = 4;
function myFunction() {
    document.getElementById("demo").innerHTML = a * a;
} 
</script>

Counting with a global variable.

<button type="button" onclick="myFunction()">Count!</button>

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

<script>
var counter = 0;

function add() {
    return counter += 1;
}

function myFunction(){
    document.getElementById("demo").innerHTML = add();
}
</script>

Counting with a local variable.

<button type="button" onclick="myFunction()">Count!</button>

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

<script>
function add() {
    var counter = 0;
    return counter += 1;
}

function myFunction(){
    document.getElementById("demo").innerHTML = add();
}
</script>

Counting with a local variable.

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

<script>
document.getElementById("demo").innerHTML = add();
function add() {
    var counter = 0;
    function plus() {counter += 1;}
    plus();    
    return counter; 
}
</script>

Counting with a local variable.

<button type="button" onclick="myFunction()">Count!</button>

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

<script>
var add = (function () {
    var counter = 0;
    return function () {return counter += 1;}
})();

function myFunction(){
    document.getElementById("demo").innerHTML = add();
}
</script>

My First Page

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

<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>

getElementById

<p id="intro">Hello World!</p>

<p>This example demonstrates the <b>getElementById</b> method!</p>

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

<script>
var myElement = document.getElementById("intro");
document.getElementById("demo").innerHTML = 
"The text from the intro paragraph is " + myElement.innerHTML;
</script>

Hello World!

<p>The DOM is very useful.</p>
<p>This example demonstrates the <b>getElementsByTagName</b> method</p>

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

<script>
var x = document.getElementsByTagName("p");
document.getElementById("demo").innerHTML = 
'The first paragraph (index 0) is: ' + x[0].innerHTML;
</script>

Hello World!

<div id="main">
<p>The DOM is very useful.</p>
<p>This example demonstrates the <b>getElementsByTagName</b> method</p>
</div>

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

<script>
var x = document.getElementById("main");
var y = x.getElementsByTagName("p");
document.getElementById("demo").innerHTML = 
'The first paragraph (index 0) inside "main" is: ' + y[0].innerHTML;
</script>

Hello World!

<p class="intro">The DOM is very useful.</p>
<p class="intro">This example demonstrates the <b>getElementsByClassName</b> method.</p>

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

<script>
var x = document.getElementsByClassName("intro");
document.getElementById("demo").innerHTML = 
'The first paragraph (index 0) with class="intro": ' + x[0].innerHTML;
</script>

Hello World!

<p class="intro">The DOM is very useful.</p>
<p class="intro">This example demonstrates the <b>querySelectorAll</b> method.</p>

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

<script>
var x = document.querySelectorAll("p.intro");
document.getElementById("demo").innerHTML = 
'The first paragraph (index 0) with class="intro": ' + x[0].innerHTML;
</script>

form

<form id="frm1" action="/action_page.php">
  First name: <input type="text" name="fname" value="Donald"><br>
  Last name: <input type="text" name="lname" value="Duck"><br><br>
  <input type="submit" value="Submit">
</form> 

<p>Click "Try it" to display the value of each element in the form.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = document.forms["frm1"];
    var text = "";
    var i;
    for (i = 0; i < x.length ;i++) {
        text += x.elements[i].value + "<br>";
    }
    document.getElementById("demo").innerHTML = text;
}
</script>


document.anchors

<br>

<a name="html">HTML Tutorial</a><br>
<a name="css">CSS Tutorial</a><br>
<a name="xml">XML Tutorial</a><br>

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

<script>
document.getElementById("demo").innerHTML =
"Number of anchors are: " + document.anchors.length;
</script>



document.body

<br>

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

<script>
alert(document.body.innerHTML);
</script>


document.documentElement

<br>

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

<script>
alert(document.documentElement.innerHTML);
</script>


document.embeds

<br>

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

<script>
document.getElementById("demo").innerHTML =
"Number of embeds: " + document.embeds.length;
</script>


document.forms

<br>

<form action="">
First name: <input type="text" name="fname" value="Donald">
<input type="submit" value="Submit">
</form> 

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

<script>
document.getElementById("demo").innerHTML =
"Number of forms: " + document.forms.length;
</script>


document.head

<br>

<html>
  <head>
<title>W3Schools Demo</title>
  </head>
<body>

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

<script>
document.getElementById("demo").innerHTML =
document.head;
</script>


document.images

<br>

<img src="https://www.w3schools.com/js/pic_htmltree.gif">
<img src="https://www.w3schools.com/js/pic_navigate.gif">

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

<script>
document.getElementById("demo").innerHTML =
"Number of images: " + document.images.length;
</script>


document.links

<br>

<p>
<a href="/html/default.asp">HTML</a>
<br>
<a href="/css/default.asp">CSS</a>
</p>

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

<script>
document.getElementById("demo").innerHTML =
"Number of links: " + document.links.length;
</script>


document.scripts

<br>

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

<script>
document.getElementById("demo").innerHTML =
"Number of scripts: " + document.scripts.length;
</script>


document.title

<br>

<html>
  <head>
<title>W3Schools Demo</title>
  </head>
<body>

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

<script>
document.getElementById("demo").innerHTML =
"The title of this document is: " + document.title;
</script>


document.write

<script>
document.write(Date());
</script>


JavaScript can Change HTML

<p id="p1">Hello World!</p>

<script>
document.getElementById("p1").innerHTML = "New text!";
</script>

<p>The</pre> paragraph above was changed by a script.</p>


element.innerHTML

<h1 id="id01">Old Heading</h1>

<script>
var element = document.getElementById("id01");
element.innerHTML = "New Heading";
</script>

<p>Jav</pre>aScript changed "Old Heading" to "New Heading".</p>


document.getElementById

<img id="image" src="https://www.w3schools.com/js/smiley.gif" width="160" height="120">

<script>
document.getElementById("image").src = "landscape.jpg";
</script>

<p>The</pre> original image was smiley.gif, but the script changed it to landscape.jpg</p>


document.getElementById

<p id="p1">Hello World!</p>
<p id="p2">Hello World!</p>

<script>
document.getElementById("p2").style.color = "blue";
document.getElementById("p2").style.fontFamily = "Arial";
document.getElementById("p2").style.fontSize = "larger";
</script>

<p>The</pre> paragraph above was changed by a script.</p>


document.getElementById

<h1 id="id1">My Heading 1</h1>

<button type="button" 
onclick="document.getElementById('id1').style.color = 'red'">
Click </pre>Me!</button>


Visibility

<br>

<p id="p1">
This is a text.
This is a text.
This is a text.
This is a text.
</p>

<input type="button" value="Hide text" onclick="document.getElementById('p1').style.visibility='hidden'">
<input type="button" value="Show text" onclick="document.getElementById('p1').style.visibility='visible'">

My First JavaScript Animation

<div i</pre>d="animate">My animation will go here</div>


Animation

<html>
<style>
#container {
  width: 400px;
  height: 400px;
  position: relative;
  background: yellow;
}
#animate {
  width: 50px;
  height: 50px;
  position: absolute;
  background: red;
}
</style>
<body>

My First JavaScript Animation

<div id="container"> <div id="animate"></div> </div>

Animation

<html>
<style>
#container {
  width: 400px;
  height: 400px;
  position: relative;
  background: yellow;
}
#animate {
  width: 50px;
  height: 50px;
  position: absolute;
  background-color: red;
}
</style>
<body>

<p>
<button onclick="myMove()">Click Me</button>
</p> 

<div id ="container">
<div id ="animate"></div>
</div>

<script>
function myMove() {
  var elem = document.getElementById("animate");   
  var pos = 0;
  var id = setInterval(frame, 5);
  function frame() {
    if (pos == 350) {
      clearInterval(id);
    } else {
      pos++; 
      elem.style.top = pos + 'px'; 
      elem.style.left = pos + 'px'; 
    }
  }
}
</script>


changeText

</pre>h1 onclick="this.innerHTML='Ooops!'">Click on this text!</h1>


changeText

<h1 onclick="changeText(this)">Click on this text!</h1>

<script>
function changeText(id) {
    id.innerHTML = "Ooops!";
}
</script>


Click the button to display the date.

<button onclick="displayDate()">The time is?</button>

<script>
function displayDate() {
    document.getElementById("demo").innerHTML = Date();
}
</script>

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

Click "Try it" to execute the displayDate() function.

<button id="myBtn">Try it</button>

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

<script>
document.getElementById("myBtn").onclick = displayDate;

function displayDate() {
    document.getElementById("demo").innerHTML = Date();
}
</script>

checkCookies

<html>
<body onload="checkCookies()">

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

<script>
function checkCookies() {
    var text = "";
    if (navigator.cookieEnabled == true) {
        text = "Cookies are enabled.";
    } else {
        text = "Cookies are not enabled.";
    }
    document.getElementById("demo").innerHTML = text;
}
</script>


toUpperCase

<html>
<head>
<script>
function myFunction() {
    var x = document.getElementById("fname");
    x.value = x.value.toUpperCase();
}
</script>
</head>
<body>

Enter your name: <input type="text" id="fname" onchange="myFunction()">
<p>When you leave the input field, a function is triggered which transforms the input text to upper </pre>case.</p>


Mouse Over Me

<div onmouseover="mOver(this)" onmouseout="mOut(this)" 
style="background-color:#D94A38;width:120px;height:20px;padding:40px;">
Mouse Over Me</div>

<script>
function mOver(obj) {
    obj.innerHTML = "Thank You"
}

function mOut(obj) {
    obj.innerHTML = "Mouse Over Me"
}
</script>


onmousedown

<div onmousedown="mDown(this)" onmouseup="mUp(this)"
style="background-color:#D94A38;width:90px;height:20px;padding:40px;">
Click Me</div>

<script>
function mDown(obj) {
    obj.style.backgroundColor = "#1ec5e5";
    obj.innerHTML = "Release Me";
}

function mUp(obj) {
    obj.style.backgroundColor="#D94A38";
    obj.innerHTML="Thank You";
}
</script>


onmousedown and onmouseup

<br>

<html>
<head>
<script>
function lighton() {
    document.getElementById('myimage').src = "bulbon.gif";
}
function lightoff() {
    document.getElementById('myimage').src = "bulboff.gif";
}
</script>
</head>

<body>

<img id="myimage" onmousedown="lighton()" onmouseup="lightoff()" src="https://www.w3schools.com/js/bulboff.gif" width="100" height="180" />

<p>Cli</pre>ck mouse and hold down!</p>


onload

<br>

<html>
<head>

<script>
function mymessage() {
    alert("This message was triggered from the onload event");
}
</script>
</head>

<body onload="mymessage()">
</body>
/html>

onfocus

<br>

<html>
<head>
<script>
function myFunction(x) {
    x.style.background = "yellow";
}
</script>
</head>
<body>

Enter your name: <input type="text" onfocus="myFunction(this)">

<p>When the input field gets focus, a function is triggered which changes the background-color.</p>


Mouse Events

<br>

<h1 onmouseover="style.color='red'"
onmouseout="style.color='black'">
Mouse over this text</h1>


uses the addEventListener() method to attach a click event to a button.

<button id="myBtn">Try it</button>

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

<script>
document.getElementById("myBtn").addEventListener("click", displayDate);

function displayDate() {
    document.getElementById("demo").innerHTML = Date();
}
</script>

uses the addEventListener() method to attach a click event to a button.

<button id="myBtn">Try it</button>

<script>
document.getElementById("myBtn").addEventListener("click", function(){
    alert("Hello World!");
});
</script>

uses the addEventListener() method to execute a function

<button id="myBtn">Try it</button>

<script>
document.getElementById("myBtn").addEventListener("click", myFunction);

function myFunction() {
    alert ("Hello World!");
}
</script>

uses the addEventListener() method to add two click events to the same button.

<button id="myBtn">Try it</button>

<script>
var x = document.getElementById("myBtn");
x.addEventListener("click", myFunction);
x.addEventListener("click", someOtherFunction);

function myFunction() {
    alert ("Hello World!");
}

function someOtherFunction() {
    alert ("This function was also executed!");
}
</script>

uses the addEventListener() method to add many events on the same button.

<button id="myBtn">Try it</button>

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

<script>
var x = document.getElementById("myBtn");
x.addEventListener("mouseover", myFunction);
x.addEventListener("click", mySecondFunction);
x.addEventListener("mouseout", myThirdFunction);

function myFunction() {
    document.getElementById("demo").innerHTML += "Moused over!<br>";
}

function mySecondFunction() {
    document.getElementById("demo").innerHTML += "Clicked!<br>";
}

function myThirdFunction() {
    document.getElementById("demo").innerHTML += "Moused out!<br>";
}
</script>

uses the addEventListener() method on the window object.

<p>Try resizing this browser window to trigger the "resize" event handler.</p>

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

<script>
window.addEventListener("resize", function(){
    document.getElementById("demo").innerHTML = Math.random();
});
</script>

pass parameter values when using addEventListener() method.</p>

<p>Click the button to perform a calculation.</p>

<button id="myBtn">Try it</button>

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

<script>
var p1 = 5;
var p2 = 7;

document.getElementById("myBtn").addEventListener("click", function() {
    myFunction(p1, p2);
});

function myFunction(a, b) {
    var result = a * b;
    document.getElementById("demo").innerHTML = result;
}
</script>

difference between bubbling and capturing when adding event listeners

<html>
<head>
<style>
div {
    background-color: coral;
    border: 1px solid;
    padding: 50px;
}
</style>
</head>
<body>

<p>This example demonstrates the difference between bubbling and capturing when adding event listeners.</p>

<div id="myDiv">
  <p id="myP">Click this paragraph, I am Bubbling.</p>
</div><br>

<div id="myDiv2">
  <p id="myP2">Click this paragraph, I am Capturing.</p>
</div>

<script>
document.getElementById("myP").addEventListener("click", function() {
    alert("You clicked the P element!");
}, false);

document.getElementById("myDiv").addEventListener("click", function() {
    alert("You clicked the DIV element!");
}, false);

document.getElementById("myP2").addEventListener("click", function() {
    alert("You clicked the P element!");
}, true);

document.getElementById("myDiv2").addEventListener("click", function() {
    alert("You clicked the DIV element!");
}, true);
</script>

onmousemove event handler

<html>
<head>
<style>
#myDIV {
    background-color: coral;
    border: 1px solid;
    padding: 50px;
    color: white;
}
</style>
</head>
<body>

<div id="myDIV">This div element has an onmousemove event handler that displays a random number every time you move your mouse inside this orange field.
  <p>Click the button to remove the DIV's event handler.</p>
  <button onclick="removeHandler()" id="myBtn">Try it</button>
</div>

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

<script>
document.getElementById("myDIV").addEventListener("mousemove", myFunction);

function myFunction() {
    document.getElementById("demo").innerHTML = Math.random();
}

function removeHandler() {
    document.getElementById("myDIV").removeEventListener("mousemove", myFunction);
}
</script>

</body>
</html>



The addEventListener() method is not supported Internet Explorer 8 and earlier versions.

<p>This example demonstrates a solution that will work for all browsers.</p>

<button id="myBtn">Try it</button>

<script>
var x = document.getElementById("myBtn");
if (x.addEventListener) {
    x.addEventListener("click", myFunction);
} else if (x.attachEvent) {
    x.attachEvent("onclick", myFunction);
}

function myFunction() {
    alert("Hello World!");
}
</script>

retrieves the text

<h1 id="id01">My First Page</h1>
<p id="id02"></p>

<script>
document.getElementById("id02").innerHTML = document.getElementById("id01").innerHTML;
</script>


retrieves the text

<h1 id="id01">My First Page</h1>
<p id="id02"></p>

<script>
document.getElementById("id02").innerHTML = document.getElementById("id01").firstChild.nodeValue;
</script>


retrieves the text

<h1 id="id01">My First Page</h1>
<p id="id02"></p>

<script>
document.getElementById("id02").innerHTML = document.getElementById("id01").childNodes[0].nodeValue;
</script>


Hello World!

<div>
<p>The DOM is very useful!</p>
<p>This example demonstrates the <b>document.body</b> property.</p>
</div>

<script>
alert(document.body.innerHTML);
</script>

DOM Root Nodes

<div>
<p>The DOM is very useful!</p>
<p>This example demonstrates the <b>document.documentElement</b> property.</p>
</div>

<script>
alert(document.documentElement.innerHTML);
</script>

DOM Root Nodes

<h1 id="id01">My First Page</h1>
<p id="id02"></p>

<script>
document.getElementById("id02").innerHTML = document.getElementById("id01").nodeName;
</script>

The nodeType Property

<h1 id="id01">My First Page</h1>
<p id="id02"></p>

<script>
document.getElementById("id02").innerHTML = document.getElementById("id01").nodeType;
</script>

Creating New HTML Elements (Nodes)

<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>

<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
</script>

Creating new HTML Elements - insertBefore()

<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>

<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);

var element = document.getElementById("div1");
var child = document.getElementById("p1");
element.insertBefore(para,child);
</script>

Removing Existing HTML Elements

<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>

<script>
var parent = document.getElementById("div1");
var child = document.getElementById("p1");
parent.removeChild(child);
</script>

Removing Existing HTML Elements

<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>

<script>
var parent = document.getElementById("div1");
var child = document.getElementById("p1");
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);
parent.replaceChild(para,child);
</script>

JavaScript HTML DOM

<p>Hello World!</p>

<p>Hello Norway!</p>

<p>Click the button to change the color of all p elements.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    var myCollection = document.getElementsByTagName("p");
    var i;
    for (i = 0; i < myCollection.length; i++) {
        myCollection[i].style.color = "red";
    }
}
</script>

JavaScript HTML DOM!

<p>Hello World!</p>

<p>Hello Norway!</p>

<p>Click the button to change the color of all p elements.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    var myNodelist = document.querySelectorAll("p");
    var i;
    for (i = 0; i < myNodelist.length; i++) {
        myNodelist[i].style.color = "red";
    }
}
</script>

Window Size

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

<script>
var w = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;

var h = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;

var x = document.getElementById("demo");
x.innerHTML = "Browser inner window width: " + w + ", height: " + h + ".";
</script>

Window Screen Width

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

<script>
document.getElementById("demo").innerHTML = 
"Screen width is " + screen.width;
</script>

Window Screen Height

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

<script>
document.getElementById("demo").innerHTML = 
"Screen height is " + screen.height;
</script>

Window Screen Available Width

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

<script>
document.getElementById("demo").innerHTML = 
"Available screen width is " + screen.availWidth;
</script>

Window Screen Available Height

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

<script>
document.getElementById("demo").innerHTML = 
"Available screen height is " + screen.availHeight;
</script>

Window Screen Color Depth

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

<script>
document.getElementById("demo").innerHTML = 
"Screen color depth is " + screen.colorDepth;
</script>

Window Screen Pixel Depth

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

<script>
document.getElementById("demo").innerHTML = 
"Screen pixel depth is " + screen.pixelDepth;
</script>

The window.location object

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

<script>
document.getElementById("demo").innerHTML = 
"The full URL of this page is:<br>" + window.location.href;
</script>

The window.location object

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

<script>
document.getElementById("demo").innerHTML = 
"Page hostname is: " + window.location.hostname;
</script>

The window.location object

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

<script>
document.getElementById("demo").innerHTML =
"Page path is: " + window.location.pathname;
</script>

The window.location object

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

<script>
document.getElementById("demo").innerHTML =
"The page protocol is: " + window.location.protocol;
</script>

The window.location object

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

<p><b>Note: </b>If the port number is default (80 for http and 443 for https), most browsers will display 0 or nothing.</p>

<script>
document.getElementById("demo").innerHTML = 
"The URL port number of the current page is: " + window.location.port;
</script>

The window.location object

<input type="button" value="Load new document" onclick="newDoc()">

<script>
function newDoc() {
    window.location.assign("https://www.w3schools.com")
}
</script>

The Navigator Object

<p>The cookieEnabled property returns true if cookies are enabled:</p>

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

<script>
document.getElementById("demo").innerHTML =
"navigator.cookieEnabled is " + navigator.cookieEnabled;
</script>

The Navigator Object

<p>The appName property returns the application name of the browser:</p>

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

<p>Strange enough, "Netscape" is the application name for both IE11, Chrome, Firefox, and Safari.</p>

<script>
document.getElementById("demo").innerHTML = 
"navigator.appName is " + navigator.appName;
</script>

JavaScript Navigator

<p>The appCodeName property returns the code name of the browser.</p>

<p>Do not rely on it! "Mozilla" is the application code name for both Chrome, Firefox, IE, Safari, and Opera.</p>

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

<script>
document.getElementById("demo").innerHTML = 
"navigator.appCodeName is " + navigator.appCodeName;
</script>

The Navigator Object

<p>The product property returns the product name of the browser.</p>

<p>Do not rely on it! Most browsers returns "Gecko" as product name!</p>

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

<script>
document.getElementById("demo").innerHTML =
"navigator.product is " + navigator.product;
</script>

The Navigator Object

<p>The appVersion property returns version information about the browser:</p>

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

<script>
document.getElementById("demo").innerHTML = navigator.appVersion;
</script>

The Navigator Object

<p>The userAgent property returns the user-agent header sent by the browser to the server:</p>

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

<script>
document.getElementById("demo").innerHTML =
navigator.userAgent;
</script>

The Navigator Object

<p>The platform property returns the browser platform (operating system):</p>

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

<script>
document.getElementById("demo").innerHTML = 
"navigator.platform is " + navigator.platform;
</script>

The Navigator Object

<p>The language property returns the browser's language:</p>

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

<script>
document.getElementById("demo").innerHTML =
"navigator.language is " + navigator.language;
</script>

The Navigator Object

<p>The onLine property returns true if the browser is online:</p>

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

<script>
document.getElementById("demo").innerHTML =
"navigator.onLine is " + navigator.onLine;
</script>

The Navigator Object

<p>The javaEnabled() method returns true if Java is enabled:</p>

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

<script>
document.getElementById("demo").innerHTML =
"javaEnabled is " + navigator.javaEnabled();
</script>

JavaScript Alert

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    alert("I am an alert box!");
}
</script>

JavaScript Confirm Box

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var txt;
    if (confirm("Press a button!")) {
        txt = "You pressed OK!";
    } else {
        txt = "You pressed Cancel!";
    }
    document.getElementById("demo").innerHTML = txt;
}
</script>

JavaScript Prompt

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var txt;
    var person = prompt("Please enter your name:", "Harry Potter");
    if (person == null || person == "") {
        txt = "User cancelled the prompt.";
    } else {
        txt = "Hello " + person + "! How are you today?";
    }
    document.getElementById("demo").innerHTML = txt;
}
</script>

JavaScript

<p>Line-breaks in a popup box.</p>

<button onclick="alert('Hello\nHow are you?')">Try it</button>


Click "Try it". Wait 3 seconds, and the page will alert "Hello".

<button onclick="setTimeout(myFunction, 3000);">Try it</button>

<script>
function myFunction() {
    alert('Hello');
}
</script>

Click "Try it". Wait 3 seconds. The page will alert "Hello".

<p>Click "Stop" to prevent the first function to execute.</p>
<p>(You must click "Stop" before the 3 seconds are up.)</p>

<button onclick="myVar = setTimeout(myFunction, 3000)">Try it</button>

<button onclick="clearTimeout(myVar)">Stop it</button>

<script>
function myFunction() {
    alert("Hello");
}
</pre></script>

A script on this page starts this clock:

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

<script>
var myVar = setInterval(myTimer, 1000);

function myTimer() {
    var d = new Date();
    document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
</script>

A script on this page starts this clock:

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

<button onclick="clearInterval(myVar)">Stop time</button>

<script>
var myVar = setInterval(myTimer ,1000);
function myTimer() {
    var d = new Date();
    document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
</script>

Another simple timing

<br>

<button onclick="timedText()">Try it</button>

<p id="demo">Click on "Try it". I will display when two, four, and six seconds have passed.</p>

<script>
function timedText() {
    setTimeout(myTimeout1, 2000) 
    setTimeout(myTimeout2, 4000) 
    setTimeout(myTimeout3, 6000) 
}
function myTimeout1() {
    document.getElementById("demo").innerHTML = "2 seconds";
}
function myTimeout2() {
    document.getElementById("demo").innerHTML = "4 seconds";
}
function myTimeout3() {
    document.getElementById("demo").innerHTML = "6 seconds";
}
</script>


A clock created with a timing event

<br>

<html>
<head>
<script>
function startTime() {
    var today = new Date();
    var h = today.getHours();
    var m = today.getMinutes();
    var s = today.getSeconds();
    m = checkTime(m);
    s = checkTime(s);
    document.getElementById('txt').innerHTML =
    h + ":" + m + ":" + s;
    var t = setTimeout(startTime, 500);
}
function checkTime(i) {
    if (i < 10) {i = "0" + i};  // add zero in front of numbers < 10
    return i;
}
</script>
</head>

<body onload="startTime()">

<div id="txt"></div>


Create a Cookie with JavaScript

<html>
<head>
<script>

function setCookie(cname,cvalue,exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires=" + d.toGMTString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

function checkCookie() {
    var user=getCookie("username");
    if (user != "") {
        alert("Welcome again " + user);
    } else {
       user = prompt("Please enter your name:","");
       if (user != "" && user != null) {
           setCookie("username", user, 30);
       }
    }
}

</script>
</head
ad="checkCookie()">

XMLHttpRequest Object

<div id="demo">

The XMLHttpRequest Object

<button type="button" onclick="loadDoc()">Change Content</button> </div> <script> function loadDoc() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("demo").innerHTML = this.responseText; } }; xhttp.open("GET", "ajax_info.txt", true); xhttp.send(); } </script>

The XMLHttpRequest Object

<p id="demo">Let AJAX change this text.</p>

<button type="button" onclick="loadDoc()">Change Content</button>

<script>
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "ajax_info.txt", true);
  xhttp.send();
}
</script>

The XMLHttpRequest Object

<p id="demo">Let AJAX change this text.</p>

<button type="button" onclick="loadDoc()">Change Content</button>

<script>
function loadDoc() {
  var xhttp;
  if (window.XMLHttpRequest) {
    // code for modern browsers
    xhttp = new XMLHttpRequest();
    } else {
    // code for IE6, IE5
    xhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "ajax_info.txt", true);
  xhttp.send();
}
</script>

The XMLHttpRequest Object

<button type="button" onclick="loadDoc()">Request data</button>

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


<script>
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "demo_get.asp", true);
  xhttp.send();
}
</script>

The XMLHttpRequest Object

<button type="button" onclick="loadDoc()">Request data</button>

<p>Click the button several times to see if the time changes, or if the file is cached.</p>

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

<script>
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange=function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "demo_get.asp?t=" + Math.random(), true);
  xhttp.send();
}
</script>

The XMLHttpRequest Object

<button type="button" onclick="loadDoc()">Request data</button>

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

<script>
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "demo_get2.asp?fname=Henry&lname=Ford", true);
  xhttp.send();
}
</script>
</pre> 

The XMLHttpRequest Object

<button type="button" onclick="loadDoc()">Request data</button>

<p id="demo"></p>
 
<script>
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML = this.responseText;
    }
  };
  xhttp.open("POST", "demo_post.asp", true);
  xhttp.send();
}
</script>

The XMLHttpRequest Object

<button type="button" onclick="loadDoc()">Request data</button>

<p id="demo"></p>
 
<script>
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML = this.responseText;
    }
  };
  xhttp.open("POST", "demo_post2.asp", true);
  xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhttp.send("fname=Henry&lname=Ford");
}
</script>

XMLHttpRequest Object

<div id="demo">

The XMLHttpRequest Object

<button type="button" onclick="loadDoc()">Change Content</button> </div> <script> function loadDoc() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("demo").innerHTML = this.responseText; } }; xhttp.open("GET", "ajax_info.txt", true); xhttp.send(); } </script>

The XMLHttpRequest Object

<p id="demo">Let AJAX change this text.</p>

<button type="button" onclick="loadDoc()">Change Content</button>

<script>
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.open("GET", "ajax_info.txt", false);
  xhttp.send();
  document.getElementById("demo").innerHTML = xhttp.responseText;
}
</script>

XMLHttpRequest Object

<div id="demo">

The XMLHttpRequest Object

<button type="button" onclick="loadDoc('ajax_info.txt', myFunction)">Change Content </button> </div> <script> function loadDoc(url, cFunction) { var xhttp; xhttp=new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { cFunction(this); } }; xhttp.open("GET", url, true); xhttp.send(); } function myFunction(xhttp) { document.getElementById("demo").innerHTML = xhttp.responseText; } </pre></script>

The XMLHttpRequest Object

<p id="demo"></p>
 
<script>
var xhttp, xmlDoc, txt, x, i;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
  xmlDoc = this.responseXML;
  txt = "";
  x = xmlDoc.getElementsByTagName("ARTIST");
  for (i = 0; i < x.length; i++) {
    txt = txt + x[i].childNodes[0].nodeValue + "<br>";
  }
  document.getElementById("demo").innerHTML = txt;
  }
};
xhttp.open("GET", "cd_catalog.xml", true);
xhttp.send();
</script>

The XMLHttpRequest Object

<p>The getAllResponseHeaders() function returns all the header information of a resource, like length, server-type, content-type, last-modified, etc:</p>

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

<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    document.getElementById("demo").innerHTML =
    this.getAllResponseHeaders();
  }
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
</script>

The XMLHttpRequest Object

<p>The getResponseHeader() function is used to return specific header information from a resource, like length, server-type, content-type, last-modified, etc:</p>

<p>Last modified: <span id="demo"></span></p>

<script>
var xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    document.getElementById("demo").innerHTML =
    this.getResponseHeader("Last-Modified");
  }
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
</script>

XMLHttpRequest Object

<html>
<style>
table,th,td {
  border : 1px solid black;
  border-collapse: collapse;
}
th,td {
  padding: 5px;
}
</style>
<body>

The XMLHttpRequest Object

<button type="button" onclick="loadDoc()">Get my CD collection</button> <br><br> <table id="demo"></table> <script> function loadDoc() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myFunction(this); } }; xhttp.open("GET", "cd_catalog.xml", true); xhttp.send(); } function myFunction(xml) { var i; var xmlDoc = xml.responseXML; var table="<tr><th>Artist</th><th>Title</th></tr>"; var x = xmlDoc.getElementsByTagName("CD"); for (i = 0; i <x.length; i++) { table += "<tr><td>" + x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue + "</td><td>" + x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue + "</td></tr>"; } document.getElementById("demo").innerHTML = table; } </script>

The XMLHttpRequest Object

<h3>Start typing a name in the input field below:</h3>

<form action=""> 
First name: <input type="text" id="txt1" onkeyup="showHint(this.value)">
</form>

<p>Suggestions: <span id="txtHint"></span></p> 

<script>
function showHint(str) {
  var xhttp;
  if (str.length == 0) { 
    document.getElementById("txtHint").innerHTML = "";
    return;
  }
  xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("txtHint").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "gethint.php?q="+str, true);
  xhttp.send();   
}
</script>

The XMLHttpRequest Object

<h3>Start typing a name in the input field below:</h3>

<form action=""> 
First name: <input type="text" id="txt1" onkeyup="showHint(this.value)">
</form>

<p>Suggestions: <span id="txtHint"></span></p> 

<script>
function showHint(str) {
  var xhttp;
  if (str.length == 0) { 
    document.getElementById("txtHint").innerHTML = "";
    return;
  }
  xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("txtHint").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "gethint.asp?q="+str, true);
  xhttp.send();
}
</script>

XMLHttpRequest Object

<html>
<style>
table,th,td {
  border : 1px solid black;
  border-collapse: collapse;
}
th,td {
  padding: 5px;
}
</style>
<body>

The XMLHttpRequest Object

<form action=""> <select name="customers" onchange="showCustomer(this.value)"> <option value="">Select a customer:</option> <option value="ALFKI">Alfreds Futterkiste</option> <option value="NORTS ">North/South</option> <option value="WOLZA">Wolski Zajazd</option> </select> </form> <br> <div id="txtHint">Customer info will be listed here...</div> <script> function showCustomer(str) { var xhttp; if (str == "") { document.getElementById("txtHint").innerHTML = ""; return; } xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("txtHint").innerHTML = this.responseText; } }; xhttp.open("GET", "getcustomer.asp?q="+str, true); xhttp.send(); } </script>

XMLHttpRequest Object

<html>
<style>
table,th,td {
  border : 1px solid black;
  border-collapse: collapse;
}
th,td {
  padding: 5px;
}
</style>
<body>

<button type="button" onclick="loadXMLDoc()">Get my CD collection</button>
<br><br>
<table id="demo"></table>

<script>
function loadXMLDoc() {
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      myFunction(this);
    }
  };
  xmlhttp.open("GET", "cd_catalog.xml", true);
  xmlhttp.send();
}
function myFunction(xml) {
  var i;
  var xmlDoc = xml.responseXML;
  var table="<tr><th>Artist</th><th>Title</th></tr>";
  var x = xmlDoc.getElementsByTagName("CD");
  for (i = 0; i <x.length; i++) { 
    table += "<tr><td>" +
    x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue +
    "</td><td>" +
    x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue +
    "</td></tr>";
  }
  document.getElementById("demo").innerHTML = table;
}
</script>


XMLHttpRequest Object

<div id='showCD'></div>

<script>
displayCD(0);

function displayCD(i) {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            myFunction(this, i);
        }
    };
    xmlhttp.open("GET", "cd_catalog.xml", true);
    xmlhttp.send();
}

function myFunction(xml, i) {
    var xmlDoc = xml.responseXML; 
    x = xmlDoc.getElementsByTagName("CD");
    document.getElementById("showCD").innerHTML =
    "Artist: " +
    x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue +
    "<br>Title: " +
    x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue +
    "<br>Year: " + 
    x[i].getElementsByTagName("YEAR")[0].childNodes[0].nodeValue;
}
</script>


XMLHttpRequest Object

<div id='showCD'></div><br>
<input type="button" onclick="previous()" value="<<">
<input type="button" onclick="next()" value=">>">

<script>
var i = 0, len;
displayCD(i);

function displayCD(i) {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            myFunction(this, i);
        }
    };
    xmlhttp.open("GET", "cd_catalog.xml", true);
    xmlhttp.send();
}

function myFunction(xml, i) {
    var xmlDoc = xml.responseXML; 
    x = xmlDoc.getElementsByTagName("CD");
    len = x.length;
    document.getElementById("showCD").innerHTML =
    "Artist: " +
    x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue +
    "<br>Title: " +
    x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue +
    "<br>Year: " + 
    x[i].getElementsByTagName("YEAR")[0].childNodes[0].nodeValue;
}

function next() {
if (i < len-1) {
  i++;
  displayCD(i);
  }
}

function previous() {
if (i > 0) {
  i--;
  displayCD(i);
  }
}
</script>


XMLHttpRequest Object

<html>
<style>
table,th,td {
  border : 1px solid black;
  border-collapse: collapse;
}
th,td {
  padding: 5px;
}
</style>
<body>

<p>Click on a CD to display album information.</p>
<p id='showCD'></p>
<table id="demo"></table>

<script>
var x,xmlhttp,xmlDoc
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "cd_catalog.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML; 
x = xmlDoc.getElementsByTagName("CD");
table="<tr><th>Artist</th><th>Title</th></tr>";
for (i = 0; i <x.length; i++) { 
  table += "<tr onclick='displayCD(" + i + ")'><td>";
  table += x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue;
  table += "</td><td>";
  table +=  x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue;
  table += "</td></tr>";
}
document.getElementById("demo").innerHTML = table;

function displayCD(i) {
  document.getElementById("showCD").innerHTML =
  "Artist: " +
  x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue +
  "<br>Title: " +
  x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue +
  "<br>Year: " + 
  x[i].getElementsByTagName("YEAR")[0].childNodes[0].nodeValue;
}
</script>


A simple AJAX example

<br>

<div id="demo">

The XMLHttpRequest Object

<button type="button" onclick="loadDoc()">Change Content</button> </div> <script> function loadDoc() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("demo").innerHTML = this.responseText; } }; xhttp.open("GET", "ajax_info.txt", true); xhttp.send(); } </script>

An AJAX example with a callback function

<br>

<div id="demo">

The XMLHttpRequest Object

<button type="button" onclick="loadDoc('ajax_info.txt', myFunction)">Change Content </button> </div> <script> function loadDoc(url, cFunction) { var xhttp; xhttp=new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { cFunction(this); } }; xhttp.open("GET", url, true); xhttp.send(); } function myFunction(xhttp) { document.getElementById("demo").innerHTML = xhttp.responseText; }script>

Retrieve all header information

<br>

The XMLHttpRequest Object

<p>The getAllResponseHeaders() function returns all the header information of a resource, like length, server-type, content-type, last-modified, etc:</p> <p id="demo"></p> <script> var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("demo").innerHTML = this.getAllResponseHeaders(); } }; xhttp.open("GET", "ajax_info.txt", true); xhttp.send(); </script>

Retrieve specific header information

<br>

The XMLHttpRequest Object

<p>The getResponseHeader() function is used to return specific header information from a resource, like length, server-type, content-type, last-modified, etc:</p> <p>Last modified: <span id="demo"></span></p> <script> var xhttp=new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("demo").innerHTML = this.getResponseHeader("Last-Modified"); } }; xhttp.open("GET", "ajax_info.txt", true); xhttp.send(); </script>

Load an XML file with AJAX

<br>

The XMLHttpRequest Object

Retrieve data from XML file

<p><b>Status:</b> <span id="A1"></span></p> <p><b>Status text:</b> <span id="A2"></span></p> <p><b>Response:</b> <span id="A3"></span></p> <button onclick="loadDoc('note.xml')">Get XML data</button> <script> function loadDoc(url) { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById('A1').innerHTML = this.status; document.getElementById('A2').innerHTML = this.statusText; document.getElementById('A3').innerHTML = this.responseText; } }; xhttp.open("GET", url, true); xhttp.send(); } </script>

Retrieve the content of an XML file

<br>

<html>
<style>
table,th,td {
  border : 1px solid black;
  border-collapse: collapse;
}
th,td {
  padding: 5px;
}
</style>
<body>

The XMLHttpRequest Object

<button type="button" onclick="loadDoc()">Get my CD collection</button> <br><br> <table id="demo"></table> <script> function loadDoc() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myFunction(this); } }; xhttp.open("GET", "cd_catalog.xml", true); xhttp.send(); } function myFunction(xml) { var i; var xmlDoc = xml.responseXML; var table="<tr><th>Artist</th><th>Title</th></tr>"; var x = xmlDoc.getElementsByTagName("CD"); for (i = 0; i <x.length; i++) { table += "<tr><td>" + x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue + "</td><td>" + x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue + "</td></tr>"; } document.getElementById("demo").innerHTML = table; } </script>

Retrieve the content of a PHP file

<br>

The XMLHttpRequest Object

<h3>Start typing a name in the input field below:</h3> <form action=""> First name: <input type="text" id="txt1" onkeyup="showHint(this.value)"> </form> <p>Suggestions: <span id="txtHint"></span></p> <script> function showHint(str) { var xhttp; if (str.length == 0) { document.getElementById("txtHint").innerHTML = ""; return; } xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("txtHint").innerHTML = this.responseText; } }; xhttp.open("GET", "gethint.php?q="+str, true); xhttp.send(); } </script>

Retrieve the content of an ASP file

<br>

The XMLHttpRequest Object

<h3>Start typing a name in the input field below:</h3> <form action=""> First name: <input type="text" id="txt1" onkeyup="showHint(this.value)"> </form> <p>Suggestions: <span id="txtHint"></span></p> <script> function showHint(str) { var xhttp; if (str.length == 0) { document.getElementById("txtHint").innerHTML = ""; return; } xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("txtHint").innerHTML = this.responseText; } }; xhttp.open("GET", "gethint.asp?q="+str, true); xhttp.send(); } </script>

Retrieve content from a database

<br>

<html>
<style>
table,th,td {
  border : 1px solid black;
  border-collapse: collapse;
}
th,td {
  padding: 5px;
}
</style>
<body>

The XMLHttpRequest Object

<form action=""> <select name="customers" onchange="showCustomer(this.value)"> <option value="">Select a customer:</option> <option value="ALFKI">Alfreds Futterkiste</option> <option value="NORTS ">North/South</option> <option value="WOLZA">Wolski Zajazd</option> </select> </form> <br> <div id="txtHint">Customer info will be listed here...</div> <script> function showCustomer(str) { var xhttp; if (str == "") { document.getElementById("txtHint").innerHTML = ""; return; } xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("txtHint").innerHTML = this.responseText; } }; xhttp.open("GET", "getcustomer.asp?q="+str, true); xhttp.send(); } </script>

Display XML data in an HTML table

<br>

<html>
<style>
table,th,td {
  border : 1px solid black;
  border-collapse: collapse;
}
th,td {
  padding: 5px;
}
</style>
<body>

<button type="button" onclick="loadXMLDoc()">Get my CD collection</button>
<br><br>
<table id="demo"></table>

<script>
function loadXMLDoc() {
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      myFunction(this);
    }
  };
  xmlhttp.open("GET", "cd_catalog.xml", true);
  xmlhttp.send();
}
function myFunction(xml) {
  var i;
  var xmlDoc = xml.responseXML;
  var table="<tr><th>Artist</th><th>Title</th></tr>";
  var x = xmlDoc.getElementsByTagName("CD");
  for (i = 0; i <x.length; i++) { 
    table += "<tr><td>" +
    x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue +
    "</td><td>" +
    x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue +
    "</td></tr>";
  }
  document.getElementById("demo").innerHTML = table;
}
</script>


Show XML data inside an HTML div element

<br>

<div id='showCD'></div>

<script>
displayCD(0);

function displayCD(i) {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            myFunction(this, i);
        }
    };
    xmlhttp.open("GET", "cd_catalog.xml", true);
    xmlhttp.send();
}

function myFunction(xml, i) {
    var xmlDoc = xml.responseXML; 
    x = xmlDoc.getElementsByTagName("CD");
    document.getElementById("showCD").innerHTML =
    "Artist: " +
    x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue +
    "<br>Title: " +
    x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue +
    "<br>Year: " + 
    x[i].getElementsByTagName("YEAR")[0].childNodes[0].nodeValue;
}
</script>


Navigate through XML nodes

<br>

<div id='showCD'></div><br>
<input type="button" onclick="previous()" value="<<">
<input type="button" onclick="next()" value=">>">

<script>
var i = 0, len;
displayCD(i);

function displayCD(i) {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            myFunction(this, i);
        }
    };
    xmlhttp.open("GET", "cd_catalog.xml", true);
    xmlhttp.send();
}

function myFunction(xml, i) {
    var xmlDoc = xml.responseXML; 
    x = xmlDoc.getElementsByTagName("CD");
    len = x.length;
    document.getElementById("showCD").innerHTML =
    "Artist: " +
    x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue +
    "<br>Title: " +
    x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue +
    "<br>Year: " + 
    x[i].getElementsByTagName("YEAR")[0].childNodes[0].nodeValue;
}

function next() {
if (i < len-1) {
  i++;
  displayCD(i);
  }
}

function previous() {
if (i > 0) {
  i--;
  displayCD(i);
  }
}
</script>


A simple CD catalog application

<br>

<html>
<style>
table,th,td {
  border : 1px solid black;
  border-collapse: collapse;
}
th,td {
  padding: 5px;
}
</style>
<body>

<p>Click on a CD to display album information.</p>
<p id='showCD'></p>
<table id="demo"></table>

<script>
var x,xmlhttp,xmlDoc
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "cd_catalog.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML; 
x = xmlDoc.getElementsByTagName("CD");
table="<tr><th>Artist</th><th>Title</th></tr>";
for (i = 0; i <x.length; i++) { 
  table += "<tr onclick='displayCD(" + i + ")'><td>";
  table += x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue;
  table += "</td><td>";
  table +=  x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue;
  table += "</td></tr>";
}
document.getElementById("demo").innerHTML = table;

function displayCD(i) {
  document.getElementById("showCD").innerHTML =
  "Artist: " +
  x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue +
  "<br>Title: " +
  x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue +
  "<br>Year: " + 
  x[i].getElementsByTagName("YEAR")[0].childNodes[0].nodeValue;
}
</script>


Convert a JavaScript object into a JSON string, and send it to the server.

<script>

var myObj = { "name":"John", "age":31, "city":"New York" };
var myJSON = JSON.stringify(myObj);
window.location = "demo_json.php?x=" + myJSON;

</script>

Convert a string written in JSON format, into a JavaScript object.

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

<script>

var myJSON = '{ "name":"John", "age":31, "city":"New York" }';
var myObj = JSON.parse(myJSON);
document.getElementById("demo").innerHTML = myObj.name;

</script>

Store and retrieve data from local storage.

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

<script>
var myObj, myJSON, text, obj;

//Storing data:
myObj = { "name":"John", "age":31, "city":"New York" };
myJSON = JSON.stringify(myObj);
localStorage.setItem("testJSON", myJSON);

//Retrieving data:
text = localStorage.getItem("testJSON");
obj = JSON.parse(text);
document.getElementById("demo").innerHTML = obj.name;
</script>

Access a JavaScript object:

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

<script>

var myObj, x;
myObj = { "name":"John", "age":30, "city":"New York" };
x = myObj.name;
document.getElementById("demo").innerHTML = x;

</script>

Access a JavaScript object using the bracket notation:

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

<script>

var myObj, x;
myObj = { "name":"John", "age":30, "city":"New York" };
x = myObj["name"];
document.getElementById("demo").innerHTML = x;

</script>

Modify a JavaScript object:

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

<script>

var myObj, x;
myObj = { "name":"John", "age":30, "city":"New York" };
myObj.name = "Gilbert";
document.getElementById("demo").innerHTML = myObj.name;

</script>

Modify a JavaScript object using the bracket notation:

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

<script>

var myObj, x;
myObj = { "name":"John", "age":30, "city":"New York" };
myObj["name"] = "Gilbert";
document.getElementById("demo").innerHTML = myObj.name;

</script>

How to create a JavaScript object array.

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

<script>
var employees = [
    {
    "firstName":"John",
    "lastName":"Doe"
    }, 
    {
    "firstName":"Anna",
    "lastName":"Smith"
    },
    {
    "firstName":"Peter",
    "lastName":"Jones"
    }
];
document.getElementById("demo").innerHTML =
employees[0].firstName + " " + employees[0].lastName;
</script>

How to create a JavaScript object array.

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

<script>
var employees = [
    {
    "firstName":"John",
    "lastName":"Doe"
    }, 
    {
    "firstName":"Anna",
    "lastName":"Smith"
    },
    {
    "firstName":"Peter",
    "lastName":"Jones"
    }
];
document.getElementById("demo").innerHTML =
employees[0]["firstName"] + " " + employees[0]["lastName"];
</script>

How to create a JavaScript object array.

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

<script>
var employees = [
    {
    "firstName":"John",
    "lastName":"Doe"
    }, 
    {
    "firstName":"Anna",
    "lastName":"Smith"
    },
    {
    "firstName":"Peter",
    "lastName":"Jones"
    }
];

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

How to create a JavaScript object array.

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

<script>
var employees = [
    {
    "firstName":"John",
    "lastName":"Doe"
    }, 
    {
    "firstName":"Anna",
    "lastName":"Smith"
    },
    {
    "firstName":"Peter",
    "lastName":"Jones"
    }
];
employees[0]["firstName"] = "Gilbert";
document.getElementById("demo").innerHTML =
employees[0].firstName + " " + employees[0].lastName;
</script>

Access a JSON object using dot notation:

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

<script>

var myObj, x;
myObj = { "name":"John", "age":30, "car":null };
x = myObj.name;
document.getElementById("demo").innerHTML = x;

</script>

Access a JSON object using bracket notation:

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

<script>

var myObj, x;
myObj = { "name":"John", "age":30, "car":null };
x = myObj["name"];
document.getElementById("demo").innerHTML = x;

</script>

How to loop through all properties in a JSON object.

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

<script>
var myObj = { "name":"John", "age":30, "car":null };
for (x in myObj) {
    document.getElementById("demo").innerHTML += x + "<br>";
}
</script>

Use bracket notation to access the property values.

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

<script>
var myObj = { "name":"John", "age":30, "car":null };
for (x in myObj) {
    document.getElementById("demo").innerHTML += myObj[x] + "<br>";
}
</script>

How to access nested JSON objects.

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

<script>
var myObj = {
  "name":"John",
  "age":30,
  "cars": {
    "car1":"Ford",
    "car2":"BMW",
    "car3":"Fiat"
  }
}
document.getElementById("demo").innerHTML += myObj.cars.car2 + "<br>";
//or:
document.getElementById("demo").innerHTML += myObj.cars["car2"];
</script>

How to modify values in a JSON object.

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

<script>
var myObj, i, x = "";
myObj = {
  "name":"John",
  "age":30,
  "cars": {
    "car1":"Ford",
    "car2":"BMW",
    "car3":"Fiat"
  }
}
myObj.cars.car2 = "Mercedes";

for (i in myObj.cars) {
    x += myObj.cars[i] + "<br>";
}

document.getElementById("demo").innerHTML = x;

</script>

How to modify values in a JSON object using the bracket notation.

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

<script>
var myObj, i, x = "";
myObj = {
  "name":"John",
  "age":30,
  "cars": {
    "car1":"Ford",
    "car2":"BMW",
    "car3":"Fiat"
  }
}
myObj.cars["car2"] = "Mercedes";

for (i in myObj.cars) {
    x += myObj.cars[i] + "<br>";
}

document.getElementById("demo").innerHTML = x;

</script>

How to delete properties of a JSON object.

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

<script>
var myObj, i, x = "";
myObj = {
  "name":"John",
  "age":30,
  "cars": {
    "car1":"Ford",
    "car2":"BMW",
    "car3":"Fiat"
  }
}
delete myObj.cars.car2;

for (i in myObj.cars) {
    x += myObj.cars[i] + "<br>";
}

document.getElementById("demo").innerHTML = x;

</script>

Access an array value of a JSON object.

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

<script>

var myObj, x;
myObj = {
    "name":"John",
    "age":30,
    "cars":[ "Ford", "BMW", "Fiat" ]
};
x = myObj.cars[0];
document.getElementById("demo").innerHTML = x;

</script>

Looping through an array using a for in loop:

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

<script>

var myObj, i, x = "";
myObj = {
    "name":"John",
    "age":30,
    "cars":[ "Ford", "BMW", "Fiat" ]
};

for (i in myObj.cars) {
    x += myObj.cars[i] + "<br>";
}

document.getElementById("demo").innerHTML = x;

</script>

Loopin through an array using a for loop:

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

<script>

var myObj, i, x = "";
myObj = {
    "name":"John",
    "age":30,
    "cars":[ "Ford", "BMW", "Fiat" ]
};

for (i = 0; i < myObj.cars.length; i++) {
    x += myObj.cars[i] + "<br>";
}

document.getElementById("demo").innerHTML = x;

</script>

Looping through arrays inside arrays.

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

<script>

var myObj, i, j, x = "";
myObj = {
    "name":"John",
    "age":30,
    "cars": [
        { "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] },
        { "name":"BMW", "models":[ "320", "X3", "X5" ] },
        { "name":"Fiat", "models":[ "500", "Panda" ] }
    ]
}

for (i in myObj.cars) {
    x += "

" + myObj.cars[i].name + "&l

for (j in myObj.cars[i].models) { x += myObj.cars[i].models[j] + "<br>"; } } document.getElementById("demo").innerHTML = x; </script>

How to modify an array value of a JSON object.

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

<script>

var myObj, i, x = "";
myObj = {
    "name":"John",
    "age":30,
    "cars":[ "Ford", "BMW", "Fiat" ]
};
myObj.cars[1] = "Mercedes";

for (i in myObj.cars) {
    x += myObj.cars[i] + "<br>";
}

document.getElementById("demo").innerHTML = x;

</script>

How to delete properties of an array.

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

<script>
var myObj, i, x = "";
myObj = {
  "name":"John",
  "age":30,
  "cars": ["Ford","BMW","Fiat"]
}
delete myObj.cars[1];

for (i in myObj.cars) {
    x += myObj.cars[i] + "<br>";
}

document.getElementById("demo").innerHTML = x;

</script>

Create Object from JSON String

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

<script>

var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');
document.getElementById("demo").innerHTML = obj.name + ", " + obj.age;

</script>

Use the XMLHttpRequest to get the content of a file.

<p>The content is written in JSON format, and can easily be converted into a JavaScript object.</p>

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

<script>

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var myObj = JSON.parse(this.responseText);
        document.getElementById("demo").innerHTML = myObj.name;
    }
};
xmlhttp.open("GET", "json_demo.txt", true);
xmlhttp.send();

</script>

<p>Tak</pre>e a look at <a href="json_demo.txt" target="_blank">json_demo.txt</a></p>


Content as Array.

<p>Content written as an JSON array will be converted into a JavaScript array.</p>

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

<script>

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var myArr = JSON.parse(this.responseText);
        document.getElementById("demo").innerHTML = myArr[0];
    }
};
xmlhttp.open("GET", "json_demo_array.txt", true);
xmlhttp.send();

</script>

<p>Take a look at <a href="json_demo_array.txt" target="_blank">json_demo_array.txt</a></p>


Convert a string into a date object.

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

<script>

var text = '{ "name":"John", "birth":"1986-12-14", "city":"New York"}';
var obj = JSON.parse(text);
obj.birth = new Date(obj.birth);

document.getElementById("demo").innerHTML = obj.name + ", " + obj.birth; 

</script>

Convert a string into a date object.

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

<script>

var text = '{ "name":"John", "birth":"1986-12-14", "city":"New York"}';
var obj = JSON.parse(text, function (key, value) {
    if (key == "birth") {
        return new Date(value);
    } else {
        return value;
    }});
document.getElementById("demo").innerHTML = obj.name + ", " + obj.birth; 

</script>

Convert a string into a function.

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

<script>

var text = '{ "name":"John", "age":"function() {return 30;}", "city":"New York"}';
var obj = JSON.parse(text);
obj.age = eval("(" + obj.age + ")");

document.getElementById("demo").innerHTML = obj.name + ", " + obj.age(); 

</script>

Create JSON string from a JavaScript object.

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

<script>

var obj = { "name":"John", "age":30, "city":"New York"};
var myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;

</script>

Create JSON string from a JavaScript array.

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

<script>

var arr = [ "John", "Peter", "Sally", "Jane" ];
var myJSON = JSON.stringify(arr);
document.getElementById("demo").innerHTML = myJSON;

</script>

JSON.stringify will convert any date objects into strings.

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

<script>

var obj = { "name":"John", "today":new Date(), "city":"New York"};
var myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;

</script>

JSON.stringify will remove any functions from an object.

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

<script>

var obj = { "name":"John", "age":function () {return 30;}, "city":"New York"};
var myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;

</script>

JSON.stringify will remove any functions from an object.

<p>Convert the functions into strings to keep them in the JSON object.</p>

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

<script>

var obj = { "name":"John", "age":function () {return 30;}, "city":"New York"};
obj.age = obj.age.toString();
var myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;

</script>

Get data as JSON from a PHP file on the server.

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

<script>

var xmlhttp = new XMLHttpRequest();

xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        myObj = JSON.parse(this.responseText);
        document.getElementById("demo").innerHTML = myObj.name;
    }
};
xmlhttp.open("GET", "demo_file.php", true);
xmlhttp.send();

</script>

Get data as JSON from a PHP file, and convert it into a JavaScript array.

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

<script>

var xmlhttp = new XMLHttpRequest();

xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var myObj = JSON.parse(this.responseText);
        document.getElementById("demo").innerHTML = myObj[2];
    }
};
xmlhttp.open("GET", "demo_file_array.php", true);
xmlhttp.send();

</script>

Get data as JSON from a PHP file on the server.

<p>The JSON received from the PHP file:</p>

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

<script>
var obj, dbParam, xmlhttp;
obj = { "table":"customers", "limit":10 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        document.getElementById("demo").innerHTML = this.responseText;
    }
};
xmlhttp.open("GET", "json_demo_db.php?x=" + dbParam, true);
xmlhttp.send();

</script>

Get data as JSON from a PHP file on the server.

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

<script>
var obj, dbParam, xmlhttp, myObj, x, txt = "";
obj = { "table":"customers", "limit":10 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        myObj = JSON.parse(this.responseText);
        for (x in myObj) {
            txt += myObj[x].name + "<br>";
        }
        document.getElementById("demo").innerHTML = txt;
    }
};
xmlhttp.open("GET", "json_demo_db.php?x=" + dbParam, true);
xmlhttp.send();

</script>

<p>Try changing the "table" property from "customers" to "products".</p>

Use the HTTP method POST to send data to the PHP file.

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

<script>
var obj, dbParam, xmlhttp, myObj, x, txt = "";
obj = { "table":"customers", "limit":10 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        myObj = JSON.parse(this.responseText);
        for (x in myObj) {
            txt += myObj[x].name + "<br>";
        }
        document.getElementById("demo").innerHTML = txt;
    }
};
xmlhttp.open("POST", "json_demo_db_post.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);

</script>

<p>Try changing the "table" property from "customers" to "products".</p>

Make a table based on JSON data.

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

<script>
var obj, dbParam, xmlhttp, myObj, x, txt = "";
obj = { "table":"customers", "limit":20 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        myObj = JSON.parse(this.responseText);
        txt += "<table border='1'>"
        for (x in myObj) {
            txt += "<tr><td>" + myObj[x].name + "</td></tr>";
        }
        txt += "</table>"        
        document.getElementById("demo").innerHTML = txt;
    }
};
xmlhttp.open("POST", "json_demo_db_post.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);

</script>

Make a table based on the value of a drop down menu.

<select id="myselect" onchange="change_myselect(this.value)">
<option value="">Choose an option:</option>
<option value="customers">Customers</option>
<option value="products">Products</option>
<option value="suppliers">Suppliers</option>
</select>


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

<script>
function change_myselect(sel) {
  var obj, dbParam, xmlhttp, myObj, x, txt = "";
  obj = { "table":sel, "limit":20 };
  dbParam = JSON.stringify(obj);
  xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      myObj = JSON.parse(this.responseText);
      txt += "<table border='1'>"
      for (x in myObj) {
        txt += "<tr><td>" + myObj[x].name + "</td></tr>";
      }
      txt += "</table>"        
      document.getElementById("demo").innerHTML = txt;
    }
  };
  xmlhttp.open("POST", "json_demo_db_post.php", true);
  xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xmlhttp.send("x=" + dbParam);
}
</script>

Make a drop down list based on JSON data.

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

<script>
var obj, dbParam, xmlhttp, myObj, x, txt = "";
obj = { "table":"customers", "limit":20 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        myObj = JSON.parse(this.responseText);
        txt += "<select>"
        for (x in myObj) {
            txt += "<option>" + myObj[x].name;
        }
        txt += "</select>"
        document.getElementById("demo").innerHTML = txt;
    }
};
xmlhttp.open("POST", "json_demo_db_post.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);

</script>

Request JSON using the script tag

<html>

<body>


<p>The PHP file returns a call to a function that will handle the JSON data.</p>

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

<script>
function myFunc(myObj) {
  document.getElementById("demo").innerHTML = myObj.name;
}
</script>

<scrip</pre>t src="demo_jsonp.php"></script>


Request JSON using the script tag

<html>

<body>

Click the Button.

<p>A script tag with a src attribute is created and placed in the document.</p> <p>The PHP file returns a call to a function with the JSON object as a parameter.</p> <button onclick="clickButton()">Click me!</button> <p id="demo"></p> <script> function clickButton() { var s = document.createElement("script"); s.src = "demo_jsonp.php"; document.body.appendChild(s); } function myFunc(myObj) { document.getElementById("demo").innerHTML = myObj.name; } </script>

Request JSON using the script tag

<html>

<body>

Click the Button.

<p>A script tag with a src attribute is created and placed in the document.</p> <p>The PHP file returns a call to a function with the JSON object as a parameter.</p> <button onclick="clickButton()">Click me!</button> <p id="demo"></p> <p>Try changing the table property from "customers" to "products".</p> <script> function clickButton() { var obj, s obj = { "table":"customers", "limit":10 }; s = document.createElement("script"); s.src = "jsonp_demo_db.php?x=" + JSON.stringify(obj); document.body.appendChild(s); } function myFunc(myObj) { var x, txt = ""; for (x in myObj) { txt += myObj[x].name + "<br>"; } document.getElementById("demo").innerHTML = txt; } </script>

Request JSON using the script tag

<html>

<body>

Request With a Callback Function

<p>The PHP file returns a call to the function you send as a callback.</p> <button onclick="clickButton()">Click me!</button> <p id="demo"></p> <script> function clickButton() { var s = document.createElement("script"); s.src = "demo_jsonp2.php?callback=myDisplayFunction"; document.body.appendChild(s); } function myDisplayFunction(myObj) { document.getElementById("demo").innerHTML = myObj.name; } </script>

What Can JavaScript Do

<p id="demo">JavaScript can change HTML content.</p>

<button type="button" onclick='document.getElementById("demo").innerHTML = "Hello JavaScript!"'>Click </pre>Me!</button>


What Can JavaScript Do

<p>JavaScript can change HTML attributes.</p>

<p>In this case JavaScript changes the src (source) attribute of an image.</p>

<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on the light</button>

<img id="myImage" src="https://www.w3schools.com/js/pic_bulboff.gif" style="width:100px">

<button onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn off the light</button

What Can JavaScript Do

<p id="demo">JavaScript can change the style of an HTML element.</p>

<button type="button" onclick="document.getElementById('demo').style.fontSize='35px'">Click Me!</button>



What Can JavaScript Do

<p id="demo">JavaScript can hide HTML elements.</p>

<button type="button" onclick="document.getElementById('demo').style.display='none'">Click Me!</button>



What Can JavaScript Do

<p>JavaScript can show hidden HTML elements.</p>

<p id="demo" style="display:none">Hello JavaScript!</p>

<button type="button" onclick="document.getElementById('demo').style.display='block'">Click Me!</button


Paragraph changed

<br>

<html>
<head>
<script>
function myFunction() {
    document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>

<body>

JavaScript in Head

<p id="demo">A Paragraph.</p> <butto</pre>n type="button" onclick="myFunction()">Try it</button>

JavaScript in Body

<p id="demo">A Paragraph.</p>

<button type="button" onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>


External JavaScript

<p id="demo">A Paragraph.</p>

<button type="button" onclick="myFunction()">Try it</button>

<p>(myFunction is stored in an external file called "myScript.js")</p>

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

External JavaScript

<p id="demo">A Paragraph.</p>

<button type="button" onclick="myFunction()">Try it</button>

<p>(myFunction is stored in an external file called "myScript.js")</p>

<script src="https://www.w3schools.com/js/myScript.js"></script>

External JavaScript

<p id="demo">A Paragraph.</p>

<button type="button" onclick="myFunction()">Try it</button>

<p>(myFunction is stored in an external file called "myScript.js")</p>

<scrip</pre>t src="/js/myScript.js"></script>


document.write

<br>

My First Web Page

<p>My first paragraph.</p> <script> document.write(5 + 6); </script>

document.getElementById

<br>

My First Web Page

<p>My First Paragraph.</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = 5 + 6; </script>

window.alert

<br>

My First Web Page

<p>My first paragraph.</p> <script> window.alert(5 + 6); </script>

Activate debugging with F12

<p>Select "Console" in the debugger menu. Then click Run again.</p>

<script>
console.log(5 + 6);
</script>

JavaScript Statements

<p>A <b>JavaScript program</b> is a list of <b>statements</b> to be executed by a computer.</p>

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

<script>

var x, y, z;  // Declare 3 variables
x = 5;        // Assign the value 5 to x
y = 6;        // Assign the value 6 to y
z = x + y;    // Assign the sum of x and y to z

document.getElementById("demo").innerHTML =
"The value of z is " + z + ".";

</script>

JavaScript Numbers

<p>Number can be written with or without decimals.</p>

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

<script>
document.getElementById("demo").innerHTML = 10.50;
</script>

JavaScript Strings

<p>Strings can be written with double or single quotes.</p>

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

<script>
document.getElementById("demo").innerHTML = 'John Doe';
</script>

JavaScript Variables

<p>In this example, x is defined as a variable.
Then, x is assigned the value of 6:</p>

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

<script>
var x;
x = 6;
document.getElementById("demo").innerHTML = x;
</script>

JavaScript Operators

<p>JavaScript uses arithmetic operators to compute values (just like algebra).</p>

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

<script>
document.getElementById("demo").innerHTML = (5 + 6) * 10;
</script>

Assigning JavaScript Values

<p>In JavaScript the = operator is used to assign values to variables.</p>

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

<script>
var x, y;
x = 5;
y = 6;
document.getElementById("demo").innerHTML = x + y;
</script>

JavaScript Expressions

<p>Expressions compute to values.</p>

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

<script>
document.getElementById("demo").innerHTML = 5 * 10;
</script>

JavaScript Expressions

<p>Expressions compute to values.</p>

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

<script>
document.getElementById("demo").innerHTML = "John" + " "  + "Doe";
</script>

JavaScript Expressions

<p>Expressions compute to values.</p>

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

<script>
var x;
x = 5;
document.getElementById("demo").innerHTML = x * 10;
</script>

The var Keyword Creates Variables

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

<script>
var x, y;
x = 5 + 6;
y = x * 10;
document.getElementById("demo").innerHTML = y;
</script>

JavaScript Comments are NOT Executed

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

<script>
var x;
x = 5;
// x = 6; I will not be executed
document.getElementById("demo").innerHTML = x;
</script>

JavaScript is Case Sensitive

<p>Try change lastName to lastname.</p>

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

<script>
var lastname, lastName;
lastName = "Doe";
lastname = "Peterson";
document.getElementById("demo").innerHTML = lastName;
</script>

JavaScript Statements

<p>In HTML, JavaScript statements are executed by the browser.</p>

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

<script>
document.getElementById("demo").innerHTML = "Hello Dolly.";
</script>

JavaScript Statements

<p>A <b>JavaScript program</b> is a list of <b>statements</b> to be executed by a computer.</p>

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

<script>

var x, y, z;  // Statement 1
x = 5;        // Statement 2
y = 6;        // Statement 3
z = x + y;    // Statement 4

document.getElementById("demo").innerHTML =
"The value of z is " + z + ".";  

</script>

JavaScript Statements

<p>JavaScript statements are separated by semicolons.</p>

<p id="demo1"></p>

<script>
var a, b, c;
a = 1;
b = 2;
c = a + b;
document.getElementById("demo1").innerHTML = c;
</script>

JavaScript Statements

<p>Multiple statements on one line is allowed.</p>

<p id="demo1"></p>

<script>
var a, b, c;
a = 1; b = 2; c = a + b;
document.getElementById("demo1").innerHTML = c;
</script>

JavaScript Statements

<p>JavaScript code blocks are written between { and }</p>

<button type="button" onclick="myFunction()">Click Me!</button>

<p id="demo1"></p>
<p id="demo2"></p>

<script>
function myFunction() {
    document.getElementById("demo1").innerHTML = "Hello Dolly!";
    document.getElementById("demo2").innerHTML = "How are you?";
}
</script>

JavaScript Statements

<p>
The best place to break a code line is after an operator or a comma.
</p>

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

<script>
document.getElementById("demo").innerHTML =
"Hello Dolly!";
</script>

<br>

<h1 id="myH"></h1>
<p id="myP"></p>

<script>
// Change heading:
document.getElementById("myH").innerHTML = "My First Page";
// Change paragraph:
document.getElementById("myP").innerHTML = "My first paragraph.";
</script>

<p><st</pre>rong>Note:</strong> The comments are not executed.</p>


<br>

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

<script>
var x = 5;      // Declare x, give it the value of 5
var y = x + 2;  // Declare y, give it the value of x + 2 

document.getElementById("demo").innerHTML = y; // Write y to demo
</script>

<p><st</pre>rong>Note:</strong> The comments are not executed.</p>


<br>

<h1 id="myH"></h1>
<p id="myP"></p>

<script>
/*
The code below will change
the heading with id = "myH"
and the paragraph with id = "myp"
in my web page:
*/
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
</script>

<p><st</pre>rong>Note:</strong> The comment block is not executed.</p>


<br>

<h1 id="myH"></h1>

<p id="myP"></p>

<script>
//document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
</script>

<p><st</pre>rong>Note:</strong> The comment is not executed.</p>


<br>

<h1 id="myH"></h1>

<p id="myP"></p>

<script>
/*
document.getElementById("myH").innerHTML = "Welcome to my Homepage";
document.getElementById("myP").innerHTML = "This is my first paragraph.";
*/
</script>

<p><strong>Note:</strong> The comment-block is not executed.</p>


JavaScript Variables

<p>In this example, x, y, and z are variables.</p>

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

<script>
var x = 5;
var y = 6;
var z = x + y;
document.getElementById("demo").innerHTML =
"The value of z is: " + z;
</script>

</body>
</html>

JavaScript Variables

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

<script>
var price1 = 5;
var price2 = 6;
var total = price1 + price2;
document.getElementById("demo").innerHTML =
"The total is: " + total;
</script>

</body>
</html>

JavaScript Variables

<p>Strings are written with quotes.</p>
<p>Numbers are written without quotes.</p>

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

<script>
var pi = 3.14;
var person = "John Doe";
var answer = 'Yes I am!';

document.getElementById("demo").innerHTML =
pi + "<br>" + person + "<br>" + answer;
</script>

</body>
</html>

JavaScript Variables

<p>Create a variable, assign a value to it, and display it:</p>

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

<script>
var carName = "Volvo";
document.getElementById("demo").innerHTML = carName;
</script>

JavaScript Variables

<p>You can declare many variables in one statement.</p>

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

<script>
var person = "John Doe", carName = "Volvo", price = 200;
document.getElementById("demo").innerHTML = carName;
</script>

</body>
</html>

JavaScript Variables

<p>You can declare many variables in one statement.</p>

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

<script>
var person = "John Doe",
carName = "Volvo",
price = 200;
document.getElementById("demo").innerHTML = carName;
</script>

</body>
</html>

JavaScript Variables

<p>A variable declared without a value will have the value undefined.</p>

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

<script>
var carName;
document.getElementById("demo").innerHTML = carName;
</script>

</body>
</html>

JavaScript Variables

<p>If you re-declare a JavaScript variable, it will not lose its value.</p>

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

<script>
var carName = "Volvo";
var carName;
document.getElementById("demo").innerHTML = carName;
</script>

</body>
</html>

JavaScript Variables

<p>The result of adding 5 + 2 + 3:</p>

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

<script>
var x = 5 + 2 + 3;
document.getElementById("demo").innerHTML = x;
</script>

JavaScript Variables

<p>The result of adding "John" + " " + "Doe":</p>

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

<script>
var x = "John" + " " + "Doe";
document.getElementById("demo").innerHTML = x;
</script>

JavaScript Variables

<p>The result of adding "5" + 2 + 3:</p>

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

<script>
x = "5" + 2 + 3;
document.getElementById("demo").innerHTML = x;
</script>

The + Operator

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

<script>
var x = 5;
var y = 2;
var z = x + y;
document.getElementById("demo").innerHTML = z;
</script>

The - Operator

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

<script>
var x = 5;
var y = 2;
var z = x - y;
document.getElementById("demo").innerHTML = z
</script>

The * Operator

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

<script>
var x = 5;
var y = 2;
var z = x * y;
document.getElementById("demo").innerHTML = z;
</script>

The / Operator

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

<script>
var x = 5;
var y = 2;
var z = x / y;
document.getElementById("demo").innerHTML = z;
</script>

The % Operator

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

<script>
var x = 5;
var y = 2;
var z = x % y;
document.getElementById("demo").innerHTML = z;
</script>

JavaScript Operators

<p>In this example, y is incremented before it is assigned to x (pre-incremented).</p>

<p id="demo1"></p>
<p id="demo2"></p>

<script>
var y = 5;
var x = ++y;
document.getElementById("demo1").innerHTML = y;
document.getElementById("demo2").innerHTML = x;
</script>

JavaScript Operators

<p>In this example, y is decremented before it is assigned to x (pre-decremented).</p>

<p id="demo1"></p>
<p id="demo2"></p>

<script>
var y = 5;
var x = --y;
document.getElementById("demo1").innerHTML = y;
document.getElementById("demo2").innerHTML = x;
</script>

The = Operator

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

<script>
var x = 10;
document.getElementById("demo").innerHTML = x;
</script>

The += Operator

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

<script>
var x = 10;
x += 5;
document.getElementById("demo").innerHTML = x;
</script>

The -= Operator

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

<script>
var x = 10;
x -= 5;
document.getElementById("demo").innerHTML = x;
</script>

The *= Operator

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

<script>
var x = 10;
x *= 5;
document.getElementById("demo").innerHTML = x;
</script>

The /= Operator

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

<script>
var x = 10;
x /= 5;
document.getElementById("demo").innerHTML = x;
</script>

The %= Operator

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

<script>
var x = 10;
x %= 5;
document.getElementById("demo").innerHTML = x;
</script>

JavaScript Operators

<p>The + operator concatenates (adds) strings.</p>

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

<script>
var txt1 = "What a very";
var txt2 = "nice day";
document.getElementById("demo").innerHTML = txt1 + txt2;
</script>

JavaScript Operators

<p>The + operator concatenates (adds) strings.</p>

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

<script>
var txt1 = "What a very ";
var txt2 = "nice day";
document.getElementById("demo").innerHTML = txt1 + txt2;
</script>

JavaScript Operators

<p>The + operator concatenates (adds) strings.</p>

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

<script>
var txt1 = "What a very";
var txt2 = "nice day";
document.getElementById("demo").innerHTML = txt1 + " " + txt2;
</script>

JavaScript Operators

<p>The assignment operator += can concatenate strings.</p>

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

<script>
txt1 = "What a very ";
txt1 += "nice day";
document.getElementById("demo").innerHTML = txt1;
</script>

JavaScript Operators

<p>Adding a number and a string, returns a string.</p>

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

<script>
var x = 5 + 5;
var y = "5" + 5;
var z = "Hello" + 5;
document.getElementById("demo").innerHTML =
x + "<br>" + y + "<br>" + z;
</script>

JavaScript Strings

<p>You can use quotes inside a string, as long as they don't match the quotes surrounding the string:</p>

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

<script>
var answer1 = "It's alright";
var answer2 = "He is called 'Johnny'";
var answer3 = 'He is called "Johnny"';

document.getElementById("demo").innerHTML =
answer1 + "<br>" + 
answer2 + "<br>" + 
answer3;
</script>

</body>
</html>

JavaScript Numbers

<p>Numbers can be written with, or without decimals:</p>

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

<script>
var x1 = 34.00;
var x2 = 34;
var x3 = 3.14;

document.getElementById("demo").innerHTML =
x1 + "<br>" + x2 + "<br>" + x3;
</script>

</body>
</html>

JavaScript Arrays

<p>Array indexes are zero-based, which means the first item is [0].</p>

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

<script>
var cars = ["Saab","Volvo","BMW"];

document.getElementById("demo").innerHTML = cars[0];
</script>

</body>
</html>

JavaScript Objects

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

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

document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>

<br>

<p>The typeof operator returns the type of a variable or an expression.</p>

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

<script>
document.getElementById("demo").innerHTML = 
typeof "" + "<br>" +
typeof "John" + "<br>" + 
typeof "John Doe" + "<br>" +
typeof 0 + "<br>" +
typeof 314 + "<br>" +
typeof 3.14 + "<br>" +
typeof (3.14);
</script>
</body>
</html>



JavaScript

<p>JavaScript evaluates expressions from left to right. Different sequences can produce different results:</p>

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

<script>
var x = 16 + 4 + "Volvo";
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

JavaScript

<p>JavaScript evaluates expressions from left to right. Different sequences can produce different results:</p>

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

<script>
var x = "Volvo" + 16 + 4;
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

JavaScript

<p>The value (and the data type) of a variable with no value is <b>undefined</b>.</p>

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

<script>
var car;
document.getElementById("demo").innerHTML =
car + "<br>" + typeof car;
</script>

JavaScript

<p>An empty string has both a legal value and a type:</p>

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

<script>
var car = "";
document.getElementById("demo").innerHTML =
"The value is: " +
car + "<br>" +
"The type is: " + typeof car;
</script>

</body>
</html>

<br>

<p>Creating a JavaScript Variable.</p>

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

<script>
var car = "Fiat";
document.getElementById("demo").innerHTML = car;
</script>


<br>

<p>Creating a JavaScript Object.</p>

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

<script>
var car = {type:"Fiat", model:"500", color:"white"};
document.getElementById("demo").innerHTML = car.type;
</script>


<br>

<p>Creating a JavaScript Object.</p>

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

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

document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>


<br>

<p>Creating a JavaScript Object.</p>

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

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

document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>


<br>

<p>
There are two different ways to access an object property: 
</p>
<p>You can use person.property or person["property"].</p>

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

<script>
var person = {
    firstName: "John",
    lastName : "Doe",
    id       :  5566
};
document.getElementById("demo").innerHTML =
person.firstName + " " + person.lastName;
</script>

</body>
</html>



<br>

<p>
There are two different ways to access an object property: 
</p>
<p>You can use person.property or person["property"].</p>

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

<script>
var person = {
    firstName: "John",
    lastName : "Doe",
    id       :  5566
};
document.getElementById("demo").innerHTML =
person["firstName"] + " " + person["lastName"];
</script>

</body>
</html>



<br>

<p>Creating and using an object method.</p>

<p>An object method is a function definition, stored as a property value.</p>

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

<script>
var person = {
    firstName: "John",
    lastName : "Doe",
    id       : 5566,
    fullName : function() {
       return this.firstName + " " + this.lastName;
    }
};

document.getElementById("demo").innerHTML = person.fullName();
</pre></script>

JavaScript Object Methods

<p>If you access an object method without (), it will return the function definition:</p>

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

<script>
var person = {
    firstName: "John",
    lastName : "Doe",
    id       : 5566,
    fullName : function() {
       return this.firstName + " " + this.lastName;
    }
};

docume</pre>nt.getElementById("demo").innerHTML = person.fullName;
</script>

A simple function

<br>

<html>
<head>
<script>
function myFunction() {
    document.getElementById("demo").innerHTML = "Hello World!";
}
</script>
</head>

<body>

<p>When you click "Try it", a function will be called.</p>
<p>The function will display a message.</p>

<button onclick="myFunction()">Try it</button>

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


A function with an argument

<br>

<p>Click "Try it" to call a function with arguments</p>

<button onclick="myFunction('Harry Potter','Wizard')">Try it</button>

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

<script>
function myFunction(name,job) {
    document.getElementById("demo").innerHTML =
    "Welcome " + name + ", the " + job + ".";
}
</script>

A function with an argument 2

<br>

<html>>
<head>>
<script>>
function myfunction(txt) { 
    document.getElementById("demo").innerHTML = txt
} 
</script>>
</head>>

<body>>
<p>
When you click on one of the buttons, a function will be called. The function will display the argument that is passed to it.
</p>

<form> 
<input type="button" onclick="myfunction('Good Morning!')" value="In the Morning"> 
<input type="button" onclick="myfunction('Good Evening!')" value="In the Evening"> 
</form> 

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

</body> 
</html</pre> 


A function that returns a value

<br>

JavaScript Functions

<p>This example calls a function which performs a calculation and returns the result:</p> <p id="demo"></p> <script> var x = myFunction(4, 3); document.getElementById("demo").innerHTML = x; function myFunction(a, b) { return a * b; } </script>

A function that converts Fahrenheit to Celsius

<br>

JavaScript Functions

<p>This example calls a function to convert from Fahrenheit to Celsius:</p> <p id="demo"></p> <script> function toCelsius(f) { return (5/9) * (f-32); } document.getElementById("demo").innerHTML = toCelsius(77); </script>

A function call without ()

<br>

JavaScript Functions

<p>Accessing a function without () will return the function definition instead of the function result:</p> <p id="demo"></p> <script> function toCelsius(f) { return (5/9) * (f-32); } document.getElementById("demo").innerHTML = toCelsius; </script>

An onclick event changes an HTML element

<br>

<button onclick="document.getElementById('demo').innerHTML=Date()">The time is?</button>

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


An onclick event changes its own element

<br>

<butto</pre>n onclick="this.innerHTML=Date()">The time is?</button>


An onclick event calls a function

<br>

<p>Click the button to display the date.</p>

<button onclick="displayDate()">The time is?</button>

<script>
function displayDate() {
    document.getElementById("demo").innerHTML = Date();
}
</script>

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


JavaScript Strings

<p>Strings are written inside quotes.</p>
<p>You can use single or double quotes:</p>

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

<script>

var carName1 = "Volvo XC60";
var carName2 = 'Volvo XC60';

document.getElementById("demo").innerHTML =
carName1 + " " + carName2; 

</script>

</body>
</html>

Show some string examples

<br>

JavaScript Strings

<p>You can use quotes inside a string, as long as they don't match the quotes surrounding the string:</p> <p id="demo"></p> <script> var answer1 = "It's alright"; var answer2 = "He is called 'Johnny'"; var answer3 = 'He is called "Johnny"'; document.getElementById("demo").innerHTML = answer1 + "<br>" + answer2 + "<br>" + answer3; </script> </body> </html>

<br>

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

<script>

var x = 'It\'s alright';
var y = "We are the so-called \"Vikings\" from the north.";

document.getElementById("demo").innerHTML = x + "<br>" + y; 

</script>

</body>
</html>



Find the length of a string

<br>

JavaScript String Properties

<p>The length property returns the length of a string:</p> <p id="demo"></p> <script> var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; document.getElementById("demo").innerHTML = txt.length; </script> </body> </html>

JavaScript Strings

<p>
You can break a code line within a text string with a backslash.
</p>

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

<script>
document.getElementById("demo").innerHTML = "Hello \
Dolly!";
</script>

JavaScript Statements

<p id="demo">You cannot break a code line with a \ backslash.</p>

<script>
document.getElementById("demo").innerHTML = \
"Hello Dolly.";
</script>

Find the position of the first occurrence of a text

<br>

JavaScript String Methods

<p>The indexOf() method returns the position of the first occurrence of a specified text:</p> <p id="demo"></p> <script> var str = "Please locate where 'locate' occurs!"; var pos = str.indexOf("locate"); document.getElementById("demo").innerHTML = pos; </script> </body> </html

Search for a text in a string and return the text if found

<br>

<p>Click the button to perfom a global (/g) search for the letters "ain" (/ain) in a string, and display the matches.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var str = "The rain in SPAIN stays mainly in the plain"; 
    var res = str.match(/ain/g);
    document.getElementById("demo").innerHTML = res;
}
</script>

</body>
</html


Replace characters in a string - replace()

<br>

JavaScript String Methods

<p>Replace "Microsoft" with "W3Schools" in the paragraph below:</p> <button onclick="myFunction()">Try it</button> <p id="demo">Please visit Microsoft!</p> <script> function myFunction() { var str = document.getElementById("demo").innerHTML; var txt = str.replace("Microsoft","W3Schools"); document.getElementById("demo").innerHTML = txt; } </script> </body> </html>

Convert string to upper case - toUpperCase()

<br>

<p>Convert string to upper case:</p>

<button onclick="myFunction()">Try it</button>

<p id="demo">Hello World!</p>

<script>
function myFunction() {
    var text = document.getElementById("demo").innerHTML;
    document.getElementById("demo").innerHTML = text.toUpperCase();
}
</script>

</body>
</html


Convert string to lower case - toLowerCase()

<br>

<p>Convert string to lower case:</p>

<button onclick="myFunction()">Try it</button>

<p id="demo">Hello World!</p>

<script>
function myFunction() {
    var text = document.getElementById("demo").innerHTML;
    document.getElementById("demo").innerHTML = text.toLowerCase();
}
</script>

</body>
</html>



Split a string into an array - split()

<br>

<p>Click "Try it" to display the first array element, after a string split.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var str = "a,b,c,d,e,f";
    var arr = str.split(",");
    document.getElementById("demo").innerHTML = arr[0];
}
</script>

</body>
</html>



Numbers can be written with or without decimals

<br>

JavaScript Numbers

<p>Numbers can be written with or without decimals:</p> <p id="demo"></p> <script> var x = 3.14; var y = 3; document.getElementById("demo").innerHTML = x + "<br>" + y; </script>

Extra large or extra small numbers can be written with exponent notation

<br>

JavaScript Numbers

<p>Extra large or extra small numbers can be written with scientific (exponent) notation:</p> <p id="demo"></p> <script> var x = 123e5; var y = 123e-5; document.getElementById("demo").innerHTML = x + "<br>" + y; </script>

Number are considered accurate only up to 15 digits

<br>

JavaScript Numbers

<p>Integers (numbers without a period or exponent notation) are accurate up to 15 digits:</p> <p id="demo"></p> <script> var x = 999999999999999; var y = 9999999999999999; document.getElementById("demo").innerHTML = x + "<br>" + y; </script> </body> </html>

Floating point arithmetic is not always 100% accurate

<br>

JavaScript Numbers

<p>Floating point arithmetic is not always 100% accurate.</p> <p id="demo"></p> <script> var x = 0.2 + 0.1; document.getElementById("demo").innerHTML = "0.2 + 0.1 = " + x; </script> </body> </html>

But it helps to multiply and divide by 10

<br>

JavaScript Numbers

<p>Floating point arithmetic is not always 100% accurate:</p> <p id="demo1"></p> <p>But it helps to multiply and divide:</p> <p id="demo2"></p> <script> var x = 0.2 + 0.1; document.getElementById("demo1").innerHTML = "0.2 + 0.1 = " + x; var y = (0.2*10 + 0.1*10) / 10; document.getElementById("demo2").innerHTML = "0.2 + 0.1 = " + y; </script> </body> </html>

Constants, preceded by 0x, are interpreted as hexadecimal

<br>

JavaScript Numbers

<p>Numeric constants, preceded by 0x, are interpreted as hexadecimal:</p> <p id="demo"></p> <script> var x = 0xFF; document.getElementById("demo").innerHTML = "0xFF = " + x; </script> </body> </html>

A number divided by a string is not a number

<br>

JavaScript Numbers

<p>A number divided by a non-numeric string becomes NaN (Not a Number):</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = 100 / "Apple"; </script>

JavaScript will generate Infinity if you calculate a too large number

<br>

JavaScript Numbers

<p>Infinity is returned if you calculate a number outside the largest possible number:</p> <p id="demo"></p> <script> var myNumber = 2; var txt = ""; while (myNumber != Infinity) { myNumber = myNumber * myNumber; txt = txt + myNumber + "<br>"; } document.getElementById("demo").innerHTML = txt; </script> </body> </html>

Division by zero generates Infinity

<br>

JavaScript Numbers

<p>Division by zero generates Infinity;</p> <p id="demo"></p> <script> var x = 2/0; var y = -2/0; document.getElementById("demo").innerHTML = x + "<br>" + y; </script> </body> </html>

The toString() method can output numbers as hex, octal, and binary

<br>

JavaScript Numbers

<p>The toString() method can output numbers as base 16 (hex), base 8 (octal), or base 2 (binary).</p> <p id="demo"></p> <script> var myNumber = 128; document.getElementById("demo").innerHTML = "128 = " + myNumber + " Decimal, " + myNumber.toString(16) + " Hexadecimal, " + myNumber.toString(8) + " Octal, " + myNumber.toString(2) + " Binary." </script>

JavaScript Math.PI

<p>Math.PI returns the ratio of a circle's circumference to its diameter:</p>

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

<script>
document.getElementById("demo").innerHTML = Math.PI;
</script>

JavaScript Math.round()

<p>Math.round(x) returns the value of x rounded to its nearest integer:</p>

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

<script>
document.getElementById("demo").innerHTML = Math.round(4.4);
</script>

JavaScript Math.pow()

<p>Math.pow(x,y) returns the value of x to the power of y:</p>

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

<script>
document.getElementById("demo").innerHTML = Math.pow(8,2);
</script>

JavaScript Math.sqrt()

<p>Math.sqrt(x) returns the square root of x:</p>

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

<script>
document.getElementById("demo").innerHTML = Math.sqrt(64);
</script>

JavaScript Math.abs()

<p>Math.abs(x) returns the absolute (positive) value of x:</p>


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

<script>
document.getElementById("demo").innerHTML = Math.abs(-4.4);
</script>

JavaScript Math.ceil()

<p>Math.ceil() rounds a number <strong>up</strong> to its nearest integer:</p>


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

<script>
document.getElementById("demo").innerHTML = Math.ceil(4.4);
</script>

JavaScript Math.floor()

<p>Math.floor(x) returns the value of x rounded <strong>down</strong> to its nearest integer:</p>

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

<script>
document.getElementById("demo").innerHTML = Math.floor(4.7);
</script>

JavaScript Math.sin()

<p>Math.sin(x) returns the sin of x (given in radians):</p>
<p>Angle in radians = (angle in degrees) * PI / 180.</p>

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

<script>
document.getElementById("demo").innerHTML = 
"The sine value of 90 degrees is " + Math.sin(90 * Math.PI / 180);
</script>

JavaScript Math.cos()

<p>Math.cos(x) returns the cosin of x (given in radians):</p>
<p>Angle in radians = (angle in degrees) * PI / 180.</p>

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

<script>
document.getElementById("demo").innerHTML = 
"The cosine value of 0 degrees is " + Math.cos(0 * Math.PI / 180);
</script>

JavaScript Math.max()

<p>Math.max() returns the highest value in a list of arguments.</p>

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

<script>
document.getElementById("demo").innerHTML =
Math.max(0, 150, 30, 20, -8, -200);
</script>

JavaScript Math.min()

<p>Math.min() returns the lowest value in a list of arguments:</p>

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

<script>
document.getElementById("demo").innerHTML =
Math.min(0, 150, 30, 20, -8, -200);
</script>

JavaScript Celcius to Fahrenhet

<p>Insert a number into one of the input fields below:</p>

<p><input id="c" onkeyup="convert('C')"> degrees Celsius</p>

<p><input id="f" onkeyup="convert('F')"> degrees Fahrenheit</p> 

<p>Note that the <b>Math.round()</b> method is used, so that the result will be returned as an integer.</p>

<script>
function convert(degree) {
    var x;
    if (degree == "C") {
        x = document.getElementById("c").value * 9 / 5 + 32;
        document.getElementById("f").value = Math.round(x);
    } else {
        x = (document.getElementById("f").value -32) * 5 / 9;
        document.getElementById("c").value = Math.round(x);
    }
}
</script>

JavaScript Math.random()

<p>Math.random() returns a random number between 0 (included) and 1 (excluded):</p>

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

<script>
document.getElementById("demo").innerHTML = Math.random();
</script>

JavaScript Math

<p>Math.floor(Math.random() * 10) returns a random integer between 0 and 9 (both included).</p>

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

<script>
document.getElementById("demo").innerHTML =
Math.floor(Math.random() * 10);
</script>

JavaScript Math

<p>Math.floor(Math.random() * 11) returns a random integer between 0 and 10 (both included).</p>

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

<script>
document.getElementById("demo").innerHTML =
Math.floor(Math.random() * 11);
</script>

JavaScript Math

<p>Math.floor(Math.random() * 100)) returns a random integer between 0 and 99 (both included).</p>

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

<script>
document.getElementById("demo").innerHTML =
Math.floor(Math.random() * 100);
</script>

JavaScript Math

<p>Math.floor() used with Math.random() * 101 returns a random integer between 0 and 100.</p>

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

<script>
document.getElementById("demo").innerHTML =
Math.floor(Math.random() * 101);
</script>

JavaScript Math

<p>Math.floor(Math.random() * 10) + 1) returns a random integer between 1 and 10 (both included).</p>

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

<script>
document.getElementById("demo").innerHTML =
Math.floor(Math.random() * 10) + 1;
</script>

JavaScript Math

<p>Math.floor(Math.random() * 100) + 1) returns a random integer between 1 and 100 (both included).</p>

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

<script>
document.getElementById("demo").innerHTML =
Math.floor(Math.random() * 100) + 1;
</script>

JavaScript Math.random()

<p>Every time you click the button, getRndInteger(min, max) returns a random number between 0 (included) and 10 (excluded):</p>

<button onclick="document.getElementById('demo').innerHTML = getRndInteger(0,10)">Click Me</button>

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

<script>
function getRndInteger(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
}
</script>

JavaScript Math.random()

<p>Every time you click the button, getRndInteger(min, max) returns a random number between 1 and 10 (both included):</p>

<button onclick="document.getElementById('demo').innerHTML = getRndInteger(1,10)">Click Me</button>

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

<script>
function getRndInteger(min, max) {
    return Math.floor(Math.random() * (max - min + 1) ) + min;
}
</script>

Use Date() to display today's date and time

<br>

JavaScript new Date()

<p id="demo"></p> <script> var d = new Date(); document.getElementById("demo").innerHTML = d; </script>

Use getFullYear() display the year

<br>

JavaScript getFullYear()

<p>The getFullYear() method returns the full year of a date:</p> <p id="demo"></p> <script> var d = new Date(); document.getElementById("demo").innerHTML = d.getFullYear(); </script>

Use getTime() to calculate the number of milliseconds since 1970

<br>

JavaScript getTime()

<p>The internal clock in JavaScript counts from midnight January 1, 1970.</p> <p>The getTime() function returns the number of milliseconds since then:</p> <p id="demo"></p> <script> var d = new Date(); document.getElementById("demo").innerHTML = d.getTime(); </script>

Use setFullYear() to set a specific date

<br>

JavaScript setFullYear()

<p>The setFullYear() method sets the year of a date object:</p> <p id="demo"></p> <script> var d = new Date(); d.setFullYear(2020); document.getElementById("demo").innerHTML = d; </script>

Use toUTCString() to convert today's date (according to UTC) to a string

<br>

JavaScript Date()

<p>The toUTCString() method converts a date to a UTC string (a date display standard):</p> <p id="demo"></p> <script> var d = new Date(); document.getElementById("demo").innerHTML = d.toUTCString(); </script>

Use getDay() to display the weekday as a number

<br>

JavaScript getDay()

<p>The getDay() method returns the weekday as a number:</p> <p id="demo"></p> <script> var d = new Date(); document.getElementById("demo").innerHTML = d.getDay(); </script>

Use getDay() and an array to display the weekday as a name

<br>

JavaScript getDay()

<p>The getDay() method returns the weekday as a number:</p> <p>You can use an array to display the name of the weekday:</p> <p id="demo"></p> <script> var d = new Date(); var days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]; document.getElementById("demo").innerHTML = days[d.getDay()]; </script>

Display a clock

<br>

<html>
<head>
<script>
function startTime() {
    var today = new Date();
    var h = today.getHours();
    var m = today.getMinutes();
    var s = today.getSeconds();
    m = checkTime(m);
    s = checkTime(s);
    document.getElementById('txt').innerHTML =
    h + ":" + m + ":" + s;
    var t = setTimeout(startTime, 500);
}
function checkTime(i) {
    if (i < 10) {i = "0" + i};  // add zero in front of numbers < 10
    return i;
}
</script>
</head>

<body onload="startTime()">

<div i</pre>d="txt"></div>


Create an array

<br>

JavaScript Arrays

<p id="demo"></p> <script> var cars = ["Saab", "Volvo", "BMW"]; document.getElementById("demo").innerHTML = cars; </script> </body> </html

Join two arrays - concat()

<br>

JavaScript Array Methods

concat()

<p>The concat() method is used to merge (concatenate) arrays:</p> <p id="demo"></p> <script> var myGirls = ["Cecilie", "Lone"]; var myBoys = ["Emil", "Tobias", "Linus"]; var myChildren = myGirls.concat(myBoys); document.getElementById("demo").innerHTML = myChildren; </script>

Join three arrays - concat()

<br>

JavaScript Array Methods

concat()

<p>The concat() method is used to merge (concatenate) arrays:</p> <p id="demo"></p> <script> var arr1 = ["Cecilie", "Lone"]; var arr2 = ["Emil", "Tobias", "Linus"]; var arr3 = ["Robin", "Morgan"]; var myChildren = arr1.concat(arr2, arr3); document.getElementById("demo").innerHTML = myChildren; </script>

Join all elements of an array into a string - join()

<br>

JavaScript Array Methods&

join()

<p>The join() method joins array elements into a string.</p> <p>It this example we have used " * " as a separator between the elements:</p> <p id="demo"></p> <script> var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo").innerHTML = fruits.join(" * "); </script>

Remove the last element of an array - pop()

<br>

JavaScript Array Methods

pop()

<p>The pop() method removes the last element from an array.</p> <p id="demo1"></p> <p id="demo2"></p> <script> var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo1").innerHTML = fruits; fruits.pop(); document.getElementById("demo2").innerHTML = fruits; </script>

Add new elements to the end of an array - push()

<br>

JavaScript Array Methods&

push()

<p>The push() method appends a new element to an array.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo").innerHTML = fruits; function myFunction() { fruits.push("Kiwi"); document.getElementById("demo").innerHTML = fruits; } </script>

Reverse the order of the elements in an array - reverse()

<br>

<p>The sort() method sorts an array alphabetically.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;

function myFunction() {
    fruits.sort();
    fruits.reverse();
    document.getElementById("demo").innerHTML = fruits;
}
</script>


Remove the first element of an array - shift()

<br>

JavaScript Array Methods&

shift()

<p>The shift() method removes the first element of an array (and "shifts" all other elements to the left):</p> <p id="demo1"></p> <p id="demo2"></p> <script> var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo1").innerHTML = fruits; fruits.shift(); document.getElementById("demo2").innerHTML = fruits; </script>

Select elements from an array - slice()

<br>

JavaScript Array Methods&

slice()

<p>When the slice() method is given two arguments, it selects array elements from the start argument, and up to (but not included) the end argument:</p> <p id="demo"></p> <script> var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"]; var citrus = fruits.slice(1,3); document.getElementById("demo").innerHTML = fruits + "<br><br>" + citrus; </script>

Sort an array (alphabetically and ascending) - sort()

<br>

JavaScript Array Sort

<p>The sort() method sorts an array alphabetically.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo").innerHTML = fruits; function myFunction() { fruits.sort(); document.getElementById("demo").innerHTML = fruits; } </script>

Sort numbers (numerically and ascending) - sort()

<br>

JavaScript Array Sort

<p>Click the button to sort the array in ascending order.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> var points = [40, 100, 1, 5, 25, 10]; document.getElementById("demo").innerHTML = points; function myFunction() { points.sort(function(a, b){return a - b}); document.getElementById("demo").innerHTML = points; } </script>

Sort numbers (numerically and descending) - sort()

<br>

JavaScript Array Sort

<p>Click the button to sort the array in descending order.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> var points = [40, 100, 1, 5, 25, 10]; document.getElementById("demo").innerHTML = points; function myFunction() { points.sort(function(a, b){return b - a}); document.getElementById("demo").innerHTML = points; } </script> </body> </html

Sort numbers (alphabetically and numerically) - sort()

<br>

JavaScript Array Sort

<p>Click the buttons to sort the array alphabetically or numerically.</p> <button onclick="myFunction1()">Sort Alphabetically</button> <button onclick="myFunction2()">Sort Numerically</button> <p id="demo"></p> <script> var points = [40, 100, 1, 5, 25, 10]; document.getElementById("demo").innerHTML = points; function myFunction1() { points.sort(); document.getElementById("demo").innerHTML = points; } function myFunction2() { points.sort(function(a, b){return a - b}); document.getElementById("demo").innerHTML = points; } </script>

Sort numbers in random order - sort()

<br>

JavaScript Array Sort

<p>Click the button (again and again) to sort the array in random order.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> var points = [40, 100, 1, 5, 25, 10]; document.getElementById("demo").innerHTML = points; function myFunction() { points.sort(function(a, b){return 0.5 - Math.random()}); document.getElementById("demo").innerHTML = points; } </script>

Sort objects by numeric properties - sort()

<br>

JavaScript Array Sort

<p>Click the buttons to sort car objects on age.</p> <button onclick="myFunction()">Sort</button> <p id="demo"></p> <script> var cars = [ {type:"Volvo", year:2016}, {type:"Saab", year:2001}, {type:"BMW", year:2010}] displayCars(); function myFunction() { cars.sort(function(a, b){return a.year - b.year}); displayCars(); } function displayCars() { document.getElementById("demo").innerHTML = cars[0].type + " " + cars[0].year + "<br>" + cars[1].type + " " + cars[1].year + "<br>" + cars[2].type + " " + cars[2].year; } </script>

Sort objects by string properties - sort()

<br>

JavaScript Array Sort

<p>Click the buttons to sort car objects on type.</p> <button onclick="myFunction()">Sort</button> <p id="demo"></p> <script> var cars = [ {type:"Volvo", year:2016}, {type:"Saab", year:2001}, {type:"BMW", year:2010}] displayCars(); function myFunction() { cars.sort(function(a, b){ var x = a.type.toLowerCase(); var y = b.type.toLowerCase(); if (x < y) {return -1;} if (x > y) {return 1;} return 0; }); displayCars(); } function displayCars() { document.getElementById("demo").innerHTML = cars[0].type + " " + cars[0].year + "<br>" + cars[1].type + " " + cars[1].year + "<br>" + cars[2].type + " " + cars[2].year; } </script>

Add an element to position 2 in an array - splice()

<br>

JavaScript Array Methods

splice()

<p>The splice() method adds new elements to an array.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo").innerHTML = fruits; function myFunction() { fruits.splice(2, 0, "Lemon", "Kiwi"); document.getElementById("demo").innerHTML = fruits; } </script>

Convert an array to a string - toString()

<br>

JavaScript Array Methods&

toString()

<p>The toString() method returns an array as a comma separated string:</p> <p id="demo"></p> <script> var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo").innerHTML = fruits.toString(); </script>

Add new elements to the beginning of an array - unshift()

<br>

JavaScript Array Methods&

unshift()

<p>The unshift() method adds new elements to the beginning of an array.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo").innerHTML = fruits; function myFunction() { fruits.unshift("Lemon"); document.getElementById("demo").innerHTML = fruits; } </script>

Display the typeof all variable types

<br>

The JavaScript typeof Operator

<p>The typeof operator returns the type of a variable, object, function or expression.</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = typeof "john" + "<br>" + typeof 3.14 + "<br>" + typeof NaN + "<br>" + typeof false + "<br>" + typeof [1,2,3,4] + "<br>" + typeof {name:'john', age:34} + "<br>" + typeof new Date() + "<br>" + typeof function () {} + "<br>" + typeof myCar + "<br>" + typeof null; </script> </body> </html>

Display the constructor of all variable types

<br>

The JavaScript constructor Property

<p>The constructor property returns the constructor function for a variable or an object.</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = "john".constructor + "<br>" + (3.14).constructor + "<br>" + false.constructor + "<br>" + [1,2,3,4].constructor + "<br>" + {name:'john', age:34}.constructor + "<br>" + new Date().constructor + "<br>" + function () {}.constructor; </script> </body> </html>

Convert a number to a string using String()

<br>

The JavaScript String() Method

<p>The String() method can convert a number to a string.</p> <p id="demo"></p> <script> var x = 123; document.getElementById("demo").innerHTML = String(x) + "<br>" + String(123) + "<br>" + Stri</pre>ng(100 + 23); </script>

Convert a number to a string using toString()

<br>

The JavaScript toString() Method

<p>The toString() method converts a number to a string.</p> <p id="demo"></p> <script> var x = 123; document.getElementById("demo").innerHTML = x.toString() + "<br>" + (123).toString() + "<br>" + (100 + 23).toString(); </script>

Find out if a variable is an array

<br>

JavaScript Arrays

<p>This "home made" isArray() function returns true when used on an array:</p> <p id="demo"></p> <script> var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo").innerHTML = isArray(fruits); function isArray(myArray) { return myArray.constructor.toString().indexOf("Array") > -1; } </script>

Find out if a variable is a date

<br>

JavaScript Date Object

<p>This "home made" isDate() function returns true when used on an date:</p> <p id="demo"></p> <script> var myDate = new Date(); document.getElementById("demo").innerHTML = isDate(myDate); function isDate(myDate) { return myDate.constructor.toString().indexOf("Date") > -1; } </script>

Display the value of Boolean(10 > 9)

<br>

<p>Display the value of Boolean(10 > 9):</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    document.getElementById("demo").innerHTML = Boolean(10 > 9);
}
</script>


Display the value of 10 > 9

<br>

<p>Display the value of 10 > 9:</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    document.getElementById("demo").innerHTML = 10 > 9;
}
</script>


Everything with a real value is true

<br>

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

<script>
var b1 = Boolean(100);
var b2 = Boolean(3.14);
var b3 = Boolean(-15);
var b4 = Boolean("Hello");
var b5 = Boolean('false');
var b6 = Boolean(1 + 7 + 3.14);

document.getElementById("demo").innerHTML =
"100 is " + b1 + "<br>" +
"3.14 is " + b2 + "<br>" +
"-15 is " + b3 + "<br>" +
"Any (not empty) string is " + b4 + "<br>" +
"Even the string 'false' is " + b5 + "<br>" +
"Any expression (except zero) is " + b6;
</script>


The Boolean value of zero is false

<br>

<p>Display the Boolean value of 0:</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = 0;
    document.getElementById("demo").innerHTML = Boolean(x);
}
</script>


The Boolean value of minus zero is false

<br>

<p>Display the Boolean value of -0:</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = -0;
    document.getElementById("demo").innerHTML = Boolean(x);
}
</script>


The Boolean value of an empty string is false

<br>

<p>Display the Boolean value of "":</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = "";
    document.getElementById("demo").innerHTML = Boolean(x);
}
</script>


The Boolean value of undefined is false

<br>

<p>Display the Boolean value of undefined:</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x;
    document.getElementById("demo").innerHTML = Boolean(x);
}
</script>


The Boolean value of null is false

<br>

<p>Display the Boolean value of null:</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = null;
    document.getElementById("demo").innerHTML = Boolean(x);
}
</script>


The Boolean value of false is false

<br>

<p>Display the Boolean value of false:</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = false;
    document.getElementById("demo").innerHTML = Boolean(x);
}
</script>


The Boolean value of NaN is false

<br>

<p>Display the Boolean value of NaN:</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = 10 / "H";
    document.getElementById("demo").innerHTML = Boolean(x);
}
</script>


Assign 5 to x, and display the value of (x == 8)

<br>

JavaScript Comparison

<p>Assign 5 to x, and display the value of the comparison (x == 8):</p> <p id="demo"></p> <script> var x = 5; document.getElementById("demo").innerHTML = (x == 8); </script>

Assign 5 to x, and display the value of (x == 5)

<br>

JavaScript Comparison

<p>Assign 5 to x, and display the value of the comparison (x == 5):</p> <p id="demo"></p> <script> var x = 5; document.getElementById("demo").innerHTML = (x == 5); </script>

Assign 5 to x, and display the value of (x === 5)

<br>

JavaScript Comparison

<p>Assign 5 to x, and display the value of the comparison (x === 5):</p> <p id="demo"></p> <script> var x = 5; document.getElementById("demo").innerHTML = (x === 5); </script>

Assign 5 to x, and display the value of (x === "5")

<br>

JavaScript Comparison

<p>Assign 5 to x, and display the value of the comparison (x === "5").</p> <p id="demo"></p> <script> var x = 5; document.getElementById("demo").innerHTML = (x === "5"); </script>

Assign 5 to x, and display the value of (x != 8)

<br>

JavaScript Comparison

<p>Assign 5 to x, and display the value of the comparison (x != 8).</p> <p id="demo"></p> <script> var x = 5; document.getElementById("demo").innerHTML = (x != 8); </script>

Assign 5 to x, and display the value of (x !== 5)

<br>

JavaScript Comparison

<p>Assign 5 to x, and display the value of the comparison (x !== 5):</p> <p id="demo"></p> <script> var x = 5; document.getElementById("demo").innerHTML = (x !== 5); </script>

Assign 5 to x, and display the value of (x !== "5")

<br>

JavaScript Comparison

<p>Assign 5 to x, and display the value of the comparison (x !== "5"):</p> <p id="demo"></p> <script> var x = 5; document.getElementById("demo").innerHTML = (x !== "5"); </script>

Assign 5 to x, and display the value of (x > 8)

<br>

JavaScript Comparison

<p>Assign 5 to x, and display the value of the comparison (x > 8).</p> <p id="demo"></p> <script> var x = 5; document.getElementById("demo").innerHTML = (x > 8); </script>

Assign 5 to x, and display the value of (x < 8)

<br>

JavaScript Comparison

<p>Assign 5 to x, and display the value of the comparison (x < 8).</p> <p id="demo"></p> <script> var x = 5; document.getElementById("demo").innerHTML = (x < 8); </script>

Assign 5 to x, and display the value of (x >= 8)

<br>

JavaScript Comparison

<p>Assign 5 to x, and display the value of the comparison (x >= 8).</p> <p id="demo"></p> <script> var x = 5; document.getElementById("demo").innerHTML = (x >= 8); </script>

Assign 5 to x, and display the value of (x <= 8)

<br>

JavaScript Comparison

<p>Assign 5 to x, and display the value of the comparison (x <= 8).</p> <p id="demo"></p> <script> var x = 5; document.getElementById("demo").innerHTML = (x <= 8); </script>

The if statement

<br>

<p>Display "Good day!" if the hour is less than 18:00:</p>

<p id="demo">Good Evening!</p>

<script>
if (new Date().getHours() < 18) {
    document.getElementById("demo").innerHTML = "Good day!";
}
</script>


The else statement

<br>

<p>Click the button to display a time-based greeting:</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var hour = new Date().getHours(); 
    var greeting;
    if (hour < 18) {
        greeting = "Good day";
    } else {
        greeting = "Good evening";
    }
    document.getElementById("demo").innerHTML = greeting;
}
</script>


The else if statement

<br>

<p>Click the button to get a time-based greeting:</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var greeting;
    var time = new Date().getHours();
    if (time < 10) {
        greeting = "Good morning";
    } else if (time < 20) {
        greeting = "Good day";
    } else {
        greeting = "Good evening";
    }
document.getElementById("demo").innerHTML = greeting;
}
</script>


Switch statement

<br>

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

<script>
var day;
switch (new Date().getDay()) {
    case 0:
        day = "Sunday";
        break;
    case 1:
        day = "Monday";
        break;
    case 2:
        day = "Tuesday";
        break;
    case 3:
        day = "Wednesday";
        break;
    case 4:
        day = "Thursday";
        break;
    case 5:
        day = "Friday";
        break;
    case  6:
        day = "Saturday";
}
document.getElementById("demo").innerHTML = "Today is " + day;
</script>


For loop

<br>

<p>Click the button to loop through a block of code five times.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>

<script>
function myFunction() {
    var x = "", i;
    for (i=0; i<5; i++) {
        x = x + "The number is " + i + "<br>";
    }
    document.getElementById("demo").innerHTML = x;
}
</script>


Looping through HTML headers

<br>

<p>Click the button to loop from 1 to 6, to make HTML headings.</p>
<button onclick="myFunction()">Try it</button>
<div id="demo"></div>

<script>
function myFunction() {
    var x ="", i;
    for (i=1; i<=6; i++) {
        x = x + "<h" + i + ">Heading " + i + "</h" + i + ">";
    }
    document.getElementById("demo").innerHTML = x;
}
</script>


While loop

<br>

JavaScript while

<p id="demo"></p> <script> var text = ""; var i = 0; while (i < 10) { text += "<br>The number is " + i; i++; } document.getElementById("demo").innerHTML = text; </script>

Do While loop

<br>

JavaScript do ... while

<p id="demo"></p> <script> var text = "" var i = 0; do { text += "<br>The number is " + i; i++; } while (i < 10); document.getElementById("demo").innerHTML = text; </script>

Break a loop

<br>

<p>A loop with a break.</p>

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

<script>
var text = "";
var i;
for (i = 0; i < 10; i++) {
    if (i === 3) { break; }
    text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>


Break and continue a loop

<br>

<p>A loop which will skip the step where i = 3.</p>

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

<script>
var text = "";
var i;
for (i = 0; i < 10; i++) {
    if (i === 3) { continue; }
    text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>


Use a for...in statement to loop through the elements of an

<br>

JavaScript Loops

<p>The for/in statement loops through the properties of an object.</p> <p id="demo"></p> <script> var txt = ""; var person = {fname:"John", lname:"Doe", age:25}; var x; for (x in person) { txt += person[x] + " "; } document.getElementById("demo").innerHTML = txt; </script>

The try...catch statement

<br>

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

<script>
try {
    adddlert("Welcome guest!");
}
catch(err) {
    document.getElementById("demo").innerHTML = err.message;
}
</script>


The try...catch statement with a confirm box

<br>

<html>
<head>
<script>
var txt = "";
function message() {
    try {
        adddlert("Welcome guest!");
    }
    catch(err) {
        txt = "There was an error on this page.\n\n";
        txt += "Click OK to continue viewing this page,\n";
        txt += "or Cancel to return to the home page.\n\n";
        if(!confirm(txt)) {
            document.location.href = "https://www.w3schools.com/";
        }
    }
}
</script>
</head>

<body>
<input type="button" value="View message" onclick="message()" />
</body>
/html>

The onerror event

<br>

<html>
<head>
<script>
onerror = handleErr;
var txt = "";
function handleErr(msg, url, l) {
    txt = "There was an error on this page.\n\n";
    txt += "Error: " + msg + "\n";
    txt += "URL: " + url + "\n";
    txt += "Line: " + l + "\n\n";
    txt += "Click OK to continue.\n\n";
    alert(txt);
    return true;
}

function message() {
   adddlert("Welcome guest!");
}
</script>
</head>

<body>
<input type="button" value="View message" onclick="message()" />
</body>
/html>

Search for an expression in a string

<br>

<p>Search a string for "w3Schools", and display the position of the match:</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var str = "Visit W3Schools!"; 
    var n = str.search(/w3Schools/i);
    document.getElementById("demo").innerHTML = n;
}
</script>

</body>
</html


Search for an expression and replace it

<br>

JavaScript String Methods

<p>Replace "microsoft" with "W3Schools" in the paragraph below:</p> <button onclick="myFunction()">Try it</button> <p id="demo">Please visit Microsoft and Microsoft!</p> <script> function myFunction() { var str = document.getElementById("demo").innerHTML; var txt = str.replace(/microsoft/i,"W3Schools"); document.getElementById("demo").innerHTML = txt; } </script> </body> </html>

<br>

<p>Creating a JavaScript Variable.</p>

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

<script>
var person = "John Doe";
document.getElementById("demo").innerHTML = person;
</script>


<br>

<p>Creating a JavaScript Object.</p>

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

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

document.getElementById("demo").innerHTML =
person.firstName + " " + person.lastName;
</script>


<br>

<p>Creating a JavaScript Object.</p>

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

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

document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>


<br>

<p>Creating a JavaScript Object.</p>

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

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

document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>


<br>

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

<script>
var person = new Object();
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue"; 

document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>


JavaScript Object Constructors

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

<script>

// Constructor function for Person objects
function Person(first, last, age, eye) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eye;
}

// Create a Person object
var myFather = new Person("John", "Doe", 50, "blue");

// Display age
document.getElementById("demo").innerHTML =
"My father is " + myFather.age + "."; 

</script>

<br>

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

<script>
var x1 = new Object();   // A new Object object
var x2 = new String();   // A new String object
var x3 = new Number();   // A new Number object
var x4 = new Boolean();  // A new Boolean object
var x5 = new Array();    // A new Array object
var x6 = new RegExp();   // A new RegExp object
var x7 = new Function(); // A new Function object
var x8 = new Date();     // A new Date object

document.getElementById("demo").innerHTML =
"x1: " + typeof x1 + "<br>" +
"x2: " + typeof x2 + "<br>" +
"x3: " + typeof x3 + "<br>" +
"x4: " + typeof x4 + "<br>" +
"x5: " + typeof x5 + "<br>" +
"x6: " + typeof x6 + "<br>" +
"x7: " + typeof x7 + "<br>" +
"x8: " + typeof x8 + "<br>";
</script>

<p>There is no need to use String(), Number(), Boolean(), Array(), and RegExp()</p>
<p>Rea</pre>d the JavaScript tutorials.</p>


<br>

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

<script>
var x1 = {};
var x2 = "";
var x3 = 0;
var x4 = false;
var x5 = [];
var x6 = /()/;
var x7 = function(){};

document.getElementById("demo").innerHTML =
"x1: " + typeof x1 + "<br>" +
"x2: " + typeof x2 + "<br>" +
"x3: " + typeof x3 + "<br>" +
"x4: " + typeof x4 + "<br>" +
"x5: " + typeof x5 + "<br>" +
"x6: " + typeof x6 + "<br>" +
"x7: " + typeof x7 + "<br>";
</script>


<br>

<p>JavaScript objects are mutable.</p>
<p>Any changes to a copy of an object will also change the original.</p>

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

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

var x = person;
x.age = 10;

document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>


<br>

<p>There are two different ways to access an object property:</p>
<p>You can use .property or ["property"].</p>

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

<script>
var person = {
    firstname:"John",
    lastname:"Doe",
    age:50,
    eyecolor:"blue"
};
document.getElementById("demo").innerHTML =
person.firstname + " is " + person.age + " years old.";
</script>


<br>

<p>There are two different ways to access an object property:</p>
<p>You can use .property or ["property"].</p>

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

<script>
var person = {
    firstname:"John",
    lastname:"Doe",
    age:50,
    eyecolor:"blue"
};
document.getElementById("demo").innerHTML =
person["firstname"] + " is " + person["age"] + " years old.";
</script>


<br>

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

<script>
var txt = "";
var person = {fname:"John", lname:"Doe", age:25}; 
var x;
for (x in person) {
    txt += person[x] + " ";
}
document.getElementById("demo").innerHTML = txt;
</script>


<br>

<p>You can add new properties to existing objects.</p>

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

<script>
var person = {
    firstname:"John",
    lastname:"Doe",
    age:50,
    eyecolor:"blue"
};
person.nationality = "English";
document.getElementById("demo").innerHTML =
person.firstname + " is " + person.nationality + ".";
</script>


<br>

<p>You can delete object properties.</p>

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

<script>
var person = {
    firstname:"John",
    lastname:"Doe",
    age:50,
    eyecolor:"blue"
};
delete person.age;
document.getElementById("demo").innerHTML =
person.firstname + " is " + person.age + " years old.";
</script>


<br>

<p>Access a JSON object using dot notation:</p>

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

<script>

var myObj, x;
myObj = { "name":"John", "age":30, "car":null };
x = myObj.name;
document.getElementById("demo").innerHTML = x;

</script>


<br>

<p>Access a JSON object using bracket notation:</p>

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

<script>

var myObj, x;
myObj = { "name":"John", "age":30, "car":null };
x = myObj["name"];
document.getElementById("demo").innerHTML = x;

</script>


<br>

<p>How to loop through all properties in a JSON object.</p>

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

<script>
var myObj = { "name":"John", "age":30, "car":null };
for (x in myObj) {
    document.getElementById("demo").innerHTML += x + "<br>";
}
</script>


<br>

<p>Use bracket notation to access the property values.</p>

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

<script>
var myObj = { "name":"John", "age":30, "car":null };
for (x in myObj) {
    document.getElementById("demo").innerHTML += myObj[x] + "<br>";
}
</script>


<br>

<p>How to access nested JSON objects.</p>

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

<script>
var myObj = {
  "name":"John",
  "age":30,
  "cars": {
    "car1":"Ford",
    "car2":"BMW",
    "car3":"Fiat"
  }
}
document.getElementById("demo").innerHTML += myObj.cars.car2 + "<br>";
//or:
document.getElementById("demo").innerHTML += myObj.cars["car2"];
</script>


<br>

<p>How to modify values in a JSON object.</p>

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

<script>
var myObj, i, x = "";
myObj = {
  "name":"John",
  "age":30,
  "cars": {
    "car1":"Ford",
    "car2":"BMW",
    "car3":"Fiat"
  }
}
myObj.cars.car2 = "Mercedes";

for (i in myObj.cars) {
    x += myObj.cars[i] + "<br>";
}

document.getElementById("demo").innerHTML = x;

</script>


<br>

<p>How to modify values in a JSON object using the bracket notation.</p>

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

<script>
var myObj, i, x = "";
myObj = {
  "name":"John",
  "age":30,
  "cars": {
    "car1":"Ford",
    "car2":"BMW",
    "car3":"Fiat"
  }
}
myObj.cars["car2"] = "Mercedes";

for (i in myObj.cars) {
    x += myObj.cars[i] + "<br>";
}

document.getElementById("demo").innerHTML = x;

</script>


<br>

<p>How to delete properties of a JSON object.</p>

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

<script>
var myObj, i, x = "";
myObj = {
  "name":"John",
  "age":30,
  "cars": {
    "car1":"Ford",
    "car2":"BMW",
    "car3":"Fiat"
  }
}
delete myObj.cars.car2;

for (i in myObj.cars) {
    x += myObj.cars[i] + "<br>";
}

document.getElementById("demo").innerHTML = x;

</script>


<br>

<p>Access an array value of a JSON object.</p>

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

<script>

var myObj, x;
myObj = {
    "name":"John",
    "age":30,
    "cars":[ "Ford", "BMW", "Fiat" ]
};
x = myObj.cars[0];
document.getElementById("demo").innerHTML = x;

</script>


<br>

<p>Looping through an array using a for in loop:</p>

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

<script>

var myObj, i, x = "";
myObj = {
    "name":"John",
    "age":30,
    "cars":[ "Ford", "BMW", "Fiat" ]
};

for (i in myObj.cars) {
    x += myObj.cars[i] + "<br>";
}

document.getElementById("demo").innerHTML = x;

</script>


<br>

<p>Loopin through an array using a for loop:</p>

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

<script>

var myObj, i, x = "";
myObj = {
    "name":"John",
    "age":30,
    "cars":[ "Ford", "BMW", "Fiat" ]
};

for (i = 0; i < myObj.cars.length; i++) {
    x += myObj.cars[i] + "<br>";
}

document.getElementById("demo").innerHTML = x;

</script>


<br>

<p>Looping through arrays inside arrays.</p>

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

<script>

var myObj, i, j, x = "";
myObj = {
    "name":"John",
    "age":30,
    "cars": [
        { "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] },
        { "name":"BMW", "models":[ "320", "X3", "X5" ] },
        { "name":"Fiat", "models":[ "500", "Panda" ] }
    ]
}

for (i in myObj.cars) {
    x += "

" + myObj.cars[i].name + "&l

for (j in myObj.cars[i].models) { x += myObj.cars[i].models[j] + "<br>"; } } document.getElementById("demo").innerHTML = x; </script>

<br>

<p>How to modify an array value of a JSON object.</p>

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

<script>

var myObj, i, x = "";
myObj = {
    "name":"John",
    "age":30,
    "cars":[ "Ford", "BMW", "Fiat" ]
};
myObj.cars[1] = "Mercedes";

for (i in myObj.cars) {
    x += myObj.cars[i] + "<br>";
}

document.getElementById("demo").innerHTML = x;

</script>


<br>

<p>How to delete properties of an array.</p>

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

<script>
var myObj, i, x = "";
myObj = {
  "name":"John",
  "age":30,
  "cars": ["Ford","BMW","Fiat"]
}
delete myObj.cars[1];

for (i in myObj.cars) {
    x += myObj.cars[i] + "<br>";
}

document.getElementById("demo").innerHTML = x;

</script>


Create Object from JSON String

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

<script>

var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');
document.getElementById("demo").innerHTML = obj.name + ", " + obj.age;

</script>

Use the XMLHttpRequest to get the content of a file.

<p>The content is written in JSON format, and can easily be converted into a JavaScript object.</p>

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

<script>

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var myObj = JSON.parse(this.responseText);
        document.getElementById("demo").innerHTML = myObj.name;
    }
};
xmlhttp.open("GET", "json_demo.txt", true);
xmlhttp.send();

</script>

<p>Tak</pre>e a look at <a href="json_demo.txt" target="_blank">json_demo.txt</a></p>


Content as Array.

<p>Content written as an JSON array will be converted into a JavaScript array.</p>

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

<script>

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var myArr = JSON.parse(this.responseText);
        document.getElementById("demo").innerHTML = myArr[0];
    }
};
xmlhttp.open("GET", "json_demo_array.txt", true);
xmlhttp.send();

</script>

<p>Take a look at <a href="json_demo_array.txt" target="_blank">json_demo_array.txt</a></p>


Convert a string into a date object.

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

<script>

var text = '{ "name":"John", "birth":"1986-12-14", "city":"New York"}';
var obj = JSON.parse(text);
obj.birth = new Date(obj.birth);

document.getElementById("demo").innerHTML = obj.name + ", " + obj.birth; 

</script>

Convert a string into a date object.

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

<script>

var text = '{ "name":"John", "birth":"1986-12-14", "city":"New York"}';
var obj = JSON.parse(text, function (key, value) {
    if (key == "birth") {
        return new Date(value);
    } else {
        return value;
    }});
document.getElementById("demo").innerHTML = obj.name + ", " + obj.birth; 

</script>

Convert a string into a function.

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

<script>

var text = '{ "name":"John", "age":"function() {return 30;}", "city":"New York"}';
var obj = JSON.parse(text);
obj.age = eval("(" + obj.age + ")");

document.getElementById("demo").innerHTML = obj.name + ", " + obj.age(); 

</script>

Create JSON string from a JavaScript object.

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

<script>

var obj = { "name":"John", "age":30, "city":"New York"};
var myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;

</script>

Create JSON string from a JavaScript array.

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

<script>

var arr = [ "John", "Peter", "Sally", "Jane" ];
var myJSON = JSON.stringify(arr);
document.getElementById("demo").innerHTML = myJSON;

</script>

JSON.stringify will convert any date objects into strings.

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

<script>

var obj = { "name":"John", "today":new Date(), "city":"New York"};
var myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;

</script>

JSON.stringify will remove any functions from an object.

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

<script>

var obj = { "name":"John", "age":function () {return 30;}, "city":"New York"};
var myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;

</script>

JSON.stringify will remove any functions from an object.

<p>Convert the functions into strings to keep them in the JSON object.</p>

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

<script>

var obj = { "name":"John", "age":function () {return 30;}, "city":"New York"};
obj.age = obj.age.toString();
var myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;

</script>

Get data as JSON from a PHP file on the server.

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

<script>

var xmlhttp = new XMLHttpRequest();

xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        myObj = JSON.parse(this.responseText);
        document.getElementById("demo").innerHTML = myObj.name;
    }
};
xmlhttp.open("GET", "demo_file.php", true);
xmlhttp.send();

</script>

Get data as JSON from a PHP file, and convert it into a JavaScript array.

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

<script>

var xmlhttp = new XMLHttpRequest();

xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var myObj = JSON.parse(this.responseText);
        document.getElementById("demo").innerHTML = myObj[2];
    }
};
xmlhttp.open("GET", "demo_file_array.php", true);
xmlhttp.send();

</script>

Get data as JSON from a PHP file on the server.

<p>The JSON received from the PHP file:</p>

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

<script>
var obj, dbParam, xmlhttp;
obj = { "table":"customers", "limit":10 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        document.getElementById("demo").innerHTML = this.responseText;
    }
};
xmlhttp.open("GET", "json_demo_db.php?x=" + dbParam, true);
xmlhttp.send();

</script>

Get data as JSON from a PHP file on the server.

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

<script>
var obj, dbParam, xmlhttp, myObj, x, txt = "";
obj = { "table":"customers", "limit":10 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        myObj = JSON.parse(this.responseText);
        for (x in myObj) {
            txt += myObj[x].name + "<br>";
        }
        document.getElementById("demo").innerHTML = txt;
    }
};
xmlhttp.open("GET", "json_demo_db.php?x=" + dbParam, true);
xmlhttp.send();

</script>

<p>Try changing the "table" property from "customers" to "products".</p>

Use the HTTP method POST to send data to the PHP file.

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

<script>
var obj, dbParam, xmlhttp, myObj, x, txt = "";
obj = { "table":"customers", "limit":10 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        myObj = JSON.parse(this.responseText);
        for (x in myObj) {
            txt += myObj[x].name + "<br>";
        }
        document.getElementById("demo").innerHTML = txt;
    }
};
xmlhttp.open("POST", "json_demo_db_post.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);

</script>

<p>Try changing the "table" property from "customers" to "products".</p>

Make a table based on JSON data.

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

<script>
var obj, dbParam, xmlhttp, myObj, x, txt = "";
obj = { "table":"customers", "limit":20 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        myObj = JSON.parse(this.responseText);
        txt += "<table border='1'>"
        for (x in myObj) {
            txt += "<tr><td>" + myObj[x].name + "</td></tr>";
        }
        txt += "</table>"        
        document.getElementById("demo").innerHTML = txt;
    }
};
xmlhttp.open("POST", "json_demo_db_post.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);

</script>

Make a table based on the value of a drop down menu.

<select id="myselect" onchange="change_myselect(this.value)">
<option value="">Choose an option:</option>
<option value="customers">Customers</option>
<option value="products">Products</option>
<option value="suppliers">Suppliers</option>
</select>


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

<script>
function change_myselect(sel) {
  var obj, dbParam, xmlhttp, myObj, x, txt = "";
  obj = { "table":sel, "limit":20 };
  dbParam = JSON.stringify(obj);
  xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      myObj = JSON.parse(this.responseText);
      txt += "<table border='1'>"
      for (x in myObj) {
        txt += "<tr><td>" + myObj[x].name + "</td></tr>";
      }
      txt += "</table>"        
      document.getElementById("demo").innerHTML = txt;
    }
  };
  xmlhttp.open("POST", "json_demo_db_post.php", true);
  xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xmlhttp.send("x=" + dbParam);
}
</script>

Make a drop down list based on JSON data.

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

<script>
var obj, dbParam, xmlhttp, myObj, x, txt = "";
obj = { "table":"customers", "limit":20 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        myObj = JSON.parse(this.responseText);
        txt += "<select>"
        for (x in myObj) {
            txt += "<option>" + myObj[x].name;
        }
        txt += "</select>"
        document.getElementById("demo").innerHTML = txt;
    }
};
xmlhttp.open("POST", "json_demo_db_post.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);

</script>

Request JSON using the script tag

<br>

<html>

<body>

<p>The PHP file returns a call to a function that will handle the JSON data.</p>

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

<script>
function myFunc(myObj) {
  document.getElementById("demo").innerHTML = myObj.name;
}
</script>

<script src="demo_jsonp.php"></script>

A script tag with a src attribute is created and placed in the document

<br>

<html>

<body>

Click the Button.

<p>The PHP file returns a call to a function with the JSON object as a parameter.</p> <button onclick="clickButton()">Click me!</button> <p id="demo"></p> <script> function clickButton() { var s = document.createElement("script"); s.src = "demo_jsonp.php"; document.body.appendChild(s); } function myFunc(myObj) { document.getElementById("demo").innerHTML = myObj.name; } </script>

A script tag with a src attribute is created and placed in the document

<br>

<html>

<body>

Click the Button.

<p>The PHP file returns a call to a function with the JSON object as a parameter.</p> <button onclick="clickButton()">Click me!</button> <p id="demo"></p> <p>Try changing the table property from "customers" to "products".</p> <script> function clickButton() { var obj, s obj = { "table":"customers", "limit":10 }; s = document.createElement("script"); s.src = "jsonp_demo_db.php?x=" + JSON.stringify(obj); document.body.appendChild(s); } function myFunc(myObj) { var x, txt = ""; for (x in myObj) { txt += myObj[x].name + "<br>"; } document.getElementById("demo").innerHTML = txt; } </script>

Request With a Callback Function

<br>

<html>

<body>

<p>The PHP file returns a call to the function you send as a callback.</p>

<button onclick="clickButton()">Click me!</button>

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

<script>
function clickButton() {
    var s = document.createElement("script");
    s.src = "demo_jsonp2.php?callback=myDisplayFunction";
    document.body.appendChild(s);
}

function myDisplayFunction(myObj) {
  document.getElementById("demo").innerHTML = myObj.name;
}
</script>

Display all name/value pairs of cookies in a document

<br>

<p id="demo">Click the button to display the cookies associated with this document.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    document.getElementById("demo").innerHTML =
    "Cookies associated with this document: " + document.cookie;
}
</script>


Display the domain name of the server that loaded the document

<br>

<p>Click the button to display the domain name of the server that loaded this document.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    document.getElementById("demo").innerHTML = document.domain;
}
</script>


Display the date and time the document was last modified

<br>

<p>This document was last modified <span id="demo"></span>.</p>

<script>
document.getElementById("demo").innerHTML = document.lastModified;
</script>


Display the URL of the document that loaded the current document

<br>

<p>Click the button to display the referrer of this document.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    document.getElementById("demo").innerHTML = document.referrer;
}
</script>


Display the title of a document

<br>

<html>
  <head>
<title>W3Schools Demo</title>
  </head>
<body>

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

<script>
document.getElementById("demo").innerHTML =
"The title of this document is: " + document.title;
</script>


Display the full URL of a document

<br>

<p>The full URL of this document is: <br><span id="demo"></span>.</p>

<script>
document.getElementById("demo").innerHTML = document.URL
</script>


Replace the content of a document

<br>

<p id="demo">Click the button to replace this document with new content.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    document.open("text/html","replace");
    document.write("

Learning about the HTML DOM is fun!<

document.close(); } </script>

Open a new window, and add some content

<br>

<p>Click the button to open a new window and add some content.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    var w = window.open();
    w.document.open();
    w.document.write("

Hello World!<

w.document.close(); } </script>

Display the number of elements with a specific name

<br>

<html>
<head>
<script>
function getElements() {
    var x = document.getElementsByName("x");
    document.getElementById("demo").innerHTML = x.length;
}
</script>
</head>
<body>

<p>
Cats: <input name="x" type="radio" value="Cats">
Dogs: <input name="x" type="radio" value="Dogs">
</p>

<p>
<input type="button" onclick="getElements()" value="How many elements named x?">
</p>

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


Display the number of elements with a specific tag name

<br>

<html>
<head>
<script>
function getElements() {
    var x = document.getElementsByTagName("input");
    document.getElementById("demo").innerHTML = x.length;
}
</script>
</head>
<body>

<input type="text" size="20"><br>
<input type="text" size="20"><br>
<input type="text" size="20"><br>

<p>
<input type="button" onclick="getElements()" value="How many input elements?">
</p>

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


Find the number of anchors in a document

<br>

<a name="html">HTML Tutorial</a><br>
<a name="css">CSS Tutorial</a><br>
<a name="xml">XML Tutorial</a><br>

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

<script>
document.getElementById("demo").innerHTML =
"Number of anchors are: " + document.anchors.length;
</script>



Find the innerHTML of the first anchor in a document

<br>

<a name="html">HTML Tutorial</a><br>
<a name="css">CSS Tutorial</a><br>
<a name="xml">XML Tutorial</a><br>

<p>Click the button to display the innerHTML of the first anchor in the document.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    document.getElementById("demo").innerHTML =
    document.anchors[0].innerHTML;
}
</script>


Display the number of links in a document

<br>

<p>
<a href="/html/default.asp">HTML</a>
<br>
<a href="/css/default.asp">CSS</a>
</p>

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

<script>
document.getElementById("demo").innerHTML =
"Number of links: " + document.links.length;
</script>


Display the href attribute of the first link in a document

<br>

<p>
<a href="/html/default.asp">HTML</a>
<br>
<a href="/css/default.asp">CSS</a>
</p>

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

<script>
document.getElementById("demo").innerHTML =
"The href of the first link is " + document.links[0].href;
</script>


Find the number of forms in a document

<br>

<form action="">
First name: <input type="text" name="fname" value="Donald">
<input type="submit" value="Submit">
</form> 

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

<script>
document.getElementById("demo").innerHTML =
"Number of forms: " + document.forms.length;
</script>


Find the name of the first form in a document

<br>

<form name="Form1"></form>
<form name="Form2"></form>
<form name="Form3"></form>

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

<script>
document.getElementById("demo").innerHTML =
"The name of the first for is " + document.forms[0].name;
</script>


Return the number of images in a document

<br>

<img src="https://www.w3schools.com/js/pic_htmltree.gif">
<img src="https://www.w3schools.com/js/pic_navigate.gif">

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

<script>
document.getElementById("demo").innerHTML =
"Number of images: " + document.images.length;
</script>


Return the id of the first image in a document

<br>

<img id="img1" src="https://www.w3schools.com/js/pic_htmltree.gif">
<img id="img2" src="https://www.w3schools.com/js/pic_navigate.gif">

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

<script>
document.getElementById("demo").innerHTML =
"The id of the first image is " + document.images[0].id;
</script>


Change the visibility of an HTML element

<br>

<p id="p1">
This is a text.
This is a text.
This is a text.
</p>

<input type="button" value="Hide text" 
onclick="document.getElementById('p1').style.visibility='hidden'">

<input type="button" value="Show text"
onclic</pre>k="document.getElementById('p1').style.visibility='visible'">


Change the background color of an HTML element

<br>

<html>
<head>

<script>
function bgChange(bg) {
    document.body.style.background = bg;
}
</script>
</head>

<body>

Change background color

<p>Mouse over the squares!</p> <table style="width:300px;height:100px"> <tr> <td onmouseover="bgChange(this.style.backgroundColor)" onmouseout="bgChange('transparent')" style="background-color:Khaki"> </td> <td onmouseover="bgChange(this.style.backgroundColor)" onmouseout="bgChange('transparent')" style="background-color:PaleGreen"> </td> <td onmouseover="bgChange(this.style.backgroundColor)" onmouseout="bgChange('transparent')" style="background-color:Silver"> </td> </tr> </tabl</pre>e>

Disable a button

<br>

<form>
<input type="button" id="btn01" value="OK">
</form>

<p>Click the "Disable" button to disable the "OK" button:</p>

<button onclick="disableElement()">Disable</button>

<script>
function disableElement() {
    document.getElementById("btn01").disabled = true;
}
</script>


Find the name of a button

<br>

<form id="frm1" action="/action_page.php">
<button id="btn1" name="subject" type="submit" value="HTML">HTML</button>
</form>

<p>Click the "Try it" button to display the name of the "HTML" button:</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = document.getElementById("btn1").name;
    document.getElementById("demo").innerHTML = x;
}
</script>


Find the type of a button

<br>

<button id="btn1" type="button">HTML</button>

<p>Click the "Try it" button to return the type of the "HTML" button:</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = document.getElementById("btn1").type;
    document.getElementById("demo").innerHTML = x;
}
</script>


Find the value of a button

<br>

<form id="frm1" action="/action_page.php">
<button id="btn1" name="subject" type="submit" value="fav_HTML">HTML</button>
<button id="btn2" name="subject" type="submit" value="fav_CSS">CSS</button>
</form>

<p>Click the "Try it" button to return the value of the "HTML" button:</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = document.getElementById("btn1").value;
    document.getElementById("demo").innerHTML = x;
}
</script>


Find the text displayed on a button

<br>

<form id="frm1" action="/action_page.php">
<button id="btn1" name="subject" type="submit" value="fav_HTML">HTML</button>
<button id="btn2" name="subject" type="submit" value="fav_CSS">CSS</button>
</form>

<p>Click the "Try it" button to return the text on the "HTML" button:</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = document.getElementById("btn1").innerHTML;
    document.getElementById("demo").innerHTML = x;
}
</script>


Find the id of the form a button belongs to

<br>

<form id="form1">
<button id="btn1" type="button">HTML</button>
</form>

<p>Click the "Try it" button to display the id of the form the HTML button belongs to:</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = document.getElementById("btn1").form.id;
    document.getElementById("demo").innerHTML = x;
}
</script>


Submit a form

<br>

<p>Enter names in the fields, then click "Submit" to submit the form:</p>

<form id="frm1" action="/action_page.php">
  First name: <input type="text" name="fname"><br>
  Last name: <input type="text" name="lname"><br><br>
  <input type="button" onclick="myFunction()" value="Submit">
</form>

<script>
function myFunction() {
    document.getElementById("frm1").submit();
}
</script>


Reset a form

<br>

<p>Enter names in the fields below, then click "Reset" to reset the form.</p>

<form id="frm1">
  First name: <input type="text" name="fname"><br>
  Last name: <input type="text" name="lname"><br><br>
  <input type="button" onclick="myFunction()" value="Reset">
</form>

<script>
function myFunction() {
    document.getElementById("frm1").reset();
}
</script>


Find the value of each element in a form

<br>

<form id="frm1" action="/action_page.php">
  First name: <input type="text" name="fname" value="Donald"><br>
  Last name: <input type="text" name="lname" value="Duck"><br><br>
  <input type="submit" value="Submit">
</form> 

<p>Click "Try it" to display the value of each element in the form.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = document.getElementById("frm1");
    var text = "";
    var i;
    for (i = 0; i < x.length ;i++) {
        text += x.elements[i].value + "<br>";
    }
    document.getElementById("demo").innerHTML = text;
}
</script>


Find the accepted character set of a form

<br>

<form id="frm1" accept-charset="ISO-8859-1">
  First name: <input type="text" name="fname" value="Donald"><br>
  Last name: <input type="text" name="lname" value="Duck"><br>
</form>

<p>Click "Try it" to display accept-charset of the form:</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = document.getElementById("frm1").acceptCharset;
    document.getElementById("demo").innerHTML = x;
}
</script>


Find the action attribute of a form

<br>

<form id="frm1" action="/action_page.php">
  First name: <input type="text" name="fname" value="Donald"><br>
  Last name: <input type="text" name="lname" value="Duck"><br><br>
  <input type="submit" value="Submit">
</form>

<p>Click "Try it" to display the value of the form's action attribute:</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = document.getElementById("frm1").action;
    document.getElementById("demo").innerHTML = x;
}
</script>


Find the value of the enctype attribute in a form

<br>

<form id="frm1" action="/action_page.php" method="post">
  First name: <input type="text" name="fname" value="Donald"><br>
  Last name: <input type="text" name="lname" value="Duck"><br><br>
  <input type="submit" value="Submit">
</form>

<p>Click "Try it" to display the value of the enctype attribute of the form:</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = document.getElementById("frm1").enctype;
    document.getElementById("demo").innerHTML = x;
}
</script>


Find the number of elements in a form

<br>

<form id="frm1" action="/action_page.php">
  First name: <input type="text" name="fname" value="Donald"><br>
  Last name: <input type="text" name="lname" value="Duck"><br><br>
  <input type="submit" value="Submit">
</form>

<p>Click "Try it" to display the number of elements the form:</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = document.getElementById("frm1").length;
    document.getElementById("demo").innerHTML = x;
}
</script>


Find the method for sending form data

<br>

<form id="frm1" action="/action_page.php" method="get">
  First name: <input type="text" name="fname" value="Donald"><br>
  Last name: <input type="text" name="lname" value="Duck"><br><br>
  <input type="submit" value="Submit">
</form>

<p>Click "Try it" to display the value of the form method.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = document.getElementById("frm1").method;
    document.getElementById("demo").innerHTML = x;
}
</script>


Find the name of a form

<br>

<form id="frm1" name="form1" action="/action_page.php">
  First name: <input type="text" name="fname" value="Donald"><br>
  Last name: <input type="text" name="lname" value="Duck"><br><br>
  <input type="submit" value="Submit">
</form>

<p>Click "Try it" to display the name of the form:</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = document.getElementById("frm1").name;
    document.getElementById("demo").innerHTML = x;
}
</script>


Find the target of a form

<br>

<form id="frm1" action="/action_page.php" target="_self">
  First name: <input type="text" name="fname" value="Donald"><br>
  Last name: <input type="text" name="lname" value="Duck"><br><br>
  <input type="submit" value="Submit">
</form>

<p>Click "Try it" to display the target of the form:</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = document.getElementById("frm1").target;
    document.getElementById("demo").innerHTML = x;
}
</script>


Disable and enable a dropdown list

<br>

<html>
<head>
<script>
function disable() {
    document.getElementById("mySelect").disabled=true;
}
function enable() {
    document.getElementById("mySelect").disabled=false;
}
</script>
</head>
<body>

<form>
<select id="mySelect">
  <option>Apple</option>
  <option>Pear</option>
  <option>Banana</option>
  <option>Orange</option>
</select>
<br><br>
<input type="button" onclick="disable()" value="Disable list">
<input type="button" onclick="enable()" value="Enable list">
</form


Get the id of the form that contains the dropdown list

<br>

<form id="myForm">
<select id="mySelect">
  <option>Apple</option>
  <option>Pear</option>
  <option>Banana</option>
  <option>Orange</option>
</select>
</form>

<p>The id of the form is:<p>
<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = document.getElementById("mySelect").form.id;
</script>


Get the number of options in the dropdown list

<br>

<html>
<head>
</head>
<body>

<form>
<select id="mySelect">
  <option>Apple</option>
  <option>Pear</option>
  <option>Banana</option>
  <option>Orange</option>
</select>
</form>

<p>There are <span id="demo">0</span> options in the list.</p>

<script>
document.getElementById("demo").innerHTML =
document.getElementById("mySelect").length;
</script>


Turn the dropdown list into a multiline list

<br>

<html>
<head>
<script>
function changeSize() {
    document.getElementById("mySelect").size = 4;
}
</script>
</head>
<body>

<form>
<select id="mySelect">
  <option>Apple</option>
  <option>Banana</option>
  <option>Orange</option>
  <option>Melon</option>
</select>
<input type="button" onclick="changeSize()" value="Change size">
</form


Select multiple options in a dropdown list

<br>

<html>
<head>
<script>
function selectMultiple() {
    document.getElementById("mySelect").multiple = true;
}
</script>
</head>
<body>

<form>
<select id="mySelect" size="4">
  <option>Apple</option>
  <option>Pear</option>
  <option>Banana</option>
  <option>Orange</option>
</select>
<input type="button" onclick="selectMultiple()" value="Select multiple">
</form>

<p>Before you click "Select multiple", you cannot select more than one option (by holding down the Shift or Ctrl key).</p>
<p>Aft</pre>er you have clicked "Select multiple", you can.</p>


Display the selected option in a dropdown list

<br>

<html>
<head>
<script>
function getOption() {
    var obj = document.getElementById("mySelect");
    document.getElementById("demo").innerHTML = 
    obj.options[obj.selectedIndex].text;
}
</script>
</head>
<body>

<form>
Select your favorite fruit:
<select id="mySelect">
  <option>Apple</option>
  <option>Orange</option>
  <option>Pineapple</option>
  <option>Banana</option>
</select>
<br><br>
<input type="button" onclick="getOption()" value="Click Me!">
</form>

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


Display all options from a dropdown list

<br>

<html>
<head>
<script>
function getOptions() {
    var x = document.getElementById("mySelect");
    var txt = "";
    var i;
    for (i = 0; i < x.length; i++) {
        txt = txt + " " + x.options[i].text;
    }
    document.getElementById("demo").innerHTML = txt;
}
</script>
</head>
<body>

<form>
Select your favorite fruit:
<select id="mySelect">
  <option>Apple</option>
  <option>Orange</option>
  <option>Pineapple</option>
  <option>Banana</option>
</select>
<br><br>
<input type="button" onclick="getOptions()" value="Output all options">
</form>

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


Display the index of the selected option in a dropdown list

<br>

<html>
<head>
<script>
function getIndex() {
    document.getElementById("demo").innerHTML =
    document.getElementById("mySelect").selectedIndex;
}
</script>
</head>
<body>

<form>
Select your favorite fruit:
<select id="mySelect">
  <option>Apple</option>
  <option>Orange</option>
  <option>Pineapple</option>
  <option>Banana</option>
</select>
<br><br>
<input type="button" onclick="getIndex()" 
value="Display the index of the selected option">
</form>

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


Change the text of the selected option

<br>

<html>
<head>
<script>
function changeText() {
    x = document.getElementById("mySelect");
    x.options[x.selectedIndex].text = "Melon";
}
</script>
</head>
<body>

<form>
Select your favorite fruit:
<select id="mySelect">
  <option>Apple</option>
  <option>Orange</option>
  <option>Pineapple</option>
  <option>Banana</option>
</select>
<br><br>
<input type="button" onclick="changeText()" value="Set text of selected option">
</form


Remove options from a dropdown list

<br>

<html>
<head>
<script>
function removeOption() {
    var x = document.getElementById("mySelect");
    x.remove(x.selectedIndex);
}
</script>
</head>
<body>

<form>
<select id="mySelect">
  <option>Apple</option>
  <option>Pear</option>
  <option>Banana</option>
  <option>Orange</option>
</select>
<input type="button" onclick="removeOption()" value="Remove the selected option">
</form


Find the value of the href attribute of a link

<br>

<p><a id="myAnchor" href="https://www.w3schools.com/">W3Schools</a></p>

<p>Click the button to display the value of the href attribute of the link above.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = document.getElementById("myAnchor").href;
    document.getElementById("demo").innerHTML = x;
}
</script>


Find the value of the hreflang attribute of a link

<br>

<p><a id="myAnchor" hreflang="en-us" href="https://www.w3schools.com/">W3Schools</a></p>

<p>Click the button to display the value of the hreflang attribute of the link above.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = document.getElementById("myAnchor").hreflang;
    document.getElementById("demo").innerHTML = x;
}
</script>


Find the value of the id attribute a link

<br>

<p><a id="myAnchor" href="https://www.w3schools.com/">W3Schools</a></p>

<p>Click the button to display the value of the id attribute of the link above.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = document.getElementById("myAnchor").id;
    document.getElementById("demo").innerHTML = x;
}
</script>


Find the value of the rel attribute of a link

<br>

<p><a id="myAnchor" rel="nofollow" href="https://www.w3schools.com/">W3Schools</a></p>

<p>Click the button to display the value of the rel attribute of the link above.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = document.getElementById("myAnchor").rel;
    document.getElementById("demo").innerHTML = x;
}
</script>


Find the value of the target attribute of a link

<br>

<p><a id="w3s" target="_self" href="https://www.w3schools.com/">W3Schools</a></p>

<p>Click the button to display the value of the target attribute of the link above.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = document.getElementById("w3s").target;
    document.getElementById("demo").innerHTML = x;
}
</script>


Find the value of the type attribute of a link

<br>

<p><a id="myAnchor" type="text/html" href="https://www.w3schools.com/">W3Schools</a></p>

<p>Click the button to return the value of the type attribute of the link above.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = document.getElementById("myAnchor").type;
    document.getElementById("demo").innerHTML = x;
}
</script>


Find the alternate text of an image-map area

<br>

<img src="https://www.w3schools.com/js/planets.gif" width="145" height="126" usemap="#planetmap">

<map name="planetmap">
<area id="venus" shape="circle" coords="124,58,8" alt="A beautiful planet" href="venus.htm">
</map>

<p>Click the button to display the alternate text for the "venus" area.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = document.getElementById("venus").alt;
    document.getElementById("demo").innerHTML = x;
}
</script>


Find the coordinates of an area

<br>

<img src="https://www.w3schools.com/js/planets.gif" width="145" height="126" usemap="#planetmap">

<map name="planetmap">
<area id="venus" shape="circle" coords="124,58,8" alt="Venus" href="venus.htm">
</map>

<p>Click the button to display the coordinates for the "venus" area.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = document.getElementById("venus").coords;
    document.getElementById("demo").innerHTML = x;
}
</script>


Find the shape of an area

<br>

<img src="https://www.w3schools.com/js/planets.gif" width="145" height="126" usemap="#planetmap">

<map name="planetmap">
<area id="venus" shape="circle" coords="124,58,8" alt="Venus" href="venus.htm">
</map>

<p>Click the button to return the shape of the "venus" area in the image-map.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = document.getElementById("venus").shape;
    document.getElementById("demo").innerHTML = x;
}
</script>


Find the href of an area

<br>

<img src="https://www.w3schools.com/js/planets.gif" width="145" height="126" usemap="#planetmap">

<map name="planetmap">
<area id="venus" shape="circle" coords="124,58,8" alt="Venus" href="venus.htm">
</map>

<p>Click the button to display the value of the href attribute for the "venus" area.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = document.getElementById("venus").href;
    document.getElementById("demo").innerHTML = x;
}
</script>


Find the protocol part of the href attribute of an area

<br>

<img src="https://www.w3schools.com/js/planets.gif" width="145" height="126" usemap="#planetmap">

<map name="planetmap">
<area id="venus" shape="circle" coords="124,58,8" alt="Venus" href="venus.htm">
</map>

<p>Click the button to display the protocol of the href attribute for the "venus" area.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = document.getElementById("venus").protocol;
    document.getElementById("demo").innerHTML = x;
}
</script>


Find the hostname part of the href attribute of an area

<br>

<img src="https://www.w3schools.com/js/planets.gif" width="145" height="126" usemap="#planetmap">

<map name="planetmap">
<area id="venus" shape="circle" coords="124,58,8" alt="Venus" href="venus.htm">
</map>

<p>Click the button to display the hostname of the href attribute for the "venus" area.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = document.getElementById("venus").hostname;
    document.getElementById("demo").innerHTML = x;
}
</script>


Find the port number part of the href attribute of an area

<br>

<img src="https://www.w3schools.com/js/planets.gif" width="145" height="126" usemap="#planetmap">

<map name="planetmap">
<area id="venus" shape="circle" coords="124,58,8" alt="Venus" href="venus.htm">
</map>

<p>Click the button to display the port of the href attribute for the "venus" area in the image-map.</p>

<p><b>Note:</b> If the port part is not specified in the URL, or if the port number is 80 (which is default), some browsers will just display 0 or nothing.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = document.getElementById("venus").port;
    document.getElementById("demo").innerHTML = "Port: " + x;
}
</script>


Find the pathname part of the href attribute of an area

<br>

<img src="https://www.w3schools.com/js/planets.gif" width="145" height="126" usemap="#planetmap">

<map name="planetmap">
<area id="venus" shape="circle" coords="124,58,8" alt="Venus" href="venus.htm">
</map>

<p>Click the button to display the pathname of the href attribute for the "venus" area in the image-map.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = document.getElementById("venus").pathname;
    document.getElementById("demo").innerHTML=x;
}
</script>


Find the querystring part of the href attribute of an area

<br>

<img src="https://www.w3schools.com/js/planets.gif" width="145" height="126" usemap="#planetmap">

<map name="planetmap">
<area id="venus" shape="circle" coords="124,58,8" alt="Venus" href="venus.htm?id=venus">
</map>

<p>Click the button to display the querystring part of the href attribute for the "venus" area.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = document.getElementById("venus").search;
    document.getElementById("demo").innerHTML = x;
}
</script>


Find the hash part of the href attribute of an area

<br>

<img src="https://www.w3schools.com/js/planets.gif" width="145" height="126" usemap="#planetmap">

<map name="planetmap">
<area id="venus" shape="circle" coords="124,58,8" alt="Venus" href="venus.htm#description">
</map>

<p>Click the button to display the anchor part of the href attribute for the "venus" area.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = document.getElementById("venus").hash;
    document.getElementById("demo").innerHTML = x;
}
</script>


Find the value of the target attribute of an area

<br>

<img src="https://www.w3schools.com/js/planets.gif" width="145" height="126" usemap="#planetmap">

<map name="planetmap">
<area id="venus" shape="circle" coords="124,58,8" alt="Venus" href="venus.htm" target="_self">
</map>

<p>Click the button to return the value of the target attribute for the "venus" area in the image-map.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = document.getElementById("venus").target;
    document.getElementById("demo").innerHTML = x;
}
</script>


Find the base URL for all relative URLs on a page

<br>

<html>
<head>
<base id="htmldom" href="https://www.w3schools.com/jsref/">
</head>
<body>

<p>Click the button to display the value of the href attribute of the base element.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = document.getElementById("htmldom").href;
    document.getElementById("demo").innerHTML = x;
}
</script>


Find the base target for all links on a page

<br>

<html>
<head>
<base id="htmldom" target="_self" href="https://www.w3schools.com/jsref/">
</head>
<body>

<p>Click the button to display the value of the target attribute of the base element.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = document.getElementById("htmldom").target;
    document.getElementById("demo").innerHTML = "Base target for all links: " + x;
}
</script>


Change the background color of an iframe

<br>

<iframe id="myframe" src="demo_iframe.htm">
<p>Your browser does not support iframes.</p>
</iframe>

<p>Click the button to change the background color of the document in the iframe.</p>

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

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    var x = document.getElementById("myframe");
    x.style.backgroundColor = "red";
}
</script>


Find the height of an iframe

<br>

<iframe id="myframe" src="/default.asp" height="200" width="250">
<p>Your browser does not support iframes.</p>
</iframe>

<p>Click the button to display the height of the iframe.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = document.getElementById("myframe").height;
    document.getElementById("demo").innerHTML = x;
}
</script>


Find the value of the name attribute of an iframe

<br>

<iframe id="myframe" src="/default.asp" name="iframe_a"></iframe>

<p>Click the button to return the name of the iframe.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = document.getElementById("myframe").name;
    document.getElementById("demo").innerHTML = x;
}
</script>


Find the source (src) attribute of an iframe

<br>

<iframe id="myframe" src="/default.asp"></iframe>

<p>Click the button to display the value of the src attribute in the iframe.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = document.getElementById("myframe").src;
    document.getElementById("demo").innerHTML = x;
}
</script>


Change the source (src) attribute of an iframe

<br>

<iframe id="myframe" src="/default.asp"></iframe>

<p>Click the button to change the src attribute in the iframe.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    document.getElementById("myframe").src = "http://www.cnn.com";
}
</script>


Find the alternate text of an image

<br>

<img id="myImg" src="https://www.w3schools.com/js/compman.gif" alt="Crazy computerman" width="107" height="98">

<p>Click the button to display the alternate text of the image.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = document.getElementById("myImg").alt;
    document.getElementById("demo").innerHTML = x;
}
</script>


Find the height of an image

<br>

<img id="myImg" src="https://www.w3schools.com/js/compman.gif" width="107" height="98">

<p>Click the button to display the height of the image.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = document.getElementById("myImg").height;
    document.getElementById("demo").innerHTML = x;
}
</script>


Click to display a high-resolution version of an image

<br>

<html>
<body>
<script>
function changeImage() {
    document.getElementById('myimage').src = "compman.gif";
}
</script>

<img id="myimage" onclick="changeImage()"
src="https://www.w3schools.com/js/compman_lowres.gif" width="107" height="98">

<p>Cli</pre>ck the image to display a high resolution version.</p>


Find the source (src) of an image

<br>

<img id="myImg" src="https://www.w3schools.com/js/compman.gif" width="107" height="98">

<p>Click the button to display the src attribute of the image.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = document.getElementById("myImg").src;
    document.getElementById("demo").innerHTML = x;
}
</script>


Change the source of an image

<br>

<img id="myImg" src="https://www.w3schools.com/js/compman_lowres.gif" width="107" height="98">
<br><br>
<button onclick="document.getElementById('myImg').src='compman.gif'">On</button>
<butto</pre>n onclick="document.getElementById('myImg').src='compman_lowres.gif'">Off</button>


Change the source of the lightbulb

<br>

<img id="myImage" onclick="changeImage()" src="https://www.w3schools.com/js/pic_bulboff.gif" width="100" height="180">

<p>Click the light bulb to turn on/off the light.</p>

<script>
function changeImage() {
    var image = document.getElementById('myImage');
    if (image.src.match("bulbon")) {
        image.src = "pic_bulboff.gif";
    } else {
        image.src = "pic_bulbon.gif";
    }
}
</script>


Find the value of the usemap attribute of an image

<br>

<img id="planets" src="https://www.w3schools.com/js/planets.gif" width="145" height="126" usemap="#planetmap">

<map name="planetmap">
<area id="venus" shape="circle" coords="124,58,8" alt="The planet venus" href="venus.htm">
</map>

<p>Click the button to display the value of the usemap attribute of the image.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
    var x = document.getElementById("planets").useMap;
    document.getElementById("demo").innerHTML = x;
}
</script>


Change the width of a table border

<br>

<html>
<head>
<script>
function changeBorder(id) {
    document.getElementById(id).style.border = "5px solid";
}
</script>
</head>
<body>

<table style="border:1px solid black" id="myTable">
<tr>
<td>100</td>
<td>200</td>
</tr>
<tr>
<td>300</td>
<td>400</td>
</tr>
</table>

<p>
<input type="button" onclick="changeBorder('myTable')" value="Change Border">
</p>


Change the padding of a table

<br>

<html>
<head>
<script>
function padding(id) {
    document.getElementById(id).style.padding = "15px";
}

</script>
</head>
<body>

<table id="myTable" style="border:1px solid black">
<tr>
<td>100</td>
<td>200</td>
</tr>
<tr>
<td>300</td>
<td>400</td>
</tr>
</table>

<p>
<input type="button" onclick="padding('myTable')" value="Change padding">
</p>


Find the innerHTML of a cell

<br>

<html>
<head>
<script>
function getCellContent(id) {
    var x = document.getElementById(id).rows[0].cells;
    document.getElementById("demo").innerHTML = x[0].innerHTML;
}
</script>
</head>
<body>

<table id="myTable" style="border: 1px solid black">
<tr>
<td>cell 1</td>
<td>cell 2</td>
</tr>
<tr>
<td>cell 3</td>
<td>cell 4</td>
</tr>
</table>

<p>
<input type="button" onclick="getCellContent('myTable')" value="Display first cell">
</p>

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


Create a caption for a table

<br>

<html>
<head>
<script>
function createCaption(id) {
    document.getElementById(id).createCaption().innerHTML = "My new caption";
}
</script>
</head>
<body>

<table id="myTable" style="border: 1px solid black">
<tr>
<td>Row1 cell1</td>
<td>Row1 cell2</td>
</tr>
<tr>
<td>Row2 cell1</td>
<td>Row2 cell2</td>
</tr>
</table>

<p>
<input type="button" onclick="createCaption('myTable')" value="Create caption">
</p>


Delete rows in a table

<br>

<table id="myTable" style="padding:8px;border:1px solid black">
 <tr>
    <td>Jill</td>
    <td>Smith</td>
    <td>50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td>94</td>
  </tr>
  <tr>
    <td>John</td>
    <td>Doe</td>
    <td>80</td>
  </tr>
</table>

<p>
<input type="button" value="Delete one Row"
onclick="document.getElementById('myTable').deleteRow(0)">
</p>


Add rows to a table

<br>

<html>
<head>
<script>
function insRow(id) {
    var x = document.getElementById(id).insertRow(0);
    var y = x.insertCell(0);
    var z = x.insertCell(1);
    y.innerHTML = z.innerHTML = "New";
}
</script>
</head>

<body>
<table id="myTable" style="border: 1px solid black">
<tr>
<td>Row1 cell1</td>
<td>Row1 cell2</td>
</tr>
<tr>
<td>Row2 cell1</td>
<td>Row2 cell2</td>
</tr>
<tr>
<td>Row3 cell1</td>
<td>Row3 cell2</td>
</tr>
</table>

<p>
<input type="button" onclick="insRow('myTable')" value="Insert row">
</p>


Change the content of a table cell

<br>

<html>
<head>
<script>
function changeContent(id, row, cell, content) {
    var x = document.getElementById(id).rows[row].cells;
    x[cell].innerHTML = content;
}
</script>
</head>

<body>
<table id="myTable" border="1">
<tr>
<td>Row1 cell1</td>
<td>Row1 cell2</td>
</tr>
<tr>
<td>Row2 cell1</td>
<td>Row2 cell2</td>
</tr>
<tr>
<td>Row3 cell1</td>
<td>Row3 cell2</td>
</tr>
</table>

<p>
<input type="button" onclick="changeContent('myTable', 0, 0, 'Hello')" value="Change content">
</p>


onblur - When a user leaves an input field

<br>

<html>
<head>
<script>
function myFunction() {
    var x = document.getElementById("fname");
    x.value = x.value.toUpperCase();
}
</script>
</head>
<body>

Enter your name: <input type="text" id="fname" onblur="myFunction()">

<p>When you leave the input field, a function is triggered which transforms the input text to upper </pre>case.</p>


onchange - When a user changes the content of an input field

<br>

<html>
<head>
<script>
function myFunction() {
    var x = document.getElementById("fname");
    x.value = x.value.toUpperCase();
}
</script>
</head>
<body>

Enter your name: <input type="text" id="fname" onchange="myFunction()">
<p>When you leave the input field, a function is triggered which transforms the input text to upper </pre>case.</p>


onchange - When a user selects a dropdown value

<br>

<html>
<head>
<script>
function preferedBrowser() {
    prefer = document.forms[0].browsers.value;
    alert("You prefer browsing internet with " + prefer);
}
</script>
</head>

<body>

<form>
Choose which browser you prefer:
<select id="browsers" onchange="preferedBrowser()">
<option value="Chrome">Chrome</option>
<option value="Internet Explorer">Internet Explorer</option>
<option value="Firefox">Firefox</option>
</select>
</form


onfocus - When an input field gets focus

<br>

<html>
<head>
<script>
function myFunction(x) {
    x.style.background = "yellow";
}
</script>
</head>
<body>

Enter your name: <input type="text" onfocus="myFunction(this)">

<p>When the input field gets focus, a function is triggered which changes the background-color.</p>


onselect - When input text is selected

<br>

<html>
<head>
<script>
function myFunction() {
    document.getElementById("demo").innerHTML = "You selected some text";
}
</script>
</head>
<body>

Some text: <input type="text" value="Hello world!" onselect="myFunction()">

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


onsubmit - When a user clicks the submit button

<br>

<html>
<head>
<script>
function confirmInput() {
    fname = document.forms[0].fname.value;
    alert("Hello " + fname + "! You will now be redirected to www.w3Schools.com");
}
</script>
</head>

<body>
<form onsubmit="confirmInput()" action="https://www.w3schools.com/">
Enter your name: <input id="fname" type="text" size="20">
<input type="submit">
</form>
</body>
/html>

onreset - When a user clicks the reset button

<br>

<html>
<head>
<script>
function message() {
    alert("This alert box was triggered by the onreset event handler");
}
</script>
</head>
<body>

<form onreset="message()">
Enter your name: <input type="text" size="20">
<input type="reset">
</form


onkeydown - When a user is pressing/holding down a key

<br>

<html>
<head>
<script>
function myFunction() {
    alert("You pressed a key inside the input field");
}
</script>
</head>
<body>

<p>A function is triggered when the user is pressing a key in the input field.</p>

<input</pre> type="text" onkeydown="myFunction()">


onkeypress - When a user is pressing/holding down a key

<br>

<html>
<head>
<script>
function myFunction() {
    alert("You pressed a key inside the input field");
}
</script>
</head>
<body>

<p>A function is triggered when the user is pressing a key in the input field.</p>

<input</pre> type="text" onkeypress="myFunction()">


onkeyup - When the user releases a key

<br>

<html>
<head>
<script>
function myFunction() {
    var x = document.getElementById("fname");
    x.value = x.value.toUpperCase();
}
</script>
</head>
<body>

<p>A function is triggered when the user releases a key in the input field. The function transforms the character to upper case.</p>
Enter </pre>your name: <input type="text" id="fname" onkeyup="myFunction()">


onkeyup - When the user releases a key

<br>

<html>
<head>
<script>
function writeMessage() {
    document.forms[0].mySecondInput.value = document.forms[0].myInput.value;
}
</script>
</head>

<body>

<p>The onkeyup event occurs when the a keyboard key is on its way UP.</p>
<form>
Enter your name:
<input type="text" name="myInput" onkeyup="writeMessage()" size="20">
<input type="text" name="mySecondInput" size="20">
</form


onkeydown vs onkeyup - Both

<br>

<html>
<head>
<script>
function color(color) {
    document.forms[0].myInput.style.background = color;
}
</script>
</head>

<body>

<form>
Write a message:<br>
<input
type="text" 
onkeydown="color('yellow')"
onkeyup="color('white')"
name="myInput">
</form


onmouseover/onmouseout - When the mouse passes over an element

<br>

<h1 on</pre>mouseover="style.color='red'" onmouseout="style.color='black'">Mouse over this text</h1>


onmousedown/onmouseup - When pressing/releasing a mouse button

<br>

<html>
<head>
<script>
function myFunction(elmnt, clr) {
    elmnt.style.color = clr;
}
</script>
</head>
<body>

<p onmousedown="myFunction(this,'red')" onmouseup="myFunction(this,'green')">
Click the text to change the color. A function, with parameters, is triggered when the mouse button is pressed down, and again, with other parameters, when the mouse button is released.
</p>


onmousedown - When mouse is clicked: Alert which element

<br>

<html>
<head>
<script>
function whichElement(e) {
    var targ;
    if (!e) {
        var e = window.event;
    }
    if (e.target) {
        targ=e.target;
    } else if (e.srcElement) {
        targ=e.srcElement;
    }
    var tname;
    tname = targ.tagName;
    alert("You clicked on a " + tname + " element.");
}
</script>
</head>
<body onmousedown="whichElement(event)">

<p>Click somewhere in the document. An alert box will alert the name of the element you clicked on.</p>
<h3>This is a heading</h3>
<img border="0" src="https://www.w3schools.com/js/smiley.gif" alt="Smiley" width="32" height="32">
<p>Thi</pre>s is a paragraph.</p>


onmousedown - When mouse is clicked: Alert which button

<br>

<html>
<head>
<script>
function WhichButton(event) {
    alert("You pressed button: " + event.button)
}
</script>
</head>
<body>

<div onmousedown="WhichButton(event);">Click this text (with one of your mouse-buttons)
<p>
0 Specifies the left mouse-button<br>
1 Specifies the middle mouse-button<br>
2 Specifies the right mouse-button</p>
<p><strong>Note:</strong> Internet Explorer 8, and earlier, returns another result:<br>
1 Specifies the left mouse-button<br>
4 Specifies the middle mouse-button<br>
2 Specifies the right mouse-button</p>

</div>
</body>
</html


onmousemove/onmouseout - When moving the mouse pointer over/out of an image

<br>

<html>
<head>
<script>
function myFunction(e) {
    x = e.clientX;
    y = e.clientY;
    coor = "Coordinates: (" + x + "," + y + ")";
    document.getElementById("demo").innerHTML = coor
}

function clearCoor() {
    document.getElementById("demo").innerHTML = "";
}
</script>
</head>
<body style="margin:0px;">

<div id="coordiv" style="width:199px;height:99px;border:1px solid" onmousemove="myFunction(event)" onmouseout="clearCoor()"></div>

<p>Mouse over the rectangle above, and get the coordinates of your mouse pointer.</p>

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


onmouseover/onmouseout - When moving the mouse over/out of an image

<br>

<html>
<head>
<script>
function bigImg(x) {
    x.style.height = "64px";
    x.style.width = "64px";
}

function normalImg(x) {
    x.style.height = "32px";
    x.style.width = "32px";
}
</script>
</head>
<body>

<img onmouseover="bigImg(this)" onmouseout="normalImg(this)" border="0" src="https://www.w3schools.com/js/smiley.gif" alt="Smiley" width="32" height="32">

<p>The function bigImg() is triggered when the user moves the mouse pointer over the image.</p>
<p>The</pre> function normalImg() is triggered when the mouse pointer is moved out of the image.</p>


onmouseover an image map

<br>

<html>
<head>
<script>
function writeText(txt) {
    document.getElementById("desc").innerHTML = txt;
}
</script>
</head>

<body>
<img src ="https://www.w3schools.com/js/planets.gif" width ="145" height ="126" alt="Planets" usemap="#planetmap" />

<map name="planetmap">
<area shape ="rect" coords ="0,0,82,126"
onmouseover="writeText('The Sun and the gas giant planets like Jupiter are by far the largest objects in our Solar System.')"
href ="sun.htm" target ="_blank" alt="Sun" />

<area shape ="circle" coords ="90,58,3"
onmouseover="writeText('The planet Mercury is very difficult to study from the Earth because it is always so close to the Sun.')"
href ="mercur.htm" target ="_blank" alt="Mercury" />

<area shape ="circle" coords ="124,58,8"
onmouseover="writeText('Until the 1960s, Venus was often considered a twin sister to the Earth because Venus is the nearest planet to us, and because the two planets seem to share many characteristics.')"
href ="venus.htm" target ="_blank" alt="Venus" />
</map> 

<p id="desc">Mouse over the sun and the planets and see the different descriptions.</p>

</body>
</html>



Acting to the onclick event

<br>

<html>
<head>
<script>
function displayDate() {
    document.getElementById("demo").innerHTML = Date();
}
</script>
</head>
<body>

My First JavaScript

<p id="demo">This is a paragraph.</p> <butto</pre>n type="button" onclick="displayDate()">Display Date</button>

onclick - When button is clicked

<br>

<html>
<head>
<script>
function myFunction() {
    document.getElementById("demo").innerHTML = "Hello World";
}
</script>
</head>
<body>

<p>Click the button to trigger a function.</p>

<button onclick="myFunction()">Click me</button>

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


ondblclick -

<br>

<html>
<head>
<script>
function myFunction() {
    document.getElementById("demo").innerHTML = "Hello World";
}
</script>
</head>
<body>

<p ondblclick="myFunction()">Doubleclick this paragraph to trigger a function.</p>

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


onload - When the page has been loaded

<br>

<html>
<head>
<script>
function myFunction() {
    alert("Page is loaded");
}
</script>
</head>

<body onload="myFunction()">

Hello World!

</body> /html>

onload - When an image has been loaded

<br>

<html>
<head>
<script>
function loadImage() {
    alert("Image is loaded");
}
</script>
</head>
<body>
img src="https://www.w3schools.com/js/w3javascript.gif" onload="loadImage()" width="100" height="132">


onerror - When an error occurs when loading an image

<br>

<html>
<head>
<script>
function imgError() {
    alert('The image could not be loaded.');
}
</script>
</head>
<body>

<img src="https://www.w3schools.com/js/image.gif" onerror="imgError()">
<p>A function is triggered if an error occurs when loading the image. The function shows an alert box with a text.
In thi</pre>s example we refer to an image that does not exist, therefore the onerror event occurs.</p>


onunload - When the browser closes the document

<br>

<html>
<head>
<script>
function myFunction() {
    alert("Thank you for visiting W3Schools!");
}
</script>
</head>

<body onunload="myFunction()">

Welcome to my Home Page

<p>Clo</pre>se this window or press F5 to reload the page.</p>

onresize - When the browser window is resized

<br>

<html>
<head>
<script>
function myFunction() {
    var w = window.outerWidth;
    var h = window.outerHeight;
    var txt = "Window size: width=" + w + ", height=" + h;
    document.getElementById("demo").innerHTML = txt;
}
</script>
</head>

<body onresize="myFunction()">

<p>Try to resize the browser window.</p>

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

<p>Note: this example will not work properly in IE8 and earlier. IE8 and earlier do not support the outerWidth/outerHeight propery of the window object.</p>

</body>
/html>

What is the keycode of the key pressed?

<br>

<html>
<head>
<script>
function whichButton(event) {
    document.getElementById("demo").innerHTML = event.keyCode;
}
</script>
</head>

<body onkeyup="whichButton(event)">

<p><b>Note:</b> Make sure the right frame has focus when trying this example!</p>

<p>Click on this page, and press a key on your keyboard.</p>

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


What are the coordinates of the cursor?

<br>

<html>
<head>
<script>
function show_coords(event) {
    document.getElementById("demo").innerHTML =
    "X= " + event.clientX + "<br>Y= " + event.clientY;
}
</script>
</head>

<body>

<p onmousedown="show_coords(event)">
Click this paragraph to display the x and y coordinates of the mouse pointer.</p>

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


What are the coordinates of the cursor, relative to the screen?

<br>

<html>
<head>
<script>
function coordinates(event) {
    document.getElementById("demo").innerHTML =
    "X = " + event.screenX + "<br>Y = " + event.screenY;
}
</script>
</head>
<body>

<p onmousedown="coordinates(event)">
Click this paragraph, to display the x and y coordinates of the cursor, relative to the screen.
</p>

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


Was the shift key pressed?

<br>

<html>
<head>
<script>
function isKeyPressed(event) {
    var text = "The shift key was NOT pressed!";
    if (event.shiftKey == 1) {
        text = "The shift key was pressed!";
    }
    document.getElementById("demo").innerHTML = text;
}
</script>
</head>

<body onmousedown="isKeyPressed(event)">

<p>Click on this paragraph. An alert box will tell you if you pressed the shift key or not.</p>

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


Which event type occurred?

<br>

<html>
<head>
<script>
function getEventType(event) { 
    document.getElementById("demo").innerHTML = event.type;
}
</script>
</head>

<body>

<p onmousedown="getEventType(event)">
Click on this paragraph. A message will tell what type of event was triggered.</p>

<p id=</pre>"demo"></p>


Open a new window when clicking on a button

<br>

<html>
<head>
<script>
function openWin() {
    window.open("https://www.w3schools.com");
}
</script>
</head>

<body>
<form>
<input type="button" value="Open Window" onclick="openWin()">
</form>
</body>
/html>

Open a new window and control its appearance

<br>

<html>
<head>
<script>
function openWin() {
    window.open("https://www.w3schools.com","_blank","toolbar=yes, location=yes, directories=no, status=no, menubar=yes, scrollbars=yes, resizable=no, copyhistory=yes, width=400, height=400");
}
</script>
</head>

<body>
<form>
<input type="button" value="Open Window" onclick="openWin()">
</form>
</body>
/html>

Blur and Focus a new window

<br>

<html>
<head>
<script>
var myWindow;
function openWin() {
    myWindow = window.open("", "", "width=400, height=200");
    myWindow.blur();
}
function blurWin() {
    myWindow.blur();
}
function focusWin() {
    myWindow.focus();
}
</script>
</head>
<body>

<input type="button" value="Open new window" onclick="openWin()">
<input type="button" value="Blur new window" onclick="blurWin()">
<input</pre> type="button" value="Focus new window" onclick="focusWin()">


Close the new window

<br>

<html>
<head>
<script>
var myWindow;
function openWin() {
    myWindow = window.open("", "", "width=400, height=200");
}

function closeWin() {
    myWindow.close();
}
</script>
</head>
<body>

<input type="button" value="Open 'myWindow'" onclick="openWin()" />
<input</pre> type="button" value="Close 'myWindow'" onclick="closeWin()" />


Checks whether the new window has been closed or not

<br>

<html>
<head>

<script>
var myWindow;
function openWin() {
    myWindow = window.open("", "", "width=400 ,height=200");
}

function closeWin() {
    if (myWindow) {
        myWindow.close();
    }
}

function checkWin() {
    msg = ""
    if (!myWindow) {
        msg = "was never opened";
    } else { 
        if (myWindow.closed) { 
            msg = "is closed";
        } else {
            msg = "is open";
        }
    
    }
    document.getElementById("msg").innerHTML = 
    "myWindow " + msg;
}
</script>

</head>
<body>

<button onclick="openWin()">Open myWindow</button>
<button onclick="closeWin()">Close myWindow</button>
<button onclick="checkWin()">Is myWindow open?</button>

<br><br>
<div i</pre>d="msg"></div>


Write some text to the source (parent) window

<br>

<html>
<head>
<script>
function openWin() {
    var myWindow = window.open("", "", "width=400, height=200");
    myWindow.opener.document.getElementById("demo").innerHTML = 
    "A new window has been opened.";
}
</script>
</head>
<body>

<button onclick="openWin()">Open myWindow</button>

<p id=</pre>"demo"></p>


Move the new window relative to its current position

<br>

<html>
<head>
<script>
var myWindow;
function openWin() {
    myWindow=window.open("", "", "width=400, height=200");
}
function moveWin() {
    myWindow.moveBy(250, 250)
}
</script>
</head>
<body>

<input type="button" value="Open myWindow" onclick="openWin()" />
<br><br>
<input</pre> type="button" value="Move myWindow" onclick="moveWin()" />


Move the new window to the specified position

<br>

<html>
<head>
<script>
var myWindow;
function openWin() {
    myWindow=window.open("", "", "width=400, height=200");
}

function moveWin() {
    myWindow.moveTo(300, 0);
    myWindow.focus();
}
</script>
</head>
<body>

<input type="button" value="Open myWindow" onclick="openWin()" />
<br><br>
<input</pre> type="button" value="Move myWindow" onclick="moveWin()" />


Print the current page

<br>

<html>
<head>
<script>
function printPage() {
    window.print();
}
</script>
</head>
<body>

<input</pre> type="button" value="Print this page" onclick="printPage()" />


Resize a window by the specified pixels

<br>

<html>
<head>
<script>
var w;
function openwindow() {
    w = window.open('','', 'width=100,height=100');
    w.focus();
}

function myFunction() {
    w.resizeBy(50, 50);
    w.focus();
}

</script>
</head>
<body>

<button onclick="openwindow()">Create window</button>
<butto</pre>n onclick="myFunction()">Resize window</button>


Resize a window to a specified size

<br>

<html>
<head>
<script>
var w;
function openwindow() {
    w = window.open('','', 'width=100,height=100');
    w.focus();
}

function myFunction() {
    w.resizeTo(500, 500);
    w.focus();
}

</script>
</head>
<body>

<button onclick="openwindow()">Create window</button>
<butto</pre>n onclick="myFunction()">Resize window</button>


Scroll the content by the specified number of pixels

<br>

<html>
<head>
<script>
function scrollWindow() {
    window.scrollBy(0, 10);
}
</script>
</head>
<body>


<input type="button" onclick="scrollWindow()" value="Scroll" />

Reserved Words

<hr> <p>You cannot use reserved words as variables, labels, or function names:</p> <hr> <br> abstract<br><br> arguments<br><br> boolean<br><br> break<br><br> byte<br><br> case<br><br> catch<br><br> char<br><br> class<br><br> const<br><br> continue<br><br> debugger<br><br> default<br><br> delete<br><br> do<br><br> double<br><br> else<br><br> enum<br><br> eval<br><br> export<br><br> extends<br><br> false<br><br> final<br><br> finally<br><br> float<br><br> for<br><br> function<br><br> goto<br><br> if<br><br> implements<br><br> import<br><br> in<br><br> instanceof<br><br> int<br><br> interface<br><br> let<br><br> long<br><br> native<br><br> new<br><br> null<br><br> package<br><br> private<br><br> protected<br><br> public<br><br> return<br><br> short<br><br> static<br><br> super<br><br> switch<br><br> synchronized<br><br> this<br><br> throw<br><br> throws<br><br> transient<br><br> true<br><br> try<br><br> typeof<br><br> var<br><br> void<br><br> volatile<br><br> while<br><br> with<br><br> yield</pre>br><br>

Scroll the content to a specified position

<br>

<html>
<head>
<script>
function scrollWindow() {
    window.scrollTo(0, 100);
}
</script>
</head>
<body>

<input type="button" onclick="scrollWindow()" value="Scroll" />

Reserved Words

<hr> <p>You cannot use reserved words as variables, labels, or function names:</p> <hr> <br> abstract<br><br> arguments<br><br> boolean<br><br> break<br><br> byte<br><br> case<br><br> catch<br><br> char<br><br> class<br><br> const<br><br> continue<br><br> debugger<br><br> default<br><br> delete<br><br> do<br><br> double<br><br> else<br><br> enum<br><br> eval<br><br> export<br><br> extends<br><br> false<br><br> final<br><br> finally<br><br> float<br><br> for<br><br> function<br><br> goto<br><br> if<br><br> implements<br><br> import<br><br> in<br><br> instanceof<br><br> int<br><br> interface<br><br> let<br><br> long<br><br> native<br><br> new<br><br> null<br><br> package<br><br> private<br><br> protected<br><br> public<br><br> return<br><br> short<br><br> static<br><br> super<br><br> switch<br><br> synchronized<br><br> this<br><br> throw<br><br> throws<br><br> transient<br><br> true<br><br> try<br><br> typeof<br><br> var<br><br> void<br><br> volatile<br><br> while<br><br> with<br><br> yield</pre>br><br>

The visitor's screen: Width

<br>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 
"Screen width is " + screen.width;
</script>


The visitor's screen: Height

<br>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 
"Screen height is " + screen.height;
</script>


The visitor's screen: Available Width

<br>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 
"Available screen width is " + screen.availWidth;
</script>


The visitor's screen: Available Height

<br>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 
"Available screen height is " + screen.availHeight;
</script>


The visitor's screen: Color Depth

<br>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 
"Screen color depth is " + screen.colorDepth;
</script>


The visitor's screen: Pixel Depth

<br>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 
"Screen pixel depth is " + screen.pixelDepth;
</script>


Return the hostname and port of the current URL

<br>

JavaScript

<h3>The window.location object</h3> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = "Page hostname is: " + window.location.hostname; </script>

Return the entire URL of the current page

<br>

JavaScript

<h3>The window.location object</h3> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = "The full URL of this page is:<br>" + window.location.href; </script>

Return the path name of the current URL

<br>

JavaScript

<h3>The window.location object</h3> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = "Page path is: " + window.location.pathname; </script>

Return the protocol portion of the current URL

<br>

JavaScript

<h3>The window.location object</h3> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = "The page protocol is: " + window.location.protocol; </script>

Load a new document

<br>

JavaScript

<h3>The window.location object</h3> <input type="button" value="Load new document" onclick="newDoc()"> <script> function newDoc() { window.location.assign("https://www.w3schools.com") } </script>

Replace the current document

<br>

<button onclick="window.location.replace('https://www.w3schools.com')">
Replac</pre>e document</button>


Break out of a frame

<br>

<html>
<head>
<script>
function breakout() {
    if (window.top != window.self) {
        window.top.location = "tryjs_breakout.htm";
    }
}
</script>
</head>
<body>

<input</pre> type="button" onclick="breakout()" value="Break out of frame!">


Display the number of URLs in the history list

<br>

<p>Display the number of URLs in the history list:</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
    document.getElementById("demo").innerHTML = history.length;
}
</script>


Create a back button on a page

<br>

<html>
<head>
<script>
function goBack() {
    window.history.back()
}
</script>
</head>
<body>

<button onclick="goBack()">Go Back</button>

<p>Clicking on the Back button here will not result in any action, because there is no previous URL in</pre> the history list.</p>


Create a forward button on a page

<br>

<html>
<head>
<script>
function goForward() {
    window.history.forward()
}
</script>
</head>
<body>

<button onclick="goForward()">Go Forward</button>

<p>Clicking on the Forward button here will not result in any action, because there is no next URL in</pre> the history list.</p>


Load a specific URL from the history list

<br>

<html>
<head>
<script>
function goBack() {
    window.history.go(-2)
}
</script>
</head>
<body>

<button onclick="goBack()">Go 2 pages back</button>

<p>Clicking on the "Go 2 pages back" button here will not result in any action, because there is no pre</pre>vious URL in the history list.</p>


Is cookies enabled in the visitor's browser?

<br>

The Navigator Object

<p>The cookieEnabled property returns true if cookies are enabled:</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = "navigator.cookieEnabled is " + navigator.cookieEnabled; </script>

What is the name of the visitor's browser?

<br>

JavaScript Navigator

<p>The appCodeName property returns the code name of the browser.</p> <p>Do not rely on it! "Mozilla" is the application code name for both Chrome, Firefox, IE, Safari, and Opera.</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = "navigator.appCodeName is " + navigator.appCodeName; </script>

What is the engine name of the visitor's browser?

<br>

The Navigator Object

<p>The product property returns the product name of the browser.</p> <p>Do not rely on it! Most browsers returns "Gecko" as product name!</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = "navigator.product is " + navigator.product; </script>

What is the version information of the visitor's browser?

<br>

The Navigator Object

<p>The appVersion property returns version information about the browser:</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = navigator.appVersion; </script>

What is user agent information of the visitor's browser?

<br>

The Navigator Object

<p>The userAgent property returns the user-agent header sent by the browser to the server:</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = navigator.userAgent; </script>

What is the platform of the visitor's browser?

<br>

The Navigator Object

<p>The platform property returns the browser platform (operating system):</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = "navigator.platform is " + navigator.platform; </script>

What is the language of the visitor's browser?

<br>

The Navigator Object

<p>The language property returns the browser's language:</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = "navigator.language is " + navigator.language; </script>

Is Java enabled in the visitor's browser?

<br>

The Navigator Object

<p>The javaEnabled() method returns true if Java is enabled:</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = "javaEnabled is " + navigator.javaEnabled(); </script>

Display an alert box

<br>

JavaScript Alert

<button onclick="myFunction()">Try it</button> <script> function myFunction() { alert("I am an alert box!"); } </script>

Demonstrate line breaks in an alert box

<br>

JavaScript

<p>Line-breaks in a popup box.</p> <butto</pre>n onclick="alert('Hello\nHow are you?')">Try it</button>

Display a confirm box

<br>

JavaScript Confirm Box

<button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> function myFunction() { var txt; if (confirm("Press a button!")) { txt = "You pressed OK!"; } else { txt = "You pressed Cancel!"; } document.getElementById("demo").innerHTML = txt; } </script>

Display a prompt box

<br>

JavaScript Prompt

<button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> function myFunction() { var txt; var person = prompt("Please enter your name:", "Harry Potter"); if (person == null || person == "") { txt = "User cancelled the prompt."; } else { txt = "Hello " + person + "! How are you today?"; } document.getElementById("demo").innerHTML = txt; } </script>

Simple timing

<br>

<p>Click "Try it". Wait 3 seconds, and the page will alert "Hello".</p>

<button onclick="setTimeout(myFunction, 3000);">Try it</button>

<script>
function myFunction() {
    alert('Hello');
}
</script>


Another simple timing

<br>

<button onclick="timedText()">Try it</button>

<p id="demo">Click on "Try it". I will display when two, four, and six seconds have passed.</p>

<script>
function timedText() {
    setTimeout(myTimeout1, 2000) 
    setTimeout(myTimeout2, 4000) 
    setTimeout(myTimeout3, 6000) 
}
function myTimeout1() {
    document.getElementById("demo").innerHTML = "2 seconds";
}
function myTimeout2() {
    document.getElementById("demo").innerHTML = "4 seconds";
}
function myTimeout3() {
    document.getElementById("demo").innerHTML = "6 seconds";
}
</script>


Timing event in an infinite loop

<br>

<button onClick="setInterval(myCounter, 1000)">Start counter!</button>

<p id="demo">Click on the button above and I will count forever.</p>

<script>
var c = 0;
function myCounter() {
    document.getElementById("demo").innerHTML = ++c;
}
</scri</pre>pt> 


Timing event in an infinite loop - with a Stop button

<br>

<button onClick="myTimer = setInterval(myCounter, 1000)">Start counter!</button>

<p id="demo">Click on the button above and I will count forever.</p>

<button onClick="clearInterval(myTimer)">Stop counter!</button>

<script>
var c = 0;
function myCounter() {
    document.getElementById("demo").innerHTML = ++c;
}
</scri</pre>pt> 


A clock created with a timing event

<br>

<html>
<head>
<script>
function startTime() {
    var today = new Date();
    var h = today.getHours();
    var m = today.getMinutes();
    var s = today.getSeconds();
    m = checkTime(m);
    s = checkTime(s);
    document.getElementById('txt').innerHTML =
    h + ":" + m + ":" + s;
    var t = setTimeout(startTime, 500);
}
function checkTime(i) {
    if (i < 10) {i = "0" + i};  // add zero in front of numbers < 10
    return i;
}
</script>
</head>

<body onload="startTime()">

<div i</pre>d="txt"></div>


Set and stop a timer with setInterval() and clearInterval()

<br>

<p id="demo">Clock</p>

<button onclick="clearInterval(myTimer)">Stop</button>

<script>
var myTimer = setInterval(myClock, 1000);
function myClock() {
    document.getElementById("demo").innerHTML =
    new Date().toLocaleTimeString();
}
</script>


Create a welcome cookie

<br>

<html>
<head>
<script>

function setCookie(cname,cvalue,exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires=" + d.toGMTString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

function checkCookie() {
    var user=getCookie("username");
    if (user != "") {
        alert("Welcome again " + user);
    } else {
       user = prompt("Please enter your name:","");
       if (user != "" && user != null) {
           setCookie("username", user, 30);
       }
    }
}

</script>
</head>
<body onload="checkCookie()">
</body>
</html>