document.getElementById ( " demo " ) . innerHTML = " Hello JavaScript " ; document.getElementById ( ' demo ' ) . innerHTML = ' Hello JavaScript ' ;
document.getElementById("demo").style.fontSize = "35px";
document.getElementById("demo").style.display = "none";
document.getElementById("demo").style.display = "block";
<script> document.getElementById("demo").innerHTML = "My First JavaScript"; </script>
function myFunction ( ) { document.getElementById("demo").innerHTML = "Paragraph changed."; } <p id="demo">A Paragraph>/p> <button type="button" onclick="myFunction()">Try it>/button>
<p id="demo">A Paragraph </p> <button type="button" onclick="myFunction()">Try it</button> function myFunction ( ) { document.getElementById ( " demo " ).innerHTML = "Paragraph changed."; }
<script src="myScript.js">
<script src="myScript1.js"script <script src="myScript2.js"/script
<script src="https://www.w3schools.com/js/myScript1.js"> </script>
<script src="/js/myScript1.js"></script>
<script src="myScript1.js"></script>
<!DOCTYPE html> <html> <body> <h1>My First Web Page</h1> <p>My First Paragraph</p> <p id="demo"></p> <script> document.getElementById ( " demo " ).innerHTML = 5 + 6; </script> </body> <html>
<!DOCTYPE html> <html> <body> <h1>My First Web Page</h1> <p>My first paragraph.</p> <script> document.write(5 + 6); </script> </body> <html>
<!DOCTYPE html> <html> <body> <h1>My First Web Page</h1> <p>My first paragraph.</p> <button type="button" onclick="document.write(5 + 6)">Try it</button> </body> <html>
<!DOCTYPE html> <html> <body> <h1>My First Web Page</h1> <p>My first paragraph.</p> <script> window.alert(5 + 6); </script> </body> <html>
<!DOCTYPE html> <html> <body> <h1>My First Web Page</h1> <p>My first paragraph.</p> <script> alert(5 + 6); </script> </body> <html>
<!DOCTYPE html> <html> <body> <script> console.log(5 + 6); </script> </body> <html>
<!DOCTYPE html> <html> <body> <button onclick="window.print()">Print this page </body> <html>
var x, y, z; x = 5; y = 6; z = x + y;
document.getElementById ( " demo " ).innerHTML = "Hello Dolly.";
var a, b, c; a = 5; b = 6; c = a + b;
a = 5; b = 6; c = a + b;
var person = “ Hege “; var person = “ Hege "; var x = y + z ;
document.getElementById ( " demo " ).innerHTML = Hello Dolly!;
function myFunction ( ) { document.getElementById("demo1").innerHTML = "Hello Dolly!"; document.getElementById("demo2").innerHTML = "How are you?"; }
abstract | explanation |
arguments | explanation |
await | explanation |
boolean | explanation |
break | explanation |
byte | explanation |
case | explanation |
catch | explanation |
char | explanation |
class* | explanation |
const | explanation |
continue | explanation |
debugger | explanation |
default | explanation |
delete | explanation |
do | explanation |
double | explanation |
else | explanation |
enum* | explanation |
eval | explanation |
export* | explanation |
extends* | explanation |
FALSE | explanation |
final | explanation |
finally | explanation |
float | explanation |
for | explanation |
function | explanation |
goto | explanation |
if | explanation |
implements | explanation |
import* | explanation |
in | explanation |
instanceof | explanation |
int | explanation |
interface | explanation |
let* | explanation |
long | explanation |
native | explanation |
new | explanation |
null | explanation |
package | explanation |
private | explanation |
protected | explanation |
public | explanation |
return | explanation |
short | explanation |
static | explanation |
super* | explanation |
switch | explanation |
synchronized | explanation |
this | explanation |
throw | explanation |
throws | explanation |
transient | explanation |
TRUE | explanation |
try | explanation |
typeof | explanation |
var | explanation |
void | explanation |
volatile | explanation |
while | explanation |
with | explanation |
yield | explanation |
var x, y, z; x = 5; y = 6; z = x + y;
John Doe John Doe'
var x; h3>Operators /h3> x = 6;
(5 + 6) * 10
var x, y; h3>Expressions /h3> x = 5 ; y = 6 ;
document.getElementById("myH").innerHTML = "My First Page"; document.getElementById("myP").innerHTML = "My first paragraph.";
var x = 5; var y = x + 2;
document.getElementById("myH").innerHTML = "My First Page"; document.getElementById("myP").innerHTML = "My first paragraph.";
document.getElementById("myP").innerHTML = "My first paragraph.";
document.getElementById("myH").innerHTML = "My First Page"; document.getElementById("myP").innerHTML = "My first paragraph.";
// Change heading: document.getElementById("myH").innerHTML = "My First Page";
var x = 5; // Declare x, give it the value of 5 var y = x + 2; // Declare y, give it the value of x + 2
Multi-line comments start with /* and end with */. Any text between /* and */ will be ignored by JavaScript. This example uses a multi-line comment (a comment block) to explain the code:
/* 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.";
//document.getElementById("myH").innerHTML = "My First Page"; document.getElementById("myP").innerHTML = "My first paragraph.";
/* document.getElementById("myH").innerHTML = "My First Page"; document.getElementById("myP").innerHTML = "My first paragraph."; */
var x = 5; var y = 6; var z = x + y; //z stores the value 11
var price1 = 5; var price2 = 6; var total = price1 + price2;
var x = 5; var y = 2; var z = x + y;
var x = 10;
var x = 5; var y = 2; var z = x + y;
var x = 5; var y = 2; var z = x * y;
Operator Description + Addition - Subtraction * Multiplication ** Exponentiation (ES2016) % Modulus (Division Remainder) ++ Increment -- Decrement
Operator Example Same As x = y += x += y x = x + y -= x -= y x = x - y *= x *= y x = x * y /= x /= y x = x / y %= x %= y x = x % y **= x **= y x = x ** y
var x = 10; x += 5;
var txt1 = "John"; var txt2 = "Doe"; var txt3 = txt1 + " " + txt2;
var txt1 = "What a very "; txt1 += "nice day";
var x = 5 + 5; var y = "5" + 5; var z = "Hello" + 5;
Operator Description equal to equal value and equal type != not equal !== not equal value or not equal type > greater than < less than >= greater than or equal to <= less than or equal to ? ternary operator
Operator Description && logical and || logical or ! logical not
Operator Description typeof Returns the type of a variable instanceof Returns true if an object is an instance of an object type
Operator Description Example Same as Result Decimal & AND 5 & 1 0101 & 0001 1 | OR 5 | 1 0101 | 0001 101 ~ NOT ~ 5 ~0101 1010 ^ XOR 5 ^ 1 0101 ^ 0001 100 << Zero fill left shift 5 << 1 0101 << 1 1010 >>Signed right shift 5 >> 1 0101 >> 1 10 2 >>>Zero fill right shift 5 >>> 1 0101 >>> 1 10 2
00000000000000000000000000000101 will return 11111111111111111111111111111010
var pi = 3.14; var person = "John Doe"; var answer = 'Yes I am!';
p id="demo"> script> var carName = "Volvo"; document.getElementById("demo").innerHTML = carName; /script>
var person = "John Doe", carName = "Volvo", price = 200; var person = "John Doe", carName = "Volvo", price = 200; Value = undefined
var carName;
var carName = "Volvo"; var carName;
var x = 5 + 2 + 3;
var x = "John" + " " + "Doe";
var x = "5" + 2 + 3;
var x = 2 + 3 + "5";
var $$$ = "Hello World"; var $ = 2; var $myMoney = 5;
var _lastName = "Johnson"; var _x = 2; var _100 = 5;
5 * 10 x * 10
John + " " + "Doe"
var x, y; x = 5 + 6; y = x * 10;
var x = 5; var x = 6;
var lastname, lastName; lastName = "Doe"; lastname = "Peterson";
Operator Description + Addition - Subtraction * Multiplication ** Exponentiation (ES2016) % Modulus (Remainder) ++ Increment -- Decrement
var x = 100 + 50;
var x = a + b;
var x = (100 + 50) * a;
Operand Operator Operand 100 + 50
var x = 5; var y = 2; var z = x + y;
var x = 5; var y = 2; var z = x - y;
var x = 5; var y = 2; var z = x * y;
var x = 5; var y = 2; var z = x / y;
var x = 5; var y = 2; var z = x % y;
var x = 5; x++; var z = x;
var x = 5; x--; var z = x;
var x = 5; var z = x ** 2; x ** y produces the same result as Math.pow(x,y):
var x = 5; var z = Math.pow(x,2);
var x = 100 + 50 * 3;
var x = (100 + 50) * 3;
var x = 100 + 50 - 3;
Value Operator Description Example 20 ( ) Expression grouping (3 + 4) 19 . Member person.name 19 [] Member person["name"] 19 () Function call myFunction() 19 new Create new Date() 17 ++ Postfix Increment i++ 17 -- Postfix Decrement i-- 16 ++ Prefix Increment ++i 16 -- Prefix Decrement --i 16 ! Logical not !(x==y) 16 typeof Type typeof x 15 ** Exponentiation (ES2016) 10 ** 2 14 * Multiplication 10 * 5 14 / Division 10 / 5 14 % Division Remainder 10 % 5 13 + Addition 10 + 5 13 - Subtraction 10 - 5 12 << Shift left x << 2 12 >>Shift right x >> 2 12 >>>Shift right (unsigned) x >>> 2 11 < Less than x < y 11 <= Less than or equal x <= y 11 >Greater than x > y 11 >= Greater than or equal x >= y 11 in Property in Object "PI" in Math 11 instanceof Instance of Object instanceof Array 10 Equal x == y 10 Strict equal x === y 10 != Unequal x != y 10 !== Strict unequal x !== y 9 & Bitwise AND x & y 8 ^ Bitwise XOR x ^ y 7 | Bitwise OR x | y 6 && Logical AND x && y 5 || Logical OR x || y 4 ? : Condition ? "Yes" : "No" 3 += Assignment x += y 3 /= Assignment x /= y 3 -= Assignment x -= y 3 *= Assignment x *= y 3 %= Assignment x %= y 3 <<= Assignment x <<= y 3 >>= Assignment x >>= y 3 >>>= Assignment x >>>= y 3 &= Assignment x &= y 3 ^= Assignment x ^= y 3 |= Assignment x |= y 2 yield Pause Function yield x 1 , Comma 5 , 6
Operator Example Same As = x = y x = y += x += y x = x + y -= x -= y x = x - y *= x *= y x = x * y /= x /= y x = x / y %= x %= y x = x % y <<= x <<= y x = x << y >>= x >>= y x = x >> y >>>= x >>>= y x = x >>> y &= x &= y x = x & y ^= x ^= y x = x ^ y |= x |= y x = x | y **= x **= y x = x ** y
var x = 10;
var x = 10; x += 5;
var x = 10; x -= 5;
var x = 10; x *= 5;
var x = 10; x /= 5;
var x = 10; x %= 5;
var length = 16; var lastName = "Johnson"; var x = {firstName:"John", lastName:"Doe"};
var x = 16 + "Volvo";
var x = "16" + "Volvo";
var x = 16 + "Volvo";
var x = "Volvo" + 16;
var x = 16 + 4 + "Volvo";
var x; x = 5; x = "John";
var carName1 = "Volvo XC60"; var carName2 = 'Volvo XC60';
var answer1 = "It's alright"; var answer2 = "He is called 'Johnny'"; var answer3 = 'He is called "Johnny"';
var x1 = 34.00; var x2 = 34;
var y = 123e5; var z = 123e-5;
var x = 5; var y = 5; var z = 6; (x == y) (x == z)
var cars = ["Saab", "Volvo", "BMW"];
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
typeof " typeof "John" typeof "John Doe"
typeof 0 typeof 314 typeof 3.14 typeof (3) typeof (3 + 4)
var car;
car = undefined;
var car = "; Null
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}; person = null;
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}; person = undefined;
typeof undefined typeof null null === undefined null == undefined
typeof "John" typeof 3.14 typeof true typeof false typeof x
typeof {name:'John', age:34} typeof [1,2,3,4] typeof null typeof function myFunc ( ) {}
function myFunction(p1, p2) { return p1 * p2;
(parameter1, parameter2, ...)
function name(parameter1, parameter2, parameter3) { }
var x = myFunction(4, 3); function myFunction(a, b) { return a * b; }
Convert Fahrenheit to Celsius: function toCelsius(fahrenheit) { return (5/9) * (fahrenheit-32); } document.getElementById("demo").innerHTML = toCelsius(77);
function toCelsius(fahrenheit) { return (5/9) * (fahrenheit-32); } document.getElementById("demo").innerHTML = toCelsius;
var x = toCelsius(77); var text = "The temperature is " + x + " Celsius"; var text = "The temperature is " + toCelsius(77) + " Celsius";
function myFunction ( ) { var carName = "Volvo"; }
Object Properties Methods car.name = Fiat car.model = 500 car.weight = 850kg car.color = white car.start ( ) car.drive ( ) car.brake ( ) car.stop ( )
var car = "Fiat";
var car = {type:"Fiat", model:"500", color:"white"};
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
var person = { firstName: "John", lastName: "Doe", age: 50, eyeColor: "blue" } ;
Property Property Value firstName : John lastName Doe age 50 eyeColor: blue
person.lastName;
person["lastName"];
Property Property Value firstName John lastName Doe age 50 eyeColor blue fullName function ( ) {return this.firstName + " " + this.lastName;}
var person = { firstName: "John", lastName : "Doe", id : 5566, fullName : function ( ) { return this.firstName + " " + this.lastName; } };
name = person.fullName ( ) ;
name = person.fullName;
var x = new String ( ) ; var y = new Number ( ) ; var z = new Boolean ( ) ;
element event='some JavaScript'> p>With double quotes: element event="some JavaScript">
button onclick="document.getElementById('demo').innerHTML = Date()">The time is?/button>
button onclick="this.innerHTML = Date()">The time is?/button>
button onclick="displayDate()">The time is?/button>
Event Description onchange An HTML element has been changed onclick The user clicks an HTML element onmouseover The user moves the mouse over an HTML element onmouseout The user moves the mouse away from an HTML element onkeydown The user pushes a keyboard key onload The browser has finished loading the page
var x = "John Doe";
var carName1 = "Volvo XC60"; var carName2 = 'Volvo XC60';
var answer1 = "It's alright"; var answer2 = "He is called 'Johnny'"; var answer3 = 'He is called "Johnny"';
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; var sln = txt.length;
var x = "We are the so-called "Vikings" from the north.";
Code Result Description ¥' Single quote ¥"" Double quote ¥¥ ¥ Backslash
var x = "We are the so-called ¥"Vikings¥" from the north.";
var x = 'It¥'s alright.';
var x = "The character ¥¥ is called backslash.";
Code Result ¥b Backspace ¥f Form Feed ¥n New Line ¥r Carriage Return ¥t Horizontal Tabulator ¥v Vertical Tabulator
document.getElementById("demo").innerHTML = Hello Dolly!;
document.getElementById("demo").innerHTML = "Hello Dolly!";
document.getElementById("demo").innerHTML = "Hello " + Dolly!;
document.getElementById("demo").innerHTML = ¥ Hello Dolly!;
var firstName = "John";
var firstName = new String("John"); var x = "John"; var y = new String("John");
var x = "John"; var y = new String("John");
var x = "John"; var y = new String("John");
var x = new String("John"); var y = new String("John");
var x = new String("John"); var y = new String("John");
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; var sln = txt.length;
var str = "Please locate where 'locate' occurs!"; var pos = str.indexOf("locate");
var str = "Please locate where 'locate' occurs!"; var pos = str.lastIndexOf("locate");
var str = "Please locate where 'locate' occurs!"; var pos = str.lastIndexOf("John");
var str = "Please locate where 'locate' occurs!"; var pos = str.indexOf("locate", 15);
var str = "Please locate where 'locate' occurs!"; var pos = str.lastIndexOf("locate", 15);
var str = "Please locate where 'locate' occurs!"; var pos = str.search("locate");
var str = "Apple, Banana, Kiwi"; var res = str.slice(7, 13);
var str = "Apple, Banana, Kiwi"; var res = str.slice(-12, -6);
var res = str.slice(7);
var res = str.slice(-12);
var str = "Apple, Banana, Kiwi"; var res = str.substring(7, 13);
var str = "Apple, Banana, Kiwi"; var res = str.substr(7, 6);
var str = "Apple, Banana, Kiwi"; var res = str.substr(7);
var str = "Apple, Banana, Kiwi"; var res = str.substr(-4);
str = "Please visit Microsoft!"; var n = str.replace("Microsoft", "W3Schools");
str = "Please visit Microsoft and Microsoft!"; var n = str.replace("Microsoft", "W3Schools");
str = "Please visit Microsoft!"; var n = str.replace("MICROSOFT", "W3Schools");
str = "Please visit Microsoft!"; var n = str.replace(/MICROSOFT/i, "W3Schools");
str = "Please visit Microsoft and Microsoft!"; var n = str.replace(/Microsoft/g, "W3Schools");
var text1 = "Hello World!"; var text2 = text1.toUpperCase ( ) ;
var text1 = "Hello World!"; var text2 = text1.toLowerCase ( ) ;
var text1 = "Hello"; var text2 = "World"; var text3 = text1.concat(" ", text2);
var text = "Hello" + " " + "World!"; var text = "Hello".concat(" ", "World!");
String.trim ( )
var str = "Hello World!"; alert(str.trim ( ) );
var str = " Hello World! "; alert(str.replace(/^[¥s¥uFEFF¥xA0]+|[¥s¥uFEFF¥xA0]+$/g, ''));
if (!String.prototype.trim) { String.prototype.trim = function ( ) { return this.replace(/^[¥s¥uFEFF¥xA0]+|[¥s¥uFEFF¥xA0]+$/g, ''); }; } var str = " Hello World! "; h3>JavaScript String Padding/h3>
let str = "5"; str = str.padStart(4,0);
let str = "5"; str = str.padEnd(4,0);
Chrome 57 Edge 15 Firefox 48 Safari 10 Opera 44 Mar 2017 Apr 2017 Aug 2016 Sep 2016 Mar 2017
charAt(position) charCodeAt(position)
var str = "HELLO WORLD"; str.charAt(0);
var str = "HELLO WORLD"; str.charCodeAt(0);
var str = "HELLO WORLD"; str[0];
var str = "HELLO WORLD"; str[0] = "A"; str[0];
var txt = "a,b,c,d,e"; txt.split(","); txt.split(" "); txt.split("|");
var txt = "Hello"; txt.split(");
var x = 3.14; var y = 3;
var x = 123e5; var y = 123e-5;
Exponent Sign Value (aka Fraction/Mantissa) 52 bits (0 - 51) 11 bits (52 - 62) 1 bit (63)
var x = 999999999999999; var y = 9999999999999999;
var x = 0.2 + 0.1;
var x = (0.2 * 10 + 0.1 * 10) / 10;
var x = 10; var y = 20; var z = x + y;
var x = "10"; var y = "20"; var z = x + y;
var x = 10; var y = "20"; var z = x + y;
var x = "10"; var y = 20; var z = x + y;
var x = 10; var y = 20; var z = "The result is: " + x + y;
var x = 10; var y = 20; var z = "30"; var result = x + y + z;
var x = 100; var y = "100";
var x = "100"; var y = "10"; var z = x / y;
var x = "100"; var y = "10"; var z = x * y;
var x = "100"; var y = "10"; var z = x - y;
var x = "100"; var y = "10"; var z = x + y;
var x = 100 / "Apple";
var x = 100 / "10";
var x = 100 / "Apple"; isNaN(x);
var x = NaN; var y = 5; var z = x + y;
var x = NaN; var y = "5"; var z = x + y;
typeof NaN;
var myNumber = 2; while (myNumber != Infinity) { myNumber = myNumber * myNumber; }
var x = 2 / 0; var y = -2 / 0;
typeof Infinity;
var x = 0xFF;
var myNumber = 32; myNumber.toString(10); myNumber.toString(32); myNumber.toString(16); myNumber.toString(8); myNumber.toString(2);
var x = 123;
var y = new Number(123); var x = 123; var y = new Number(123);
var x = 500; var y = new Number(500);
var x = 500; var y = new Number(500);
var x = new Number(500); var y = new Number(500);
var x = 123; x.toString ( ) ; (123).toString ( ) ; (100 + 23).toString ( ) ;
var x = 9.656; x.toExponential(2); x.toExponential(4); x.toExponential(6);
var x = 9.656; x.toFixed(0); x.toFixed(2); x.toFixed(4); x.toFixed(6); toFixed(2) is perfect for working with money.
var x = 9.656; x.toPrecision ( ) ; x.toPrecision(2); x.toPrecision(4); x.toPrecision(6);
var x = 123; x.valueOf ( ) ; (123).valueOf ( ) ;(100 + 23).valueOf ( ) ;
Method Description Number ( ) Returns a number, converted from its argument. parseFloat ( ) Parses its argument and returns a floating point number parseInt ( ) Parses its argument and returns an integer
Number(true); Number(false); Number("10"); Number(" 10"); Number("10 "); Number(" 10 "); Number("10.33"); Number("10,33"); Number("10 33"); Number("John");
Number(new Date("2017-09-30"));
parseInt("10"); parseInt("10.33"); parseInt("10 20 30"); parseInt("10 years"); parseInt("years 10");
parseFloat("10"); parseFloat("10.33"); parseFloat("10 20 30"); parseFloat("10 years"); parseFloat("years 10");
Property Description MAX_VALUE Returns the largest number possible in JavaScript MIN_VALUE Returns the smallest number possible in JavaScript POSITIVE_INFINITY Represents infinity (returned on overflow) NEGATIVE_INFINITY Represents negative infinity (returned on overflow)
var x = Number.MAX_VALUE;
var x = Number.MIN_VALUE;
var x = Number.POSITIVE_INFINITY;
var x = 1 / 0;
var x = Number.NEGATIVE_INFINITY;
var x = -1 / 0;
var x = Number.NaN;
var x = 100 / "Apple";
var x = 6; var y = x.MAX_VALUE;
var fruits = [ "Banana", "Orange", "Apple", "Mango"]; fruits.sort ( ) ;
var fruits = [ "Banana", "Orange", "Apple", "Mango"]; fruits.sort ( ) ; fruits.reverse ( ) ;
var points = [40, 100, 1, 5, 25, 10]; points.sort(function(a, b){return a - b});
var points = [40, 100, 1, 5, 25, 10]; points.sort(function(a, b){return b - a});
function ( a, b ) { return a - b }
button onclick="myFunction1()">Sort Alphabetically button onclick="myFunction2()">Sort Numerically p id="demo"> 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>
var points = [40, 100, 1, 5, 25, 10]; points.sort(function(a, b){return 0.5 - Math.random ( ) });
var points = [40, 100, 1, 5, 25, 10]; for (i = points.length -1; i > 0; i--) { j = Math.floor(Math.random ( ) * i) k = points[i] points[i] = points[j] points[j] = k }
var points = [40, 100, 1, 5, 25, 10]; points.sort(function(a, b){return a - b});
var points = [40, 100, 1, 5, 25, 10]; points.sort(function(a, b){return b - a});
function myArrayMax(arr) { return Math.max.apply(null, arr); } Math.max.apply(null, [1, 2, 3]) is equivalent to Math.max(1, 2, 3).
function myArrayMin(arr) { return Math.min.apply(null, arr); } Math.min.apply(null, [1, 2, 3]) is equivalent to Math.min(1, 2, 3).
function myArrayMax(arr) { var len = arr.length; var max = -Infinity; while (len--) { if (arr[len] > max) { max = arr[len]; } } return max; }
function myArrayMin(arr) { var len = arr.length; var min = Infinity; while (len--) { if (arr[len] < min) { min = arr[len]; } } return min; }
var cars = [ {type:"Volvo", year:2016}, {type:"Saab", year:2001}, {type:"BMW", year:2010} ];
cars.sort(function(a, b){return a.year - b.year});
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; });
var txt = "; var numbers = [45, 4, 9, 16, 25]; numbers.forEach(myFunction); function myFunction(value, index, array) { txt = txt + value + "
"; }
var txt = "; var numbers = [45, 4, 9, 16, 25]; numbers.forEach(myFunction); function myFunction(value) { txt = txt + value + "
"; }
var numbers1 = [45, 4, 9, 16, 25]; var numbers2 = numbers1.map(myFunction); function myFunction(value, index, array) { return value * 2; }
var numbers1 = [45, 4, 9, 16, 25]; var numbers2 = numbers1.map(myFunction); function myFunction(value) { return value * 2; }
var numbers = [45, 4, 9, 16, 25]; var over18 = numbers.filter(myFunction); function myFunction(value, index, array) { return value > 18; }
var numbers = [45, 4, 9, 16, 25]; var over18 = numbers.filter(myFunction); function myFunction(value) { return value > 18; }
var numbers1 = [45, 4, 9, 16, 25]; var sum = numbers1.reduce(myFunction); function myFunction(total, value, index, array) { return total + value; } Note that the function takes 4 arguments:
var numbers1 = [45, 4, 9, 16, 25]; var sum = numbers1.reduce(myFunction); function myFunction(total, value) { return total + value; }
var numbers1 = [45, 4, 9, 16, 25]; var sum = numbers1.reduce(myFunction, 100); function myFunction(total, value) { return total + value; }
var numbers1 = [45, 4, 9, 16, 25]; var sum = numbers1.reduceRight(myFunction); function myFunction(total, value, index, array) { return total + value; } Note that the function takes 4 arguments:
var numbers1 = [45, 4, 9, 16, 25]; var sum = numbers1.reduceRight(myFunction); function myFunction(total, value) { return total + value; }
var numbers = [45, 4, 9, 16, 25]; var allOver18 = numbers.every(myFunction); function myFunction(value, index, array) { return value > 18; }
that the function takes 3 arguments:
var numbers = [45, 4, 9, 16, 25]; var allOver18 = numbers.every(myFunction); function myFunction(value) { return value > 18; }
var numbers = [45, 4, 9, 16, 25]; var someOver18 = numbers.some(myFunction); function myFunction(value, index, array) { return value > 18; }
var fruits = [ "Apple", "Orange", "Apple", "Mango"]; var a = fruits.indexOf("Apple");
Search an array for the item "Apple": var fruits = [ "Apple", "Orange", "Apple", "Mango"]; var a = fruits.lastIndexOf("Apple");
var numbers = [4, 9, 16, 25, 29]; var first = numbers.find(myFunction); function myFunction(value, index, array) { return value > 18; } Note that the function takes 3 arguments:
var numbers = [4, 9, 16, 25, 29]; var first = numbers.findIndex(myFunction); function myFunction(value, index, array) { return value > 18; }
var d = new Date ( ) ;
new Date ( ) new Date(year, month, day, hours, minutes, seconds, milliseconds) new Date(milliseconds) new Date(date string) new Date ( ) new Date ( ) creates a new date object with the current date and time:
var d = new Date ( ) ; new Date(year, month, ...) new Date(year, month, ...) creates a new date object with a specified date and time. 7 numbers specify year, month, day, hour, minute, second, and millisecond (in that order):
var d = new Date(2018, 11, 24, 10, 33, 30, 0);
var d = new Date(2018, 11, 24, 10, 33, 30); 5 numbers specify year, month, day, hour, and minute:
var d = new Date(2018, 11, 24, 10, 33); 4 numbers specify year, month, day, and hour:
var d = new Date(2018, 11, 24, 10); 3 numbers specify year, month, and day:
var d = new Date(2018, 11, 24); 2 numbers specify year and month:
var d = new Date(2018, 11);
var d = new Date(2018);
var d = new Date(99, 11, 24);
var d = new Date(9, 11, 24); new Date(dateString) new Date(dateString) creates a new date object from a date string:
var d = new Date("October 13, 2014 11:13:00");
var d = new Date(0);
var d = new Date(100000000000);
var d = new Date(-100000000000);
var d = new Date(86400000);
d = new Date ( ) ; document.getElementById("demo").innerHTML = d;
d = new Date ( ) ; document.getElementById("demo").innerHTML = d.toString ( ) ;
var d = new Date ( ) ; document.getElementById("demo").innerHTML = d.toUTCString ( ) ;
var d = new Date ( ) ; document.getElementById("demo").innerHTML = d.toDateString ( ) ;
var d = new Date ( ) ; document.getElementById("demo").innerHTML = d.toISOString ( ) ;
var d = new Date ( ) ;
new Date ( ) new Date(year, month, day, hours, minutes, seconds, milliseconds) new Date(milliseconds) new Date(date string) new Date ( ) new Date ( ) creates a new date object with the current date and time:
var d = new Date ( ) ; new Date(year, month, ...) new Date(year, month, ...) creates a new date object with a specified date and time. 7 numbers specify year, month, day, hour, minute, second, and millisecond (in that order):
var d = new Date(2018, 11, 24, 10, 33, 30, 0);
var d = new Date(2018, 11, 24, 10, 33, 30); 5 numbers specify year, month, day, hour, and minute:
var d = new Date(2018, 11, 24, 10, 33); 4 numbers specify year, month, day, and hour:
var d = new Date(2018, 11, 24, 10); 3 numbers specify year, month, and day:
var d = new Date(2018, 11, 24); 2 numbers specify year and month:
var d = new Date(2018, 11);
var d = new Date(2018);
var d = new Date(99, 11, 24);
var d = new Date(9, 11, 24); new Date(dateString) new Date(dateString) creates a new date object from a date string:
var d = new Date("October 13, 2014 11:13:00");
var d = new Date(0);
var d = new Date(100000000000);
var d = new Date(-100000000000);
var d = new Date(86400000);
d = new Date ( ) ; document.getElementById("demo").innerHTML = d;
d = new Date ( ) ; document.getElementById("demo").innerHTML = d.toString ( ) ;
var d = new Date ( ) ; document.getElementById("demo").innerHTML = d.toUTCString ( ) ;
var d = new Date ( ) ; document.getElementById("demo").innerHTML = d.toDateString ( ) ;
var d = new Date ( ) ; document.getElementById("demo").innerHTML = d.toISOString ( ) ;
Type Example ISO Date "2015-03-25" (The International Standard) Short Date "03/25/2015" Long Date "Mar 25 2015" or "25 Mar 2015"
var d = new Date("2015-03-25");
var d = new Date("2015-03");
var d = new Date("2015");
var d = new Date("2015-03-25T12:00:00Z");
var d = new Date("2015-03-25T12:00:00-06:30");
var d = new Date("03/25/2015");
var d = new Date("2015-3-25");
var d = new Date("2015/03/25");
var d = new Date("25-03-2015");
var d = new Date("Mar 25 2015");
var d = new Date("25 Mar 2015");
var d = new Date("January 25 2015");
var d = new Date("Jan 25 2015");
var d = new Date("JANUARY, 25, 2015");
var msec = Date.parse("March 21, 2012"); document.getElementById("demo").innerHTML = msec;
var msec = Date.parse("March 21, 2012"); var d = new Date(msec); document.getElementById("demo").innerHTML = d;
Method Description getFullYear ( ) Get the year as a four digit number (yyyy) getMonth ( ) Get the month as a number (0-11) getDate ( ) Get the day as a number (1-31) getHours ( ) Get the hour (0-23) getMinutes ( ) Get the minute (0-59) getSeconds ( ) Get the second (0-59) getMilliseconds ( ) Get the millisecond (0-999) getTime ( ) Get the time (milliseconds since January 1, 1970) getDay ( ) Get the weekday as a number (0-6)
var d = new Date ( ) ; document.getElementById("demo").innerHTML = d.getTime ( ) ;
var d = new Date ( ) ; document.getElementById("demo").innerHTML = d.getFullYear ( ) ;
var d = new Date ( ) ; document.getElementById("demo").innerHTML = d.getMonth ( ) ;
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 ( ) ];
var d = new Date ( ) ; document.getElementById("demo").innerHTML = d.getDate ( ) ;
var d = new Date ( ) ; document.getElementById("demo").innerHTML = d.getHours ( ) ;
var d = new Date ( ) ; document.getElementById("demo").innerHTML = d.getMinutes ( ) ;
var d = new Date ( ) ; document.getElementById("demo").innerHTML = d.getSeconds ( ) ;
var d = new Date ( ) ; document.getElementById("demo").innerHTML = d.getMilliseconds ( ) ;
var d = new Date ( ) ; document.getElementById("demo").innerHTML = d.getDay ( ) ;
var d = new Date ( ) ; var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; document.getElementById("demo").innerHTML = days[d.getDay ( ) ];
Method Description getUTCDate ( ) Same as getDate ( ) , but returns the UTC date getUTCDay ( ) Same as getDay ( ) , but returns the UTC day getUTCFullYear ( ) Same as getFullYear ( ) , but returns the UTC year getUTCHours ( ) Same as getHours ( ) , but returns the UTC hour getUTCMilliseconds ( ) Same as getMilliseconds ( ) , but returns the UTC milliseconds getUTCMinutes ( ) Same as getMinutes ( ) , but returns the UTC minutes getUTCMonth ( ) Same as getMonth ( ) , but returns the UTC month getUTCSeconds ( ) Same as getSeconds ( ) , but returns the UTC seconds
Math.PI; Math.round ( )
Math.round(4.7); Math.round(4.4); Math.pow ( )
Math.pow(8, 2);
Math.sqrt(64);
Math.floor ( )
Math.floor(4.7);
Math.cos(0 * Math.PI / 180); Math.min ( ) and Math.max ( )
Math.min(0, 150, 30, 20, -8, -200); // returns -200
Math.max(0, 150, 30, 20, -8, -200); Math.random ( )
Math.random ( ) ;
Math.E Math.PI Math.SQRT2 Math.SQRT1_2 Math.LN2 Math.LN10 Math.LOG2E Math.LOG10E
Method Description abs(x) Returns the absolute value of x acos(x) Returns the arccosine of x, in radians acosh(x) Returns the hyperbolic arccosine of x asin(x) Returns the arcsine of x, in radians asinh(x) Returns the hyperbolic arcsine of x atan(x) Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians atan2(y, x) Returns the arctangent of the quotient of its arguments atanh(x) Returns the hyperbolic arctangent of x cbrt(x) Returns the cubic root of x ceil(x) Returns x, rounded upwards to the nearest integer cos ( x ) Returns the cosine of x ( x is in radians ) cosh ( x ) Returns the hyperbolic cosine of x exp(x) Returns the value of Ex floor(x) Returns x, rounded downwards to the nearest integer log(x) Returns the natural logarithm (base E) of x max(x, y, z, ..., n) Returns the number with the highest value min(x, y, z, ..., n) Returns the number with the lowest value pow(x, y) Returns the value of x to the power of y random ( ) Returns a random number between 0 and 1 round(x) Rounds x to the nearest integer sin(x) Returns the sine of x (x is in radians) sinh(x) Returns the hyperbolic sine of x sqrt(x) Returns the square root of x tan(x) Returns the tangent of an angle tanh(x) Returns the hyperbolic tangent of a number trunc(x) Returns the integer part of a number (x)
Method Description setDate ( ) Set the day as a number (1-31) setFullYear ( ) Set the year (optionally month and day) setHours ( ) Set the hour (0-23) setMilliseconds ( ) Set the milliseconds (0-999) setMinutes ( ) Set the minutes (0-59) setMonth ( ) Set the month (0-11) setSeconds ( ) Set the seconds (0-59) setTime ( ) Set the time (milliseconds since January 1, 1970)
script> var d = new Date ( ) ; d.setFullYear(2020); document.getElementById("demo").innerHTML = d;
script> var d = new Date ( ) ; d.setFullYear(2020, 11, 3); document.getElementById("demo").innerHTML = d; /script>
script> var d = new Date ( ) ; d.setMonth(11); document.getElementById("demo").innerHTML = d; /script>
script> var d = new Date ( ) ; d.setDate(15); document.getElementById("demo").innerHTML = d; /script>
script> var d = new Date ( ) ; d.setDate(d.getDate ( ) + 50); document.getElementById("demo").innerHTML = d; /script>
script> var d = new Date ( ) ; d.setHours(22); document.getElementById("demo").innerHTML = d; /script>
script> var d = new Date ( ) ; d.setMinutes(30); document.getElementById("demo").innerHTML = d; /script>
script> var d = new Date ( ) ; d.setSeconds(30); document.getElementById("demo").innerHTML = d; /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;
Math.random ( ) ;
Math.floor(Math.random ( ) * 10);
Math.floor(Math.random ( ) * 11);
Math.floor(Math.random ( ) * 100);
Math.floor(Math.random ( ) * 101);
Math.floor(Math.random ( ) * 10) + 1;
Math.floor(Math.random ( ) * 100) + 1;
function getRndInteger(min, max) { return Math.floor(Math.random ( ) * (max - min) ) + min; }
function getRndInteger(min, max) { return Math.floor(Math.random ( ) * (max - min + 1) ) + min; }
Boolean(10 > 9)
(10 > 9) 10 > 9
Operator Description Example equal to if (day == "Monday") > greater than if (salary > 9000) < less than if (age < 18)
100 3.14 -15 Hello FALSE 7 + 1 + 3.14
var x = 0; Boolean(x);
var x = -0; Boolean(x);
var x = "; Boolean(x);
var x; Boolean(x);
var x = null; Boolean(x);
var x = false; Boolean(x);
var x = 10 / "H"; Boolean(x);
var x = false; var y = new Boolean(false);
var x = false; var y = new Boolean(false);
var x = false; var y = new Boolean(false);
var x = false; var y = new Boolean(false);
var x = new Boolean(false); var y = new Boolean(false);
Operator Description Comparing Returns equal to x == 8 FALSE x == 5 TRUE x == "5" TRUE equal value and equal type x === 5 TRUE x === "5" FALSE != not equal x != 8 TRUE !== not equal value or not equal type x !== 5 FALSE x !== "5" TRUE x !== 8 TRUE > greater than x > 8 FALSE < less than x < 8 TRUE >= greater than or equal to x >= 8 FALSE <= less than or equal to x <= 8 TRUE
if (age < 18) text = "Too young";
Operator Description Example && and (x < 10 && y > 1) is true || or (x == 5 || y == 5) is false ! not !(x == y) is true
var voteable = (age < 18) ? "Too young":"Old enough";
Case Value 2 < 12 TRUE 2 < "12" TRUE 2 < "John" FALSE 2 > "John" FALSE 2 == "John" FALSE 2 < "12" FALSE 2 > "12" TRUE 2 == "12" FALSE
age = Number(age); if (isNaN(age)) { voteable = "Input is not a number"; } else { voteable = (age < 18) ? "Too young" : "Old enough"; }
if (hour < 18) {
if (hour < 18) { greeting = "Good day"; } else { greeting = "Good evening"; }
if (condition1) { 1} else if ( condition2) { 1} else { } 1
if (time < 10) { greeting = "Good morning"; } else if ( time < 20) { greeting = "Good day"; } else { greeting = "Good evening"; }
(Sunday=0, Monday=1, Tuesday=2 ..)
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"; }
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"; }
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"; }
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"; }
var x = "0"; switch (x) { case 0: text = "Off"; break; case 1: text = "On"; break; default: text = "No value found"; }
text += cars[0] + "
"; text += cars[1] + "
"; text += cars[2] + "
"; text += cars[3] + "
"; text += cars[4] + "
"; text += cars[5] + "
";
var i; for (i = 0; i < cars.length; i++) { text += cars[i] + "
"; }
for (i = 0; i < 5; i++) { text += "The number is " + i + "
"; }
for (i = 0, len = cars.length, text = "; i < len; i++) { text += cars[i] + "
"; }
var i = 2; var len = cars.length; var text = "; for (; i < len; i++) { text += cars[i] + "
"; }
var i = 0; var len = cars.length; for (; i < len; ) { text += cars[i] + "
"; i++; }
var person = {fname:"John", lname:"Doe", age:25}; var text = "; var x; for (x in person) { text += person[x]; }
var cars = ["BMW", "Volvo", "Mini"]; var x; for (x of cars) { document.write(x + "
"); }
var txt = "JavaScript"; var x; for (x of txt) { document.write(x + "
"); }
data
while (i < 10) { text += "The number is " + i; i++; }
line
do { text += "The number is " + i; i++; } while (i < 10);
var cars = ["BMW", "Volvo", "Saab", "Ford"]; var i = 0; var text = "; for (;cars[i];) { text += cars[i] + "
"; i++; }
var cars = ["BMW", "Volvo", "Saab", "Ford"]; var i = 0; var text = "; while (cars[i]) { text += cars[i] + "
"; i++; }
for (i = 0; i < 10; i++) { if (i === 3) { break; } text += "The number is " + i + "
"; }
for (i = 0; i < 10; i++) { if (i === 3) { continue; } text += "The number is " + i + "
"; }
var cars = ["BMW", "Volvo", "Saab", "Ford"]; list: { text += cars[0] + "
"; text += cars[1] + "
"; break list; text += cars[2] + "
"; text += cars[3] + "
"; }
typeof "John" typeof 3.14 typeof NaN typeof false typeof [1,2,3,4] typeof {name:'John', age:34} typeof new Date ( ) typeof function ( ) {} typeof myCar typeof null
John.constructor (3.14).constructor false.constructor [1,2,3,4].constructor {name:'John',age:34}.constructor new Date ( ) .constructor function ( ) {}.constructor
function isArray(myArray) { return myArray.constructor.toString ( ) .indexOf("Array") > -1; }
function isArray(myArray) { return myArray.constructor === Array; }
function isDate(myDate) { return myDate.constructor.toString ( ) .indexOf("Date") > -1; }
function isDate(myDate) { return myDate.constructor === Date; }
String(x) String(123) String(100 + 23)
x.toString ( ) (123).toString ( ) (100 + 23).toString ( )
Method Description toExponential ( ) Returns a string, with a number rounded and written using exponential notation. toFixed ( ) Returns a string, with a number rounded and written with a specified number of decimals. toPrecision ( ) Returns a string, with a number written with a specified length
Method Description getDate ( ) Get the day as a number (1-31) getDay ( ) Get the weekday a number (0-6) getFullYear ( ) Get the four digit year (yyyy) getHours ( ) Get the hour (0-23) getMilliseconds ( ) Get the milliseconds (0-999) getMinutes ( ) Get the minutes (0-59) getMonth ( ) Get the month (0-11) getSeconds ( ) Get the seconds (0-59) getTime ( ) Get the time (milliseconds since January 1, 1970)
Number("3.14") Number(" ") Number(") Number("99 88")
Method Description parseFloat ( ) Parses a string and returns a floating point number parseInt ( ) Parses a string and returns an integer
var y = "5"; var x = + y;
var y = "John"; var x = + y;
Number(false) Number(true)
d = new Date ( ) ; Number(d)
d = new Date ( ) ; d.getTime ( )
5 + null 5 + null 5 + 2 5 - 2 5 * "2"
document.getElementById("demo").innerHTML = myVar;
to Number Converted to String Converted to Boolean FALSE 0 "false" FALSE TRUE 1 "true" TRUE 0 0 "0" FALSE 1 1 "1" TRUE 0 0 "0" TRUE 0 0 "000" TRUE 1 1 "1" TRUE NaN NaN "NaN" FALSE Infinity Infinity "Infinity" TRUE -Infinity -Infinity "-Infinity" TRUE 0 " false 20 20 "20" TRUE twenty NaN "twenty" TRUE [ ] 0 " TRUE [20] 20 "20" TRUE [10,20] NaN "10,20" TRUE ["twenty"] NaN "twenty" TRUE ["ten","twenty"] NaN "ten,twenty" TRUE function ( ) {} NaN "function ( ) {}" TRUE { } NaN "[object Object]" TRUE null 0 "null" FALSE undefined NaN "undefined" FALSE
Operator Name Description & AND Sets each bit to 1 if both bits are 1 | OR Sets each bit to 1 if one of two bits is 1 ^ XOR Sets each bit to 1 if only one of two bits is 1 ~ NOT Inverts all the bits << Zero fill left shift Shifts left by pushing zeros in from the right and let the leftmost bits fall off >>Signed right shift Shifts right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off >>>Zero fill right shift Shifts right by pushing zeros in from the left, and let the rightmost bits fall off
Operation Result Same as Result 5 & 1 1 0101 & 0001 1 5 | 1 5 0101 | 0001 101 ~ 5 10 ~0101 1010 5 << 1 10 0101 << 1 1010 5 ^ 1 4 0101 ^ 0001 100 5 >> 1 2 0101 >> 1 10 5 >>> 1 2 0101 >>> 1 10
00000000000000000000000000000101 (5) 11111111111111111111111111111010 (~5 = -6)
Operation Result 0 & 0 0 0 & 1 0 1 & 0 0 1 & 1 1 4 bits example: Operation Result 1111 & 0000 0 1111 & 0001 1 1111 & 0010 10 1111 & 0100 100
Operation Result 0 | 0 0 0 | 1 1 1 | 0 1 1 | 1 1 4 bits example: Operation Result 1111 | 0000 1111 1111 | 0001 1111 1111 | 0010 1111 1111 | 0100 1111
Operation Result 0 ^ 0 0 0 ^ 1 1 1 ^ 0 1 1 ^ 1 0 4 bits example:
1111 ^ 0000 1111 1111 ^ 0001 1110 1111 ^ 0010 1101 1111 ^ 0100 1011
Decimal Binary 5 00000000000000000000000000000101 1 00000000000000000000000000000001 5 & 1 00000000000000000000000000000001 (1)
var x = 5 & 1;
Decimal Binary 5 00000000000000000000000000000101 1 00000000000000000000000000000001 5 | 1 00000000000000000000000000000101 (5)
Decimal Binary 5 00000000000000000000000000000101 1 00000000000000000000000000000001 5 ^ 1 00000000000000000000000000000100 (4)
var x = 5 ^ 1; h3>JavaScript Bitwise NOT (~)/h3> Decimal Binary 5 00000000000000000000000000000101 ~5 11111111111111111111111111111010 (-6)
var x = ~5;
Decimal Binary 5 00000000000000000000000000000101 5 << 1 00000000000000000000000000001010 (10)
var x = 5 << 1;
Decimal Binary -5 11111111111111111111111111111011 -5 >> 1 11111111111111111111111111111101 (-3)
var x = -5 >> 1;
Decimal Binary 5 00000000000000000000000000000101 5 >>> 1 00000000000000000000000000000010 (2)
var x = 5 >>> 1;
Binary Representation Decimal value 00000000000000000000000000000001 1 00000000000000000000000000000010 2 00000000000000000000000000000100 4 00000000000000000000000000001000 8 00000000000000000000000000010000 16 00000000000000000000000000100000 32 00000000000000000000000001000000 64
Binary Representation Decimal value 00000000000000000000000000000101 5 (4 + 1) 00000000000000000000000000001101 13 (8 + 4 + 1) 00000000000000000000000000101101 45 (32 + 8 + 4 + 1)
Binary Representation Decimal value 00000000000000000000000000000101 5 11111111111111111111111111111011 -5 00000000000000000000000000000110 6 11111111111111111111111111111010 -6 00000000000000000000000000101000 40 11111111111111111111111111011000 -40
function dec2bin(dec){ return (dec >>> 0).toString(2); }
function bin2dec(bin){ return parseInt(bin, 2).toString(10); }
var patt = /w3schools/i; Example explained:
var str = "Visit W3Schools!"; var n = str.search("W3Schools");
var str = "Visit W3Schools"; var n = str.search(/w3schools/i);
var str = "Visit Microsoft!"; var res = str.replace("Microsoft", "W3Schools");
var str = "Visit Microsoft!"; var res = str.replace(/microsoft/i, "W3Schools");
Modifier Description i Perform case-insensitive matching g Perform a global match (find all matches rather than stopping after the first match m Perform multiline matching
Expression Description [abc] Find any of the characters between the brackets
(x|y) Find any of the alternatives separated with
Metacharacter Description ¥d Find a digit ¥s Find a whitespace character ¥b Find a match at the beginning of a word like this: ¥bWORD, or at the end of a word like this: WORD¥b ¥uxxxx Find the Unicode character specified by the hexadecimal number xxxx Quantifiers define quantities: Quantifier Description n+ Matches any string that contains at least one n n* Matches any string that contains zero or more occurrences of n n? Matches any string that contains zero or one occurrences of n
var patt = /e/;
/e/.exec("The best things in life are free!");
p id="demo">
script> try { adddlert("Welcome guest!"); } catch(err) { document.getElementById("demo").innerHTML = err.message; } /script>
throw "Too big"; throw 500;
p>Please input a number between 5 and 10: input id="demo" type="text"> button type="button" onclick="myFunction()">Test Input p id="p01"> script> function myFunction ( ) { var message, x; message = document.getElementById("p01"); 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; } }
input id="demo" type="number" min="5" max="10" step="1">
function myFunction ( ) { var message, x; message = document.getElementById("p01"); 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 = "Error: " + err + "."; } finally { document.getElementById("demo").value = "; } }
Property Description name Sets or returns an error name message Sets or returns an error message (a string)
Error Name Description EvalError An error has occurred in the eval ( ) function RangeError A number "out of range" has occurred ReferenceError An illegal reference has occurred SyntaxError A syntax error has occurred TypeError A type error has occurred URIError An error in encodeURI ( ) has occurred
var num = 1; try { num.toPrecision(500); } catch(err) { document.getElementById("demo").innerHTML = err.name; }
var x; try { x = y + 1; catch(err) { document.getElementById("demo").innerHTML = err.name; }
try { eval("alert('Hello)"); catch(err) { document.getElementById("demo").innerHTML = err.name; }
var num = 1; try { num.toUpperCase ( ) ; catch(err) { document.getElementById("demo").innerHTML = err.name; }
try { decodeURI("%%%"); catch(err) { document.getElementById("demo").innerHTML = err.name; }
fileName (Mozilla) lineNumber (Mozilla) columnNumber (Mozilla)
function myFunction ( ) { var carName = "Volvo"; }
var carName = "Volvo"; function myFunction ( ) { }
myFunction ( ) ; function myFunction ( ) { carName = "Volvo"; }
var carName = "Volvo";
var x = 5; var y = 7; elem = document.getElementById("demo"); elem.innerHTML = x + " " + y;
var x = 5; elem = document.getElementById("demo"); elem.innerHTML = x + " " + y; var y = 7;
var x = 5; var y; elem = document.getElementById("demo"); elem.innerHTML = x + " " + y; y = 7;
Example 1 gives the same result as Example 2: Example 1 x = 5; elem = document.getElementById("demo"); elem.innerHTML = x; var x; Example 2 var x; x = 5; elem = document.getElementById("demo"); elem.innerHTML = x;
carName = "Volvo"; alert(carname); let carName;
use strict; x = 3.14;
use strict; myFunction ( ) ; function myFunction ( ) { y = 3.14; }
x = 3.14; myFunction ( ) ; function myFunction ( ) { "use strict"; y = 3.14;
use strict; x = 3.14;
use strict; x = {p1:10, p2:20};
use strict; var x = 3.14; delete x;
use strict; function x(p1, p2) {}; delete x;
use strict; function x(p1, p1) {};
use strict; var x = 010;
use strict; var x = "¥010";
use strict; var obj = {}; Object.defineProperty(obj, "x", {value:0, writable:false}); obj.x = 3.14;
use strict; var obj = {get x ( ) {return 0} }; obj.x = 3.14;
use strict; delete Object.prototype;
use strict; var eval = 3.14;
use strict; var arguments = 3.14;
use strict; with (Math){x = cos(2)};
use strict; eval ("var x = 2"); alert (x);
use strict; function myFunction ( ) { alert(this); myFunction ( ) ;
var person = { firstName: "John", lastName : "Doe", id : 5566, fullName : function ( ) { return this.firstName + " " + this.lastName; } } ;
fullName : function ( ) { return this.firstName + " " + this.lastName; }
var x = this;
use strict; var x = this;
function myFunction ( ) { return this; }
use strict; function myFunction ( ) { return this; }
button onclick="this.style.display='none'"> Click to Remove Me! /button>
var person = { firstName : "John", lastName : "Doe", id : 5566, myFunction : function ( ) { return this; } };
var person = { firstName: "John", lastName : "Doe", id : 5566, fullName : function ( ) { return this.firstName + " " + this.lastName; } };
var person1 = { fullName: function ( ) { return this.firstName + " " + this.lastName; } } var person2 = { firstName:"John", lastName: “Doe", }
var carName = "Volvo"; function myFunction ( ) { }
function myFunction ( ) { var carName = “Volvo"; }
{ var x = 2; }
{ let x = 2; }
var x = 10; { var x = 2; ]
var x = 10; { let x = 2;
var i = 5; for (var i = 0; i < 10; i++) { }
let i = 5; for (let i = 0; i < 10; i++) { }
function myFunction ( ) { var carName = "Volvo"; } function myFunction ( ) { let carName = “Volvo"; }
var x = 2; let x = 2;
var carName = "Volvo";
let carName = "Volvo";
var x = 2; var x = 3;
var x = 2; let x = 3; { var x = 4; let x = 5 {
let x = 2; let x = 3; { let x = 4; let x = 5; }
let x = 2; var x = 3; { let x = 4; var x = 5; {
let x = 2; { let x = 3; } { let x = 4; }
This is OK: carName = "Volvo"; alert(carName); var carName;
carName = "Volvo"; alert(carname); let carName;
const PI = 3.141592653589793; PI = 3.14; PI = PI + 10;
var x = 10; { const x = 2; }
const PI; PI = 3.14159265359; Correct const PI = 3.14159265359;
const PI = 3.141592653589793; PI = 3.14; PI = PI + 10;
const car = {type:"Fiat", model:"500", color:"white"}; car.color = "red"; car.owner = "Johnson";
const car = {type:"Fiat", model:"500", color:"white"}; car = {type:"Volvo", model:"EX60", color:"red"};
const cars = ["Saab", "Volvo", "BMW"]; cars[0] = "Toyota"; cars.push("Audi");
const cars = ["Saab", "Volvo", "BMW"]; cars = ["Toyota", "Volvo", "Audi"]; Browser Support
var x = 2; var x = 3; x = 4;
var x = 2; const x = 2; { let x = 2; const x = 2; }
const x = 2; const x = 3; x = 3; var x = 3; let x = 3; { const x = 2; const x = 3; x = 3; var x = 3; let x = 3; }
const x = 2; { const x = 3; } { const x = 4; }
carName = "Volvo"; alert(carName); var carName;
carName = "Volvo"; alert(carName); const carName;
hello = function ( ) { return "Hello World!";}
hello = (val) => "Hello " + val;
hello = function ( ) { document.getElementById("demo").innerHTML += this; } window.addEventListener("load", hello); document.getElementById("btn").addEventListener("click", hello);
hello = ( ) => { document.getElementById("demo").innerHTML += this; } window.addEventListener("load", hello); document.getElementById("btn").addEventListener("click", hello);
Syntax class ClassName { constructor ( ) { ... } }
class Car { constructor(name, year) { this.name = name; this.year = year;
let myCar1 = new Car("Ford", 2014); let myCar2 = new Car("Audi", 2019);
Syntax class ClassName { constructor ( ) { ... } method_1 ( ) { ... } method_2 ( ) { ... } method_3 ( ) { ... }
class Car { constructor(name, year) { this.name = name; this.year = year; } age ( ) { let date = new Date ( ) ; return date.getFullYear ( ) - this.year; } } let myCar = new Car("Ford", 2014); document.getElementById("demo").innerHTML = My car is + myCar.age ( ) + " years old.";
class Car { constructor(name, year) { this.name = name; this.year = year; } age(x) { return x - this.year; } } let date = new Date ( ) ; let year = date.getFullYear ( ) ; let myCar = new Car("Ford", 2014); document.getElementById("demo").innerHTML= My car is + myCar.age(year) + " years old."; Browser Support
My First Web Page script> a = 5; b = 6; c = a + b; console.log(c); /script>
var x = 15 * 5; debugger; document.getElementById("demo").innerHTML = x;