Java Script    " Step by Step "

  1. History
  2. Introduction
  3. Where To
  4. Output
  5. Statements
  6. Syntax
  7. Comments
  8. Variables
  9. Operators
  10. Arithmetic
  11. Assignment
  12. Data Types
  13. Functions
  14. Objects
  15. Events
  16. Strings
  17. String Methods
  18. Numbers
  19. Number Methods
  20. Arrays
  21. Array Methods
  22. Array Sort
  23. Array Iteration
  24. Dates
  25. Date format
  26. Date Get method
  27. Date Set Method
  28. Math
  29. Random
  30. Booleans

History and Significance

A Brief History

The Significance

Introduction

Example

document.getElementById ( " demo " ) . innerHTML = " Hello JavaScript " ;						
document.getElementById ( ' demo ' ) . innerHTML = ' Hello JavaScript ' ;						

Changing HTML Content

Changing HTML Styles with CSS.

Example

	document.getElementById("demo").style.fontSize = "35px";

Hiding HTML Elements

Example

document.getElementById("demo").style.display = "none";						

Showing HTML Elements

Example

document.getElementById("demo").style.display = "block";						

Where To

The <script> Tag

Example

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

Functions and Events

JavaScript in <head> or <body>

Example

function myFunction ( )  {	
document.getElementById("demo").innerHTML = "Paragraph changed."; }						
<p id="demo">A Paragraph>/p>
<button type="button" onclick="myFunction()">Try it>/button>						

Example

<p id="demo">A Paragraph </p>
<button type="button" onclick="myFunction()">Try it</button>
function myFunction ( )  {
document.getElementById ( " demo " ).innerHTML = "Paragraph changed."; }						

External JavaScript

The file extension .js.

Example

<script src="myScript.js">						

External Advantages

Example

<script src="myScript1.js"script
<script src="myScript2.js"/script						

External References

Example

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

Example

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

Example

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

Output

Display Possibilities

Using innerHTML

Example

<!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>						

Using document.write ( )

Example

<!DOCTYPE html>
<html>
<body> 
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
document.write(5 + 6);
</script>
</body>
<html>						

Example

<!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>						

Using window.alert ( )

Example

<!DOCTYPE html>
<html>
<body> 
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
window.alert(5 + 6);
</script>
</body>
<html>						

Example

<!DOCTYPE html>
<html>
<body> 
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
alert(5 + 6);
</script>
</body>
<html>						

Using console.log ( )

Example

<!DOCTYPE html>
<html>
<body> 
<script>
console.log(5 + 6);
</script>
</body>
<html>						

JavaScript Print

Example

<!DOCTYPE html>
<html>
<body> 
<button onclick="window.print()">Print this page
</body>
<html>						

Statements

Program Statements

Example

var x, y, z;    
x = 5;
y = 6;
z = x + y;						

Types of Statements

Example

document.getElementById ( " demo " ).innerHTML = "Hello Dolly.";						

Semicolons

Example

var a, b, c;     
a = 5;
b = 6;
c = a + b;						

Example

a = 5; b = 6; c = a + b;						

White Space

Example

var person = “ Hege “;
var person = “ Hege ";
var x = y + z ;						

Line Length and Line Breaks

Example

document.getElementById ( " demo " ).innerHTML =
Hello Dolly!;						

Code Blocks

Example

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

Keywords

abstractexplanation
argumentsexplanation
awaitexplanation
booleanexplanation
breakexplanation
byteexplanation
caseexplanation
catchexplanation
charexplanation
class*explanation
constexplanation
continueexplanation
debuggerexplanation
defaultexplanation
deleteexplanation
doexplanation
doubleexplanation
elseexplanation
enum*explanation
evalexplanation
export*explanation
extends*explanation
FALSEexplanation
finalexplanation
finallyexplanation
floatexplanation
forexplanation
functionexplanation
gotoexplanation
ifexplanation
implementsexplanation
import*explanation
inexplanation
instanceofexplanation
intexplanation
interfaceexplanation
let*explanation
longexplanation
nativeexplanation
newexplanation
nullexplanation
packageexplanation
privateexplanation
protectedexplanation
publicexplanation
returnexplanation
shortexplanation
staticexplanation
super*explanation
switchexplanation
synchronizedexplanation
thisexplanation
throwexplanation
throwsexplanation
transientexplanation
TRUEexplanation
tryexplanation
typeofexplanation
varexplanation
voidexplanation
volatileexplanation
whileexplanation
withexplanation
yieldexplanation

Syntax

The set of rules

Example

var x, y, z;       
x = 5; y = 6;
z = x + y;        						

Values

Literals

Example

John Doe
John Doe'						

Variables

Example

var x;
h3>Operators /h3>
x = 6;						

Example

(5 + 6) * 10						

Example

var x, y;
h3>Expressions /h3>
x = 5 ;
y = 6 ;						

Comments

Single Line Comments

Example

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

Example

var x = 5;
var y = x + 2;						

Multi-line Comments

Example

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

Adding

Example

document.getElementById("myP").innerHTML = "My first paragraph.";						

Example

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

Comments

Single Line Comments

Example

// Change heading:
document.getElementById("myH").innerHTML = "My First Page";						

Example

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

Example

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:						

Example

