JavaScript Examples
What can JavaScript do?
JavaScript can change HTML contentJavaScript can change HTML attributesJavaScript can change CSS styleJavaScript can hide HTML elementsJavaScript can show hidden HTML elements
Where to Insert JavaScript
JavaScript in <head>JavaScript in <body>JavaScript in an external fileJavaScript in an external urlJavaScript in an external folder
JavaScript Output
Writing into the HTML outputWriting into an HTML elementWriting into an window alert boxWriting into the browser console
JavaScript Syntax
JavaScript statementsJavaScript numbersJavaScript stringsJavaScript variablesJavaScript operatorsJavaScript assignmentJavaScript expressions (using constants)JavaScript expressions (using strings)JavaScript expressions (using variables)JavaScript keywordsJavaScript commentsJavaScript is case sensitive
JavaScript Statements
JavaScript statements are commands to the browserJavaScript code is a sequence of statementsJavaScript statements are separated with semicolonMultiple statement on one line is allowedJavaScript statements can be grouped together in code blocksYou can break a code line after an operator or a comma.
JavaScript Comments
Single line commentsSingle line comments at the end of a lineMultiple lines commentsSingle line comment to prevent executionMultiple lines comment to prevent execution
JavaScript Variables
JavaScript variablesJavaScript variables as algebraJavaScript numbers and stringsJavaScript var keyword.Declaring many variables in one statementDeclaring many variables multilineA variable without a value returns the value undefinedRe-declaring a variable will not destroy the valueAdding JavaScript numbersAdding JavaScript stringsAdding strings and numbers
JavaScript Arithmetic
The addition (+) operatorThe subtraction (-) operatorThe multiplication (*) operatorThe division (/) operatorThe modulus (%) operatorThe increment (++) operatorThe decrement (--) operator
JavaScript Assignment
The = assignment operatorThe += assignment operatorThe -= assignment operatorThe *= assignment operatorThe /= assignment operatorThe %= assignment operator
JavaScript String Concatenation
Adding two strings together using the concatenating (+) operatorAdding two strings together with a space in the first stringAdding two strings together with a space in betweenAdding two strings together using using the += operatorAdding strings and numbers
JavaScript Data Types
Declare (create) stringsDeclare (create) numbersDeclare (create) an arrayDeclare (create) an objectFind the type of a variableAdding two numbers and a stringAdding a string and two numbersAn undefined variableAn empty variable
JavaScript Objects
Create a JavaScript variableCreate a JavaScript objectCreate a person object (single line)Create a person object (multiple lines)Access object properties using .propertyAccess object properties using [property]Access a function property as a methodAccess a function property as a property
JavaScript Functions
A simple functionA function with an argumentA function with an argument 2A function that returns a valueA function that converts Fahrenheit to CelsiusA function call without ()
JavaScript Events
An onclick event changes an HTML elementAn onclick event changes its own elementAn onclick event calls a function
JavaScript Strings
Strings can be written with single or double quotes.Show some string examplesBackslash before quotes accepts quotes as quotes.Find the length of a stringYou can break text string with a backslash.You cannot break code with a backslash.Find the position of the first occurrence of a textin a string - indexOf()Search for a text in a string and return the text if found- match()Replace characters in a string - replace()Convert string to upper case - toUpperCase()Convert string to lower case - toLowerCase()Split a string into an array - split()
JavaScript Numbers
Numbers can be written with or without decimalsExtra large or extra small numbers can be written with exponent notationNumber are considered accurate only up to 15 digitsFloating point arithmetic is not always 100% accurateBut it helps to multiply and divide by 10Adding two numbers results in a new numberAdding two numeric strings results in a concatenated stringAdding a number and a numeric string also results in a concatenated stringAdding a numeric string and a number also results in a concatenated stringCommon mistake when adding strings and numbers 1Common mistake when adding strings and numbers 2JavaScript will try to convert strings to numbers when dividingJavaScript will try to convert strings to numbers when multiplyingJavaScript will try to convert strings to numbers when subtractingJavaScript will NOT convert strings to numbers when addingA number divided by a string is NaN (Not a Number)A number divided by a numeric string is a numberThe global JavaScript function isNaN() returns if a value is a numberUsing NaN in a mathematical operation will always return NaNUsing NaN in a mathematical string operation will concatenate NaNNaN (Not a Number) is a number (Yes! typeof NaN returns number)Infinity is returned if you calculate a number outside the largest possible numberDivision by zero also generates InfinityInfinity is a number (typeof Infinity returns number)Constants, preceded by 0x, are interpreted as hexadecimalThe toString() method can output numbers as hex, octal, and binaryNumbers can be objectsNumbers and objects cannot be safely comparedObjects and objects cannot be safely compared
JavaScript Number Methods
The toString() method converts a number to a stringThe valueOf() method returns a number as a numberThe toExponential() returns a number with exponential notationThe toFixed() method rounds a number to a number of digitsThe toPrecision() method a number written with a specified lengthThe global method Number() converts variables to numbersThe global method Number() can even convert dates to numbersThe global method parseInt() converts strings to numbersThe global method parseFloat() converts strings to numbersMAX_VALUE returns the largest possible number in JavaScriptMIN_VALUE returns the smallest possible number in JavaScriptPOSITIVE_INFINITY represents infinityPOSITIVE_INFINITY is returned on overflowNEGATIVE_INFINITY represents negative infinityNEGATIVE_INFINITY is returned on overflowNaN Represents "Not-a-Number"Arithmetic performed on a string will result in NaNUsing a Number property on a variable will return undefined
JavaScript Maths
Math.PI returns the value of PIMath.round(x) returns the rounded value of xMath.pow(x, y) returns the value of x to the power of yMath.sqrt(x) returns the square root of xMath.abs(x) returns the absolute (positive) value of xMath.ceil(x) returns the value of x rounded upMath.floor(x) returns the value of x rounded downMath.sin(x) returns the sin of the angle x (given in radians)Math.cos(x) returns the cosin of the angle x (given in radians)Math.max() return the number with the highest value from a list of argumentsMath.min() to return the number with the lowest value from a list of argumentsConverting Celsius to Fahrenheit
JavaScript Random
Math.random() returns a random number between 0 (included) and 1 (excluded)How to return a random integer between 0 and 9 (both included)How to return a random integer between 0 and 10 (both included)How to return a random integer between 0 and 99 (both included)How to return a random integer between 0 and 100 (both included)How to return a random integer between 1 and 10 (both included)How to return a random integer between 1 and 100 (both included)How to return a random integer between x (included) and y (excluded)How to return a random integer between x and y (both included)
JavaScript Dates
Use Date() to display today's date and timeUse getFullYear() display the yearUse getTime() to calculate the number of milliseconds since 1970Use setFullYear() to set a specific dateUse toUTCString() to convert today's date (according to UTC) to a stringUse getDay() to display the weekday as a numberUse getDay() and an array to display the weekday as a nameDisplay a clock
JavaScript Arrays
Create an array ICreate an array IIAccess an array elementChange an array elementAccess a full arrayFind the length of an arrayLoop through an arrayAdd an element to an arrayAdd undefined "holes" to an arrayHow to recognize an array IHow to recognize an array II
JavaScript Array Methods
Add an element to an arrayRemove the last element of an array - pop()Join all elements of an array into a string - join()Join two arrays - concat()Join three arrays - concat()Add an element to position 2 in an array - splice()Convert an array to a string - toString()Add new elements to the beginning of an array - unshift()Remove the first element of an array - shift()Select elements from an array - slice()
JavaScript Array Sort
Sort an array in ascending orderSort an array in descending orderSort an array of numbers ascendingSort an array of numbers descendingSort numbers (alphabetically or numerically)Sort array numbers in random orderFind the lowest number in an arrayFind the highest number in an arrayFind the lowest number in an array using Math.min()Find the highest number in an array using Math.max()Using a "homemade" myArrayMin methodUsing a "homemade" myArrayMax methodSort objects by numeric propertiesSort objects by string properties
JavaScript Array Iteration
Array.forEach()Array.map()Array.filter()Array.reduce()Array.reduceRight()Array.every()Array.some()Array.indexOf()Array.lastIndexOf()Array.find()Array.findIndex()
JavaScript Type Conversion
Display the typeof all variable typesDisplay the constructor of all variable typesConvert a number to a string using String()Convert a number to a string using toString()Find out if a variable is an arrayFind out if a variable is a date
JavaScript Booleans
Display the value of Boolean(10 > 9)Display the value of 10 > 9Everything with a real value is trueThe Boolean value of zero is falseThe Boolean value of minus zero is falseThe Boolean value of an empty string is falseThe Boolean value of undefined is falseThe Boolean value of null is falseThe Boolean value of false is falseThe Boolean value of NaN is false
JavaScript Comparisons
Assign 5 to x, and display the value of (x == 8)Assign 5 to x, and display the value of (x == 5)Assign 5 to x, and display the value of (x === 5)Assign 5 to x, and display the value of (x === "5")Assign 5 to x, and display the value of (x != 8)Assign 5 to x, and display the value of (x !== 5)Assign 5 to x, and display the value of (x !== "5")Assign 5 to x, and display the value of (x > 8)Assign 5 to x, and display the value of (x < 8)Assign 5 to x, and display the value of (x >= 8)Assign 5 to x, and display the value of (x <= 8)
JavaScript Conditionals
JavaScript Loops
For loopLooping an ArrayLooping through HTML headersWhile loopDo While loopBreak a loopBreak and continue a loopUse a for...in statement to loop through the elements of an object
JavaScript Error Handling
JavaScript Regular Expressions
JavaScript Objects
Creating a JavaScript variableCreating a JavaScript objectCreating a JavaScript object (single line)Creating a JavaScript object (multiple lines)Creating a JavaScript object using newCreating JavaScript objects using a constructorCreating built-in JavaScript objectsThe best way to create JavaScript variablesJavaScript objects are mutable
JavaScript Object Properties
Accessing properties using .propertyAccessing properties using [property]Accessing properties using for inAdding new properties to existing objectsDeleting properties from objects
JSON Objects
Accessing properties using .propertyAccessing properties using [property]Looping through propertiesLooping through property valuesAccess nested JSON objectsModify values using the dot notationModify values using the bracket notationDelete object properties
JSON Object Properties Explained
JSON Arrays
Accessing array valuesLooping through an array using for-inLooping through an array using forAccess nested JSON arraysModify array valuesDelete array items
JSON Parse
Use JSON parseUsing JSON parse in an AJAX exampleUsing JSON parse on an arrayParsing datesParsing dates using the reviver functionParsing functions
JSON Stringify
Use JSON stringifyUsing JSON stringify on an arrayStringify datesStringify functionsStringify functions using the toString() method
JSON PHP
Get JSON from a php fileGet JSON array from phpGet JSON from a databaseLoop through the result from a databaseSend JSON using POST method
JSON HTML
Make an HTML table based on JSON dataMake a dynamic HTML TableMake an HTML drop down list based on JSON data
JSON JSONP
Simple JSONP exampleCreate a dynamic script tagJSONP example with dynamic resultJSONP example with a callback function