/*
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.";						

Using Comments to Prevent Execution

Example

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

Example

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

Variables

Example

var x = 5;
var y = 6;
var z = x + y; //z stores the value 11						

Using let and const (2015)

Much Like Algebra

Example

var price1 = 5;
var price2 = 6;
var total = price1 + price2;						

Operators

Example

var x = 5;
var y = 2;
var z = x + y;     						

Assignment

Example

var x = 10;						

Adding

Example

var x = 5;
var y = 2;
var z = x + y;						

Multiplying

Example

var x = 5;
var y = 2;
var z = x * y;						

JavaScript Arithmetic Operators

Example

	Operator	Description				
				+	Addition				
				-	Subtraction				
				*	Multiplication				
				**	Exponentiation (ES2016)				
				%	Modulus (Division Remainder)				
				++	Increment				
				-- Decrement					

JavaScript Assignment Operators

Example

	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			

Assignment

Example

var x = 10;
x += 5;						

JavaScript String Operators

Example

var txt1 = "John";
var txt2 = "Doe";
var txt3 = txt1 + " " + txt2;						

Example

var txt1 = "What a very ";
txt1 += "nice day";						

Adding Strings and Numbers

Example

var x = 5 + 5;
var y = "5" + 5;
var z = "Hello" + 5;						

JavaScript Comparison Operators

Example

	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				

JavaScript Logical Operators

Example

	Operator	Description				
				&&	logical and				
				||	logical or				
				!	logical not				

JavaScript Type Operators

Example

	Operator	Description				
				typeof	Returns the type of a variable				
				instanceof	Returns true if an object is an instance of an object type				

JavaScript Bitwise Operators

Bit operators work on 32 bits numbers.

Example

	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	

Example

00000000000000000000000000000101 will return 11111111111111111111111111111010						

JavaScript Identifiers

Names must begin with a letter

The Assignment Operator

JavaScript Data Types

Example

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

Declaring (Creating) JavaScript Variables

Example

p id="demo">

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

Example

var person = "John Doe", carName = "Volvo", price = 200;
var person = "John Doe",
carName = "Volvo",
price = 200;
Value = undefined						

Example

var carName;						

Re-Declaring JavaScript Variables

Example

var carName = "Volvo";
var carName;						

JavaScript Arithmetic

Example

var x = 5 + 2 + 3;						

Example

var x = "John" + " " + "Doe";						

Example

var x = "5" + 2 + 3;						

Example

var x = 2 + 3 + "5";						

JavaScript Dollar Sign $

Example

var $$$ = "Hello World";
var $ = 2;
var $myMoney = 5;						

JavaScript Underscore (_)

Example

var _lastName = "Johnson";
var _x = 2;
var _100 = 5;						

Example

5 * 10
x * 10						

Example

John + " " + "Doe"						

JavaScript Keywords

Example

var x, y;
x = 5 + 6;
y = x * 10;						

chapter 7 Comments/h2>

Example

var x = 5;
var x = 6;						

JavaScript Identifiers

Identifiers are names.

JavaScript is Case Sensitive

Example

var lastname, lastName;
lastName = "Doe";
lastname = "Peterson";						

JavaScript and Camel Case

Lower Camel Case:

JavaScript Character Set

JavaScript uses the Unicode character set.

Arithmetic

JavaScript Arithmetic Operators

Example

	Operator	Description				
				+	Addition				
				-	Subtraction				
				*	Multiplication				
				**	Exponentiation (ES2016)				
				%	Modulus (Remainder)				
				++	Increment				
				-- Decrement					

Arithmetic Operations

Example

var x = 100 + 50;						

Example

var x = a + b;						

Example

var x = (100 + 50) * a;						

Operators and Operands

Example

	Operand	Operator	Operand			
				100	+	50			

Adding

Example

var x = 5;
var y = 2;
var z = x + y;						

Subtracting

Example

var x = 5;
var y = 2;
var z = x - y;						

Multiplying

Example

var x = 5;
var y = 2;
var z = x * y;						

Dividing

Example

var x = 5;
var y = 2;
var z = x / y;						

Remainder

Example

var x = 5;
var y = 2;
var z = x % y;						

Incrementing

Example

var x = 5;
x++;
var z = x;						

Decrementing

Example

var x = 5;
x--;
var z = x;						

Exponentiation

Example

var x = 5;
var z = x ** 2;
x ** y produces the same result as Math.pow(x,y):						

Example

var x = 5;
var z = Math.pow(x,2);						

Operator Precedence

Example

var x = 100 + 50 * 3;						

Example

var x = (100 + 50) * 3;						

Example

var x = 100 + 50 - 3;						

JavaScript Operator Precedence Values

Example

	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		

Assignment

JavaScript Assignment Operators

Example

	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			

Example

var x = 10;						

Example

var x = 10;
x += 5;						

Example

var x = 10;
x -= 5;						

Example

var x = 10;
x *= 5;						

Example

var x = 10;
x /= 5;						

Example

var x = 10;
x %= 5;						

Data Types

JavaScript Data Types

Example

var length = 16;
var lastName = "Johnson";                     
var x = {firstName:"John", lastName:"Doe"};   						

The Concept of Data Types

Example

var x = 16 + "Volvo";						

Example

var x = "16" + "Volvo";						

Example

var x = 16 + "Volvo";						

Example

var x = "Volvo" + 16;						

Example

var x = 16 + 4 + "Volvo";						

JavaScript Types are Dynamic

Example

var x;          
x = 5;
x = "John";     						

JavaScript Strings

Example

var carName1 = "Volvo XC60";
var carName2 = 'Volvo XC60';						

Example

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

JavaScript Numbers

Example

var x1 = 34.00;
var x2 = 34;						

Example

var y = 123e5;
var z = 123e-5;						

Booleans

Example

var x = 5;
var y = 5;
var z = 6;
(x == y)       
(x == z)      						

Arrays

Example

var cars = ["Saab", "Volvo", "BMW"];						

JavaScript Objects

Example

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

The typeof Operator

Example

typeof "            
typeof "John"        
typeof "John Doe"    						

Example

typeof 0
typeof 314
typeof 3.14
typeof (3)
typeof (3 + 4)						

Undefined

Example

var car;    						

Example

car = undefined;   						

Empty Values

Example

var car = ";    
Null						

Example

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

Example

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

Difference Between Undefined and Null

Example

typeof undefined           
typeof null               
null === undefined         
null == undefined						

Primitive Data

Example

typeof "John"              
typeof 3.14
typeof true              
typeof false              
typeof x 						

Complex Data

Example

typeof {name:'John', age:34}
typeof [1,2,3,4]
typeof null                  
typeof function myFunc ( ) {}   						

Functions

Example

function myFunction(p1, p2) {
return p1 * p2;						

JavaScript Function Syntax

Example

(parameter1, parameter2, ...)						

Example

function name(parameter1, parameter2, parameter3) { }						

Function Invocation

Function Return

Example

var x = myFunction(4, 3);
function myFunction(a, b) {
return a * b; }						

Why Functions?

Example

Convert Fahrenheit to Celsius:
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32); }
document.getElementById("demo").innerHTML = toCelsius(77);						

The ( ) Operator Invokes the Function

Example

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

Functions Used as Variable Values

Example

var x = toCelsius(77);
var text = "The temperature is " + x + " Celsius";
var text = "The temperature is " + toCelsius(77) + " Celsius";						

Local Variables

Example

function myFunction ( )  {
var carName = "Volvo"; }						

Objects

Real Life Objects, Properties, and Methods

Example

Object Properties Methods
car.name = Fiat
car.model = 500
car.weight = 850kg
car.color = white
car.start ( ) 
car.drive ( ) 
car.brake ( )  
car.stop ( ) 						

JavaScript Objects

Example

var car = "Fiat";						

Example

var car = {type:"Fiat", model:"500", color:"white"};						

Object Definition

Example

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

Example

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

Object Properties

Example

Property Property Value
firstName : John
lastName Doe
age 50
eyeColor: blue						

Accessing Object Properties

Example

person.lastName;						

Example

person["lastName"];						

Object Methods

Example

	Property	Property Value				
				firstName	John				
				lastName Doe					
				age	50				
				eyeColor	blue				
				fullName	function ( )  {return this.firstName + " " + this.lastName;}				

Example

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

The this Keyword

Accessing Object Methods

Example

name = person.fullName ( ) ;						

Example

name = person.fullName;						

Example

var x = new String ( ) ;       
var y = new Number ( ) ;        
var z = new Boolean ( ) ;       						

Events

HTML Events

element event='some JavaScript'>
p>With double quotes:

element event="some JavaScript">

Example

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

Example

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

Example

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

Common HTML Events

Example

	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				

Strings

JavaScript Strings

Example

var x = "John Doe";						

Example

var carName1 = "Volvo XC60";
var carName2 = 'Volvo XC60';						

Example

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

String Length

Example

var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;						

Escape Character

Example

var x = "We are the so-called "Vikings" from the north.";						

Example

	Code	Result	Description			
				¥'		Single quote			
				¥""	Double quote				
				¥¥	¥	Backslash			

Example

var x = "We are the so-called ¥"Vikings¥" from the north.";						

Example

var x = 'It¥'s alright.';						

Example

var x = "The character ¥¥ is called backslash.";						

Example

	Code	Result				
				¥b	Backspace				
				¥f	Form Feed				
				¥n	New Line				
				¥r	Carriage Return				
				¥t	Horizontal Tabulator				
				¥v	Vertical Tabulator				

Breaking Long Code Lines

Example

document.getElementById("demo").innerHTML =
Hello Dolly!;						

Example

document.getElementById("demo").innerHTML = "Hello Dolly!";						

Example

document.getElementById("demo").innerHTML = "Hello " + Dolly!;						

Example

document.getElementById("demo").innerHTML = ¥ 
Hello Dolly!;						

Strings Can be Objects

Example

var firstName = "John";						

Example

var firstName = new String("John");
var x = "John";
var y = new String("John");						

Example

var x = "John";             
var y = new String("John");						

Example

var x = "John";             
var y = new String("John");						

Example

var x = new String("John");             
var y = new String("John");						

Example

var x = new String("John");             
var y = new String("John");						

String Methods

String Methods and Properties

String Length

Example

var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;						

Finding a String in a String

Example

var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate");						

JavaScript counts positions from zero.

Example

var str = "Please locate where 'locate' occurs!";
var pos = str.lastIndexOf("locate");						

Example

var str = "Please locate where 'locate' occurs!";
var pos = str.lastIndexOf("John");						

Example

var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate", 15);						

Example

var str = "Please locate where 'locate' occurs!";
var pos = str.lastIndexOf("locate", 15);						

Searching for a String in a String

Example

var str = "Please locate where 'locate' occurs!";
var pos = str.search("locate");						

Did You Notice?

Extracting String Parts

The slice ( ) Method

Example

var str = "Apple, Banana, Kiwi";
var res = str.slice(7, 13);						

Example

var str = "Apple, Banana, Kiwi";
var res = str.slice(-12, -6);						

Example

var res = str.slice(7);						

Example

var res = str.slice(-12);						

The substring ( ) Method

Example

var str = "Apple, Banana, Kiwi";
var res = str.substring(7, 13);						

The substr ( ) Method

Example

var str = "Apple, Banana, Kiwi";
var res = str.substr(7, 6);						

Example

var str = "Apple, Banana, Kiwi";
var res = str.substr(7);						

Example

var str = "Apple, Banana, Kiwi";
var res = str.substr(-4);						

Replacing String Content

Example

str = "Please visit Microsoft!";
var n = str.replace("Microsoft", "W3Schools");						

Example

str = "Please visit Microsoft and Microsoft!";
var n = str.replace("Microsoft", "W3Schools");						

Example

str = "Please visit Microsoft!";
var n = str.replace("MICROSOFT", "W3Schools");						

Example

str = "Please visit Microsoft!";
var n = str.replace(/MICROSOFT/i, "W3Schools");						

Example

str = "Please visit Microsoft and Microsoft!";
var n = str.replace(/Microsoft/g, "W3Schools");						

Converting to Upper and Lower Case

Example

var text1 = "Hello World!";
var text2 = text1.toUpperCase ( ) ;						

Example

var text1 = "Hello World!";
var text2 = text1.toLowerCase ( ) ;						

The concat ( ) Method

Example

var text1 = "Hello";
var text2 = "World";
var text3 = text1.concat(" ", text2);						

Example

var text = "Hello" + " " + "World!";
var text = "Hello".concat(" ", "World!");						

String.trim ( )

Example

var str = "Hello World!";
alert(str.trim ( ) );						

Example

var str = "       Hello World!        ";
alert(str.replace(/^[¥s¥uFEFF¥xA0]+|[¥s¥uFEFF¥xA0]+$/g, ''));						

Example

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>						

Example

let str = "5";
str = str.padStart(4,0);						

Example

let str = "5";
str = str.padEnd(4,0);						

Example

	Chrome 57	Edge 15	Firefox 48	Safari 10	Opera 44	
				Mar 2017	Apr 2017	Aug 2016	Sep 2016	Mar 2017	

Extracting String Characters

charAt(position)
charCodeAt(position)						

The charAt ( ) Method

Example

var str = "HELLO WORLD";
str.charAt(0);						

The charCodeAt ( ) Method

Example

var str = "HELLO WORLD";
str.charCodeAt(0);						

Property Access

Example

var str = "HELLO WORLD";
str[0];						

Example

var str = "HELLO WORLD";
str[0] = "A";
str[0];						

Example

var txt = "a,b,c,d,e";  
txt.split(",");         
txt.split(" ");          
txt.split("|");						

Example

var txt = "Hello";      
txt.split(");						

Complete String Reference

Numbers

Example

var x = 3.14;
var y = 3;						

Example

var x = 123e5;
var y = 123e-5;						

Example

	Exponent	Sign				
				Value (aka Fraction/Mantissa)					
				52 bits (0 - 51) 	11 bits (52 - 62)	1 bit (63)			

Precision

Example

var x = 999999999999999;
var y = 9999999999999999;						

Example

var x = 0.2 + 0.1;						

Example

var x = (0.2 * 10 + 0.1 * 10) / 10;						

Adding Numbers and Strings

WARNING

Example

var x = 10;
var y = 20;
var z = x + y;						

Example

var x = "10";
var y = "20";
var z = x + y;						

Example

var x = 10;
var y = "20";
var z = x + y; 						

Example

var x = "10";
var y = 20;
var z = x + y;						

Example

var x = 10;
var y = 20;
var z = "The result is: " + x + y;						

Example

var x = 10;
var y = 20;
var z = "30";
var result = x + y + z;						

Numeric Strings

Example

var x = 100;
var y = "100";						

Example

var x = "100";
var y = "10";
var z = x / y;       						

Example

var x = "100";
var y = "10";
var z = x * y;       						

Example

var x = "100";
var y = "10";
var z = x - y;      						

Example

var x = "100";
var y = "10";
var z = x + y;       						

NaN - Not a Number

Example

var x = 100 / "Apple";						

Example

var x = 100 / "10";						

Example

var x = 100 / "Apple";
isNaN(x);               						

Example

var x = NaN;
var y = 5;
var z = x + y;        
						

Example

var x = NaN;
var y = "5";
var z = x + y;						

Example

typeof NaN;            
						

Infinity

Example

var myNumber = 2;
while (myNumber != Infinity) {  
myNumber = myNumber * myNumber; }						

Example

var x =  2 / 0;
var y = -2 / 0;						

Example

typeof Infinity;    						

Hexadecimal

Example

var x = 0xFF;						

Example

var myNumber = 32;
myNumber.toString(10);
myNumber.toString(32);
myNumber.toString(16);
myNumber.toString(8);
myNumber.toString(2);						

Numbers Can be Objects

Example

var x = 123;						

Example

var y = new Number(123);
var x = 123;
var y = new Number(123);						

Example

var x = 500;
var y = new Number(500);						

Example

var x = 500;
var y = new Number(500);						

Example

var x = new Number(500);
var y = new Number(500);						

Note

Number Methods

Number Methods and Properties

The toString ( ) Method

Example

var x = 123;
x.toString ( ) ;            
(123).toString ( ) ;
(100 + 23).toString ( ) ;						

The toExponential ( ) Method

Example

var x = 9.656;
x.toExponential(2);
x.toExponential(4);
x.toExponential(6);						

The toFixed ( ) Method

Example

var x = 9.656;
x.toFixed(0);
x.toFixed(2);
x.toFixed(4);
x.toFixed(6);
toFixed(2) is perfect for working with money.						

The toPrecision ( ) Method

Example

var x = 9.656;
x.toPrecision ( ) ;       
x.toPrecision(2);
x.toPrecision(4);
x.toPrecision(6);						

The valueOf ( ) Method

Example

var x = 123;
x.valueOf ( ) ;            
(123).valueOf ( ) ;						
(100 + 23).valueOf ( ) ;

Converting Variables to Numbers

The Number ( ) method

The parseInt ( ) method

The parseFloat ( ) method

Global JavaScript Methods

Example

	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				

The Number ( ) Method

Example

Number(true);        
Number(false);         
Number("10");
Number("  10");
Number("10  ");
Number(" 10  ");
Number("10.33");
Number("10,33");
Number("10 33");
Number("John");       						

The Number ( ) Method Used on Dates

Example

Number(new Date("2017-09-30"));						

The parseInt ( ) Method

Example

parseInt("10");
parseInt("10.33");
parseInt("10 20 30");
parseInt("10 years");
parseInt("years 10");						

The parseFloat ( ) Method

Example

parseFloat("10");
parseFloat("10.33");
parseFloat("10 20 30");
parseFloat("10 years");
parseFloat("years 10");						

Number Properties

Example

	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)				

MIN_VALUE and MAX_VALUE

Example

var x = Number.MAX_VALUE;						

Example

var x = Number.MIN_VALUE;						

Example

var x = Number.POSITIVE_INFINITY;						

Example

var x = 1 / 0;						

Example

var x = Number.NEGATIVE_INFINITY;						

NEGATIVE_INFINITY is returned on overflow:

Example

var x = -1 / 0;						

JavaScript NaN - Not a Number

Example

var x = Number.NaN;						

Example

var x = 100 / "Apple";						

Number Properties Cannot be Used on Variables

Example

var x = 6;
var y = x.MAX_VALUE;   						

Complete JavaScript Number Reference

Sorting Arrays

Sorting an Array

Example

var fruits = [ "Banana", "Orange", "Apple", "Mango"];
fruits.sort ( ) ;       						

Reversing an Array

Example

var fruits = [ "Banana", "Orange", "Apple", "Mango"];
fruits.sort ( ) ;       
fruits.reverse ( ) ;    						

Numeric Sort

Example

var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b});						

Example

var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b - a});						

The Compare Function

Example

function ( a, b ) { return a - b }						

Example

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>

Sorting an Array in Random Order

Example

var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return 0.5 - Math.random ( ) });						

The Fisher Yates Method

Example

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 }						

Find the Highest (or Lowest) Array Value

Sorting ascending

Example

var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b});						

Sorting descending

Example

var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b - a});						

Using Math.max ( ) on an Array

Example

function myArrayMax(arr) {
return Math.max.apply(null, arr); }
Math.max.apply(null, [1, 2, 3]) is equivalent to Math.max(1, 2, 3).						

Using Math.min ( ) on an Array

Example

function myArrayMin(arr) {
return Math.min.apply(null, arr); }
Math.min.apply(null, [1, 2, 3]) is equivalent to Math.min(1, 2, 3).						

My Min / Max JavaScript Methods

Example

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

Example

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

Sorting Object Arrays

Example

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

Example

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

Example

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; });						

Array Iteration Methods

JavaScript Array Iteration Methods

Array.forEach ( )

Example

var txt = ";
var numbers = [45, 4, 9, 16, 25];
numbers.forEach(myFunction);
function myFunction(value, index, array) {
txt = txt + value + "
"; }

Note

Example

var txt = ";
var numbers = [45, 4, 9, 16, 25];
numbers.forEach(myFunction);
function myFunction(value) {
txt = txt + value + "
"; }

Array.map ( )

Example

var numbers1 = [45, 4, 9, 16, 25];
var numbers2 = numbers1.map(myFunction);
function myFunction(value, index, array) {
return value * 2; }						

Note

Example

var numbers1 = [45, 4, 9, 16, 25];
var numbers2 = numbers1.map(myFunction);
function myFunction(value) {
return value * 2; }						

Array.filter ( )

Example

var numbers = [45, 4, 9, 16, 25];
var over18 = numbers.filter(myFunction);
function myFunction(value, index, array) {
return value > 18; }						

Example

var numbers = [45, 4, 9, 16, 25];
var over18 = numbers.filter(myFunction);
function myFunction(value) {
return value > 18; }						

Array.reduce ( )

Example

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:						

Example

var numbers1 = [45, 4, 9, 16, 25];
var sum = numbers1.reduce(myFunction);
function myFunction(total, value) {
return total + value; }						

Example

var numbers1 = [45, 4, 9, 16, 25];
var sum = numbers1.reduce(myFunction, 100);
function myFunction(total, value) {
return total + value; }						

Array.reduceRight ( )

Example

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:						

Example

var numbers1 = [45, 4, 9, 16, 25];
var sum = numbers1.reduceRight(myFunction);
function myFunction(total, value) {
return total + value; }						

Array.every ( )

Example

var numbers = [45, 4, 9, 16, 25];
var allOver18 = numbers.every(myFunction);
function myFunction(value, index, array) {
return value > 18; }						

Note

that the function takes 3 arguments:

Example

var numbers = [45, 4, 9, 16, 25];
var allOver18 = numbers.every(myFunction);
function myFunction(value) {
return value > 18; }						

Array.some ( )

Example

var numbers = [45, 4, 9, 16, 25];
var someOver18 = numbers.some(myFunction);
function myFunction(value, index, array) {
return value > 18; }						

Array.indexOf ( )

Example

						

var fruits = [ "Apple", "Orange", "Apple", "Mango"]; var a = fruits.indexOf("Apple");

Syntax

Array.lastIndexOf ( )

Example

Search an array for the item "Apple":
var fruits = [ "Apple", "Orange", "Apple", "Mango"];
var a = fruits.lastIndexOf("Apple");						

Array.find ( )

Example

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:						

Array.findIndex ( )

Example

var numbers = [4, 9, 16, 25, 29];
var first = numbers.findIndex(myFunction);
function myFunction(value, index, array) {
return value > 18; }						

Note

Chapter 24 Date Objects

Example

var d = new Date ( ) ;						

Date Output

Creating Date Objects

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:						

Example

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):						

Example

var d = new Date(2018, 11, 24, 10, 33, 30, 0);						

Note

Example

var d = new Date(2018, 11, 24, 10, 33, 30);
5 numbers specify year, month, day, hour, and minute:						

Example

var d = new Date(2018, 11, 24, 10, 33);
4 numbers specify year, month, day, and hour:						

Example

var d = new Date(2018, 11, 24, 10);
3 numbers specify year, month, and day:						

Example

var d = new Date(2018, 11, 24);
2 numbers specify year and month:						

Example

var d = new Date(2018, 11);						

Example

var d = new Date(2018);						

Previous Century

Example

var d = new Date(99, 11, 24);						

Example

var d = new Date(9, 11, 24);
new Date(dateString)
new Date(dateString) creates a new date object from a date string:						

Example

var d = new Date("October 13, 2014 11:13:00");						

JavaScript Stores Dates as Milliseconds

Example

var d = new Date(0);						

Example

var d = new Date(100000000000);						

Example

var d = new Date(-100000000000);						

Example

var d = new Date(86400000);						

Date Methods

Displaying Dates

Example

d = new Date ( ) ;
document.getElementById("demo").innerHTML = d;						

Same as

Example

d = new Date ( ) ;
document.getElementById("demo").innerHTML = d.toString ( ) ;						

Example

var d = new Date ( ) ;
document.getElementById("demo").innerHTML = d.toUTCString ( ) ;						

Example

var d = new Date ( ) ;
document.getElementById("demo").innerHTML = d.toDateString ( ) ;						

Example

var d = new Date ( ) ;
document.getElementById("demo").innerHTML = d.toISOString ( ) ;						

Date Objects

Example

var d = new Date ( ) ;						

Date Output

Creating Date Objects

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:						

Example

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):						

Example

var d = new Date(2018, 11, 24, 10, 33, 30, 0);						

Note

Example

var d = new Date(2018, 11, 24, 10, 33, 30);
5 numbers specify year, month, day, hour, and minute:						

Example

var d = new Date(2018, 11, 24, 10, 33);
4 numbers specify year, month, day, and hour:						

Example

var d = new Date(2018, 11, 24, 10);
3 numbers specify year, month, and day:						

Example

var d = new Date(2018, 11, 24);
2 numbers specify year and month:						

Example

var d = new Date(2018, 11);						

Example

var d = new Date(2018);						

Previous Century

Example

var d = new Date(99, 11, 24);						

Example

var d = new Date(9, 11, 24);
new Date(dateString)
new Date(dateString) creates a new date object from a date string:						

Example

var d = new Date("October 13, 2014 11:13:00");						

JavaScript Stores Dates as Milliseconds

Example

var d = new Date(0);						

Example

var d = new Date(100000000000);						

Example

var d = new Date(-100000000000);						

Example

var d = new Date(86400000);						

Date Methods

Displaying Dates

Example

d = new Date ( ) ;
document.getElementById("demo").innerHTML = d;						

Same as

Example

d = new Date ( ) ;
document.getElementById("demo").innerHTML = d.toString ( ) ;						

Example

var d = new Date ( ) ;
document.getElementById("demo").innerHTML = d.toUTCString ( ) ;						

Example

var d = new Date ( ) ;
document.getElementById("demo").innerHTML = d.toDateString ( ) ;						

Example

var d = new Date ( ) ;
document.getElementById("demo").innerHTML = d.toISOString ( ) ;						

Date Formats

Date Input

Example

	Type	Example				
				ISO Date	"2015-03-25" (The International Standard)				
				Short Date	"03/25/2015"				
				Long Date	"Mar 25 2015" or "25 Mar 2015"				

Date Output

ISO Dates

Example

var d = new Date("2015-03-25");						

ISO Dates (Year and Month)

Example

var d = new Date("2015-03");						

ISO Dates (Only Year)

Example

var d = new Date("2015");						

ISO Dates (Date-Time)

Example

var d = new Date("2015-03-25T12:00:00Z");						

Example

var d = new Date("2015-03-25T12:00:00-06:30");						

Time Zones

JavaScript Short Dates.

Example

var d = new Date("03/25/2015");						

WARNINGS

Example

var d = new Date("2015-3-25");						

Example

var d = new Date("2015/03/25");						

Example

var d = new Date("25-03-2015");						

Long Dates

Example

var d = new Date("Mar 25 2015");						

Example

var d = new Date("25 Mar 2015");						

Example

var d = new Date("January 25 2015");						

Example

var d = new Date("Jan 25 2015");						

Example

var d = new Date("JANUARY, 25, 2015");						

Date Input - Parsing Dates

Example

var msec = Date.parse("March 21, 2012");
document.getElementById("demo").innerHTML = msec;						

Example

var msec = Date.parse("March 21, 2012");
var d = new Date(msec);
document.getElementById("demo").innerHTML = d;						

Get Date Methods

Example

	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)				

Date.now ( )

The getTime ( ) Method

Example

var d = new Date ( ) ;
document.getElementById("demo").innerHTML = d.getTime ( ) ;						

The getFullYear ( ) Method

Example

var d = new Date ( ) ;
document.getElementById("demo").innerHTML = d.getFullYear ( ) ;						

The getMonth ( ) Method

Example

var d = new Date ( ) ;
document.getElementById("demo").innerHTML = d.getMonth ( ) ;						

Example

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 ( ) ];						

The getDate ( ) Method

Example

var d = new Date ( ) ;
document.getElementById("demo").innerHTML = d.getDate ( ) ;						

The getHours ( ) Method

Example

var d = new Date ( ) ;
document.getElementById("demo").innerHTML = d.getHours ( ) ;						

The getMinutes ( ) Method

Example

var d = new Date ( ) ;
document.getElementById("demo").innerHTML = d.getMinutes ( ) ;						

The getSeconds ( ) Method

Example

var d = new Date ( ) ;
document.getElementById("demo").innerHTML = d.getSeconds ( ) ;						

The getMilliseconds ( ) Method

Example

var d = new Date ( ) ;
document.getElementById("demo").innerHTML = d.getMilliseconds ( ) ;						

The getDay ( ) Method

Example

var d = new Date ( ) ;
document.getElementById("demo").innerHTML = d.getDay ( ) ;						

Example

var d = new Date ( ) ;
var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
document.getElementById("demo").innerHTML = days[d.getDay ( ) ];						

UTC Date Methods

Example

	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				

Complete JavaScript Date Reference

Set Date Methods

Math Object

Example

Math.PI;           
Math.round ( ) 						

Example

Math.round(4.7);
Math.round(4.4);
Math.pow ( ) 						

Example

Math.pow(8, 2);						

Math.sqrt ( )

Example

Math.sqrt(64);						

Math.abs ( )

Example

Math.ceil ( )

Example

Math.floor ( )

Example

Math.floor(4.7);						

Math.sin ( )

Example

Math.cos ( )

Example

Math.cos(0 * Math.PI / 180);
Math.min ( )  and Math.max ( ) 						

Example

Math.min(0, 150, 30, 20, -8, -200);  // returns -200						

Example

Math.max(0, 150, 30, 20, -8, -200);
Math.random ( ) 						

Example

Math.random ( ) ; 						

Math Properties (Constants)

Example

Math.E        
Math.PI       
Math.SQRT2
Math.SQRT1_2
Math.LN2
Math.LN10
Math.LOG2E
Math.LOG10E						

Math Constructor

Math Object Methods

Example

	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)				

Complete Math Reference

Set Date Methods

Example

	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)				

The setFullYear ( ) Method

Example

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

Example

script>
var d = new Date ( ) ;
d.setFullYear(2020, 11, 3);
document.getElementById("demo").innerHTML = d;
/script>						

The setMonth ( ) Method

Example

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

The setDate ( ) Method

Example

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

Example

script>
var d = new Date ( ) ;
d.setDate(d.getDate ( )  + 50);
document.getElementById("demo").innerHTML = d;
/script>						

The setHours ( ) Method

Example

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

The setMinutes ( ) Method

Example

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

The setSeconds ( ) Method

Example

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

Compare Dates

Example

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;						

Complete JavaScript Date Reference

Random

Math.random ( )

Example

Math.random ( ) ;						

JavaScript Random Integers

Example

Math.floor(Math.random ( )  * 10);						

Example

Math.floor(Math.random ( )  * 11);						

Example

Math.floor(Math.random ( )  * 100);						

Example

Math.floor(Math.random ( )  * 101);						

Example

Math.floor(Math.random ( )  * 10) + 1;						

Example

Math.floor(Math.random ( )  * 100) + 1;						

A Proper Random Function

Example

function getRndInteger(min, max) {
return Math.floor(Math.random ( )  * (max - min) ) + min; }						

Example

function getRndInteger(min, max) {
return Math.floor(Math.random ( )  * (max - min + 1) ) + min; }						

Booleans

Boolean Values

The Boolean ( ) Function

Example

Boolean(10 > 9)						

Example

(10 > 9)
10 > 9						

Comparisons and Conditions

Example

	Operator	Description	Example			
					equal to	if (day == "Monday")			
				> greater than	if (salary > 9000)				
	<	less than	if (age < 18)			

Example

100
3.14
-15
Hello
FALSE
7 + 1 + 3.14						

Example

var x = 0;
Boolean(x);						

Example

var x = -0;
Boolean(x);						

Example

var x = ";
Boolean(x);						

Example

var x;
Boolean(x);						

Example

var x = null;
Boolean(x);						

Example

var x = false;
Boolean(x);						

Example

var x = 10 / "H";
Boolean(x);						

Booleans Can be Objects

Example

var x = false;
var y = new Boolean(false);						

Example

var x = false;
var y = new Boolean(false);						

Example

var x = false;             
var y = new Boolean(false);						

Example

var x = false;             
var y = new Boolean(false);						

Example

var x = new Boolean(false);             
var y = new Boolean(false);						

Complete Boolean Reference

Comparison Operators

Example

	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		

How Can it be Used

Example

if (age < 18) text = "Too young";						

Logical Operators

Example

	Operator	Description	Example			
				&&	and	(x < 10 && y > 1) is true			
				||	or	(x == 5 || y == 5) is false			
				!	not	!(x == y) is true			

Conditional (Ternary) Operator

Example

var voteable = (age < 18) ? "Too young":"Old enough";						

Comparing Different Types

Example

	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				

Example

age = Number(age);
if (isNaN(age)) {
voteable = "Input is not a number";
} else {
voteable = (age < 18) ? "Too young" : "Old enough"; }						

if else and else if

Conditional Statements

The if Statement

Example

if (hour < 18) {						

The else Statement

Example

if (hour < 18) {
greeting = "Good day";
} else {
greeting = "Good evening"; }						

The else if Statement

if (condition1) { 1} else if ( condition2) { 1} else { } 1						

Example

if (time < 10) {
greeting = "Good morning";
} else if ( time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening"; }						

Random link

Switch Statement

The JavaScript Switch Statement

Example

(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"; }						

The break Keyword

The default Keyword

Example

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"; }						

Looking forward to the Weekend

Example

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"; }						

Common Code Blocks

Example

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"; }						

Switching Details

Strict Comparison

Example

var x = "0";
switch (x) {
case 0:
text = "Off";
break;
case 1:
text = "On";
break;
default:
text = "No value found"; }						

For Loop

JavaScript Loops

Example

text += cars[0] + "
"; text += cars[1] + "
"; text += cars[2] + "
"; text += cars[3] + "
"; text += cars[4] + "
"; text += cars[5] + "
";

Example

var i;
for (i = 0; i < cars.length; i++) {
text += cars[i] + "
"; }

Different Kinds of Loops

The For Loop

Example

for (i = 0; i < 5; i++) {
text += "The number is " + i + "
"; }

Example

for (i = 0, len = cars.length, text = "; i < len; i++) {
text += cars[i] + "
"; }

Example

var i = 2;
var len = cars.length;
var text = ";
for (; i < len; i++) { 
text += cars[i] + "
"; }

Example

var i = 0;
var len = cars.length;
for (; i < len; ) { 
text += cars[i] + "
"; i++; }

The For/In Loop

Example

var person = {fname:"John", lname:"Doe", age:25};
var text = ";
var x;
for (x in person) {
text += person[x]; }						

The For/Of Loop

Looping over an Array

Example

var cars = ["BMW", "Volvo", "Mini"];
var x;
for (x of cars) {
document.write(x + "
"); }

Looping over a String

Example

var txt = "JavaScript";
var x;
for (x of txt) {
document.write(x + "
"); }

The While Loop

While Loop

The While Loop

Example

data						

Example

while (i < 10) {
text += "The number is " + i;
i++; }						

The Do/While Loop

Example

line						

Example

do {
text += "The number is " + i;
i++; }
while (i < 10);						

Comparing For and While

Example

var cars = ["BMW", "Volvo", "Saab", "Ford"];
var i = 0;
var text = ";
for (;cars[i];) {
text += cars[i] + "
"; i++; }

Example

var cars = ["BMW", "Volvo", "Saab", "Ford"];
var i = 0;
var text = ";
while (cars[i]) {
text += cars[i] + "
"; i++; }

Break and Continue

The Break Statement

Example

for (i = 0; i < 10; i++) {
if (i === 3) { break; }
text += "The number is " + i + "
"; }

The Continue Statement

Example

for (i = 0; i < 10; i++) {
if (i === 3) { continue; }
text += "The number is " + i + "
"; }

JavaScript Labels

statements

Example

var cars = ["BMW", "Volvo", "Saab", "Ford"];
list: {
text += cars[0] + "
"; text += cars[1] + "
"; break list; text += cars[2] + "
"; text += cars[3] + "
"; }

JavaScript Data Types

The typeof Operator

Example

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						

Please observe:

The data type of a date is object

The Data Type of typeof

The constructor Property

Example

John.constructor                
(3.14).constructor
false.constructor                
[1,2,3,4].constructor
{name:'John',age:34}.constructor
new Date ( ) .constructor            
function  ( )  {}.constructor						

Example

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

Example

function isArray(myArray) {
return myArray.constructor === Array; }						

Example

function isDate(myDate) {
return myDate.constructor.toString ( ) .indexOf("Date") > -1; }						

Example

function isDate(myDate) {
return myDate.constructor === Date; }						

Type Conversion

Converting Numbers to Strings

Example

String(x)         
String(123)
String(100 + 23)						

Example

x.toString ( ) 
(123).toString ( )
(100 + 23).toString ( )						

Example

	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				

Converting Booleans to Strings

Converting Dates to Strings

Example

	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)				

Converting Strings to Numbers

Empty strings convert to 0.

Example

Number("3.14")
Number(" ")       
Number(")       
Number("99 88")						

Example

Method	Description					
			parseFloat ( ) Parses a string and returns a floating point number
parseInt ( ) 	Parses a string and returns an integer					

The Unary + Operator

Example

var y = "5";
var x = + y;      						

Example

var y = "John";  
var x = + y;     						

Converting Booleans to Numbers

Example

Number(false)     
Number(true)      						

Converting Dates to Numbers

Example

d = new Date ( ) ;
Number(d)						

Example

d = new Date ( ) ;
d.getTime ( )         						

Automatic Type Conversion

Example

	5 + null					
				5 + null					
				5 + 2					
				5 - 2					
				5 * "2"					

Automatic String Conversion

Example

document.getElementById("demo").innerHTML = myVar;						

JavaScript Type Conversion Table

Value Converted

Example

	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		

Chapter 38 Bitwise Operations

JavaScript Bitwise Operators

Example

	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				

Example

	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		

JavaScript Uses 32 bits Bitwise Operands

Example

	00000000000000000000000000000101 (5)					
				11111111111111111111111111111010 (~5 = -6)					

Bitwise AND

Example

	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				

Bitwise OR

Example

	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				

Bitwise XOR

Example

	Operation	Result				
				0 ^ 0	0				
				0 ^ 1	1				
				1 ^ 0	1				
				1 ^ 1	0				
				4 bits example:					

Example

	1111 ^ 0000	1111				
				1111 ^ 0001	1110				
				1111 ^ 0010	1101				
				1111 ^ 0100	1011				

JavaScript Bitwise AND (&)

Example

	Decimal	Binary				
				5	00000000000000000000000000000101				
				1	00000000000000000000000000000001				
				5 & 1	00000000000000000000000000000001 (1)				

Example

var x = 5 & 1;						

JavaScript Bitwise OR (|)

Example

	Decimal	Binary				
				5	00000000000000000000000000000101				
				1	00000000000000000000000000000001				
				5 | 1	00000000000000000000000000000101 (5)				

Example

var x = 5 | 1;

JavaScript Bitwise XOR (^)


	Decimal	Binary				
				5	00000000000000000000000000000101				
				1	00000000000000000000000000000001				
				5 ^ 1	00000000000000000000000000000100 (4)				
	

Example

var x = 5 ^ 1;
h3>JavaScript Bitwise NOT (~)/h3>
	Decimal	Binary				
				5	00000000000000000000000000000101				
				~5	11111111111111111111111111111010 (-6)				

Example

var x = ~5;						

JavaScript (Zero Fill) Bitwise Left Shift (<<)

Example

	Decimal	Binary				
				5	00000000000000000000000000000101				
				5 << 1	00000000000000000000000000001010 (10)				

Example

var x = 5 << 1;						

JavaScript (Sign Preserving) Bitwise Right Shift (>>)

Example

	Decimal	Binary				
				-5	11111111111111111111111111111011				
				-5 >> 1	11111111111111111111111111111101 (-3)				

Example

var x = -5 >> 1;						

JavaScript (Zero Fill) Right Shift (>>>)

	Decimal	Binary				
				5	00000000000000000000000000000101				
				5 >>> 1	00000000000000000000000000000010 (2)				

Example

var x = 5 >>> 1;						

Binary Numbers

Example

	Binary Representation	Decimal value				
				00000000000000000000000000000001	1				
				00000000000000000000000000000010	2				
				00000000000000000000000000000100	4				
				00000000000000000000000000001000	8				
				00000000000000000000000000010000	16				
				00000000000000000000000000100000	32				
				00000000000000000000000001000000	64				

Example

	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				

Example

function dec2bin(dec){
return (dec >>> 0).toString(2); }						

Example

function bin2dec(bin){
return parseInt(bin, 2).toString(10); }						

Chapter 39 Regular Expressions

What Is a Regular Expression?

Example

var patt = /w3schools/i;
Example explained:						

Using String Methods

Using String search ( ) With a String

Example

var str = "Visit W3Schools!";
var n = str.search("W3Schools");						

Example

var str = "Visit W3Schools";
var n = str.search(/w3schools/i);						

Using String replace ( ) With a String

var str = "Visit Microsoft!";
var res = str.replace("Microsoft", "W3Schools");						

Example

var str = "Visit Microsoft!";
var res = str.replace(/microsoft/i, "W3Schools");						

Did You Notice?

Regular Expression Modifiers

Example

	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				

Regular Expression Patterns

Example

	Expression	Description				
				[abc]	Find any of the characters between the brackets				

Example

	(x|y)	Find any of the alternatives separated with				

Example

	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				

Using the RegExp Object

Using test ( )

Example

var patt = /e/;						

Using exec ( )

Example

/e/.exec("The best things in life are free!");						

Complete RegExp Reference

Errors - Throw and Try to Catch

Errors Will Happen!

Example

						

p id="demo">

script> try { adddlert("Welcome guest!"); } catch(err) { document.getElementById("demo").innerHTML = err.message; } /script>

JavaScript try and catch

JavaScript Throws Errors

The throw Statement

Example

throw "Too big";   
throw 500;						

Input Validation Example

Example


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; } }

HTML Validation

input id="demo" type="number" min="5" max="10" step="1">						

The finally Statement

Example

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 = "; } }						

The Error Object

Error Object Properties

Example

	Property	Description				
				name	Sets or returns an error name				
				message	Sets or returns an error message (a string)				

Error Name Values

Example

	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				

Eval Error

Range Error

Example

var num = 1;
try {
num.toPrecision(500);  }
catch(err) {
document.getElementById("demo").innerHTML = err.name; }						

Reference Error

Example

var x;
try {
x = y + 1;
catch(err) {
document.getElementById("demo").innerHTML = err.name; }						

Syntax Error

Example

try {
eval("alert('Hello)");   
catch(err) {
document.getElementById("demo").innerHTML = err.name; }						

Type Error

Example

var num = 1;
try {
num.toUpperCase ( ) ;   
catch(err) {
document.getElementById("demo").innerHTML = err.name; }						

URI (Uniform Resource Identifier) Error

Example

try {
decodeURI("%%%");   
catch(err) {
document.getElementById("demo").innerHTML = err.name; }						

Non-Standard Error Object Properties

Example

fileName (Mozilla)
lineNumber (Mozilla)
columnNumber (Mozilla)						

Scope

JavaScript Function Scope

Local scope

Global scope

Local JavaScript Variables

Example

function myFunction ( )  {
var carName = "Volvo"; }						

Global JavaScript Variables

Example

var carName = "Volvo";
function myFunction ( )  { }						

Automatically Global

Example

myFunction ( ) ;
function myFunction ( )  {
carName = "Volvo"; }						

Strict Mode

Global Variables in HTML

Example

var carName = "Volvo";						

Warning

The Lifetime of JavaScript Variables

Function Arguments

Example

var x = 5;
var y = 7;
elem = document.getElementById("demo");
elem.innerHTML = x + " " + y;						

Example

var x = 5;
elem = document.getElementById("demo");
elem.innerHTML = x + " " + y;           
var y = 7;						

Example

var x = 5;
var y;     
elem = document.getElementById("demo"); 
elem.innerHTML = x + " " + y;           
y = 7;						

Declare Your Variables At the Top !

Hoisting

JavaScript Declarations are Hoisted

Example

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;						

The let and const Keywords

Meaning

Example

carName = "Volvo";
alert(carname);
let carName;						

JavaScript Initializations are Not Hoisted

Use Strict

The "use strict" Directive

Declaring Strict Mode

Example

use strict;
x = 3.14;						

Example

use strict;
myFunction ( ) ;
function myFunction ( )  {
y = 3.14; }						

Example

x = 3.14;
myFunction ( ) ;
function myFunction ( )  {
"use strict";
y = 3.14;						

The "use strict"; Syntax

Why Strict Mode?

Not Allowed in Strict Mode

Example

use strict;
x = 3.14;						

Objects are variables too.

Example

use strict;
x = {p1:10, p2:20};						

Example

use strict;
var x = 3.14;
delete x;						

Example

use strict;
function x(p1, p2) {};
delete x;               						

Example

use strict;
function x(p1, p1) {};						

Example

use strict;
var x = 010;						

Example

use strict;
var x = "¥010";						

Example

use strict;
var obj = {};
Object.defineProperty(obj, "x", {value:0, writable:false});
obj.x = 3.14;						

Example

use strict;
var obj = {get x ( )  {return 0} };
obj.x = 3.14;						

Example

use strict;
delete Object.prototype; 						

Example

use strict;
var eval = 3.14;						

Example

use strict;
var arguments = 3.14;						

Example

use strict;
with (Math){x = cos(2)};						

Example

use strict;
eval ("var x = 2");
alert (x);            						

Example

use strict;
function myFunction ( )  {
alert(this); 
myFunction ( ) ;						

Watch Out!

The this Keyword

Example

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

What is this?

fullName : function ( )  {
return this.firstName + " " + this.lastName; }						

Example

var x = this;						

Example

use strict;
var x = this;						

this in a Function (Default)

Example

function myFunction ( )  {
return this; }						

this in a Function (Strict)

Example

use strict;
function myFunction ( )  {
return this; }						

this in Event Handlers

Example

button onclick="this.style.display='none'">
Click to Remove Me!
/button>						

Object Method Binding

Example

var person = {
firstName  : "John",
lastName   : "Doe",
id : 5566,
myFunction : function ( )  {
return this; } };						

Example

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

Explicit Function Binding

Example

var person1 = {
fullName: function ( )  {
return this.firstName + " " + this.lastName;
}
}
var person2 = {
firstName:"John",
lastName: “Doe", }						

Let

Global Scope

Example

var carName = "Volvo";
function myFunction ( )  { }						

Function Scope

Example


function myFunction ( )  {
var carName = “Volvo"; }						

JavaScript Block Scope

Example

{ 
var x = 2;
}						

Example

{ 
let x = 2; }						

Redeclaring Variables

Example

var x = 10;
{ var x = 2; ]						

Example

var x = 10;
{ 
let x = 2;						

Loop Scope

Example

var i = 5;
for (var i = 0; i < 10; i++) { }						

Example

let i = 5;
for (let i = 0; i < 10; i++) {  }						

Function Scope

function myFunction ( ) { var carName = "Volvo"; } function myFunction ( ) { let carName = “Volvo"; }

Global Scope

Example

var x = 2;
let x = 2;						

Global Variables in HTML

Example

var carName = "Volvo";						

Example

let carName = "Volvo";						

Redeclaring

Example

var x = 2;
var x = 3;						

Example

var x = 2;
let x = 3;
{
var x = 4;
let x = 5 {						

Example

let x = 2;
let x = 3;
{
let x = 4;
let x = 5; }						

Example

let x = 2;
var x = 3;
{
let x = 4;
var x = 5; {						

Example

let x = 2;
{
let x = 3;
}
{
let x = 4; }						

Hoisting

Example

This is OK:
carName = "Volvo";
alert(carName);
var carName;						

Meaning:

Example

carName = "Volvo";
alert(carname);
let carName;						

Const

Example

const PI = 3.141592653589793;
PI = 3.14;
PI = PI + 10;						

Block Scope

Example

var x = 10;
{ const x = 2; }						

Assigned when Declared

Example

const PI;
PI = 3.14159265359;
Correct
const PI = 3.14159265359;						

Not Real Constants

Example

const PI = 3.141592653589793;
PI = 3.14;
PI = PI + 10;						

Constant Objects can Change

Example

const car = {type:"Fiat", model:"500", color:"white"};
car.color = "red";
car.owner = "Johnson";						

Example

const car = {type:"Fiat", model:"500", color:"white"};
car = {type:"Volvo", model:"EX60", color:"red"};						

Constant Arrays can Change

Example

const cars = ["Saab", "Volvo", "BMW"];
cars[0] = "Toyota";
cars.push("Audi");						

Example

const cars = ["Saab", "Volvo", "BMW"];
cars = ["Toyota", "Volvo", "Audi"];   
Browser Support						

Redeclaring

Example

var x = 2;
var x = 3;
x = 4;						

Example

var x = 2;
const x = 2;
{
let x = 2;
const x = 2; }						

Example

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; }						

Example

const x = 2;
{
const x = 3;
}
{
const x = 4; }						

Hoisting

Example

carName = "Volvo";
alert(carName);
var carName;						

Meaning

Example

carName = "Volvo";
alert(carName);
const carName;						

Arrow Function

hello = function ( ) { return "Hello World!";}

With Arrow Function:

hello = ( ) => { return "Hello World!"; }

hello = (val) => "Hello " + val;

What About this?

hello = val => "Hello " + val;

Example

						

hello = function ( ) { document.getElementById("demo").innerHTML += this; } window.addEventListener("load", hello); document.getElementById("btn").addEventListener("click", hello);

Example

						

hello = ( ) => { document.getElementById("demo").innerHTML += this; } window.addEventListener("load", hello); document.getElementById("btn").addEventListener("click", hello);

Classes

JavaScript Class Syntax

Syntax
class ClassName {
constructor ( )  { ... }
}						

Example

class Car {
constructor(name, year) {
this.name = name;
this.year = year;						

Using a Class

Example

let myCar1 = new Car("Ford", 2014);
let myCar2 = new Car("Audi", 2019);						

Class Methods

Syntax
class ClassName {
constructor ( )  { ... }
method_1 ( )  { ... }
method_2 ( )  { ... }
method_3 ( )  { ... }						

Example

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.";						

Example

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						

Debugging

Code Debugging

JavaScript Debuggers

The console.log ( ) Method

Example

My First Web Page
script>
a = 5;
b = 6;
c = a + b;
console.log(c);
/script>						

Setting Breakpoints

The debugger Keyword

Example

var x = 15 * 5;
debugger;
document.getElementById("demo").innerHTML = x;						

Major Browsers' Debugging Tools

Did You Know?

Get the time. ECMAScript 5.

alert(str.trim ( ) );