JavaScript Tutorial
JavaScript Where To
1.Scripts can be placed in the <body>, or in the <head> section of an HTML
page, or in both.
JavaScript code is inserted between <script> and </script> tags.
2.Scripts can also be placed in external files: External file: myScript.js
To use an external script, put the name of the script file in the src (source)
attribute of a <script> tag:
<script src="myScript.js"></script>
External scripts cannot contain <script> tags.
JavaScript Output
Using innerHTML
<script>
document.getElementById("demo").innerHTML = "<h2>Hello World</h2>";
</script>
Using innerText
<script>
document.getElementById("demo").innerText = "Hello World";
</script>
Note
Use innerHTML when you want to change an HTML element.
Use innerText when you only want to change the plain text.
Changing the innerHTML property of an HTML element is the most common way
to display data in HTML.
Using document.write()
<script>
document.write(5 + 6);
</script>
Using document.write() after an HTML document is loaded, will delete all
existing HTML:
The document.write() method should only be used for testing.
Using window.alert()
<script>
window.alert(5 + 6);
</script>
You can skip the window keyword:
<script>
alert(5 + 6);
</script>
JavaScript Comments
JavaScript comments can be used to explain JavaScript code, and to make it
more readable.
JavaScript comments can also be used to prevent execution, when testing
alternative code.
Single line comments start with //.
// Change heading:
Multi-line comments start with /* and end with */.
/*
The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
in my web page:
*/
JavaScript Variables
Variables are Containers for Storing Data
JavaScript Variables can be declared in 4 ways:
Automatically, Using var, let or const
Example
x = 5;
var x = 5;
let x = 5;
The var keyword should only be used in code written for older browsers.
Always use const if the value should not be changed
Always use const if the type should not be changed (Arrays and Objects)
JavaScript Operators
JavaScript Arithmetic Operators
Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation (ES2016)
/ Division
% Modulus (Division Remainder)
++ Increment
-- Decrement
JavaScript Assignment Operators
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
JavaScript Comparison Operators
Operato Description
r
== 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
Operato Description
r
&& logical and
|| logical or
! logical not
JavaScript Functions
A JavaScript function is a block of code designed to perform a particular task.
A JavaScript function is executed when "something" invokes it (calls it).
JavaScript Function Syntax
function name(parameter1, parameter2, parameter3) {
// code to be executed
}
Why Functions?
With functions you can reuse code
You can write code that can be used many times.
You can use the same code with different arguments, to produce different
results.
JavaScript Function Syntax
function name(parameter1, parameter2, parameter3) {
// code to be executed
}
JavaScript Objects
In JavaScript, almost "everything" is an object.
Objects are objects
Maths are objects
Functions are objects
Dates are objects
Arrays are objects
Objects are containers for Properties and Methods.
Properties are named Values.
Methods are Functions stored as Properties.
Creating a JavaScript Object
Ex 1:
// Create an Object
const person = {firstName:"John", lastName:"Doe", age:50,
eyeColor:"blue"};
Ex 2:
// Create an Object
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
Ex 3:
// Create an Object
const person = {};
// Add Properties
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";
Ex 5:
// Create an Object
const person = new Object();
// Add Properties
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";
Accessing Object Properties
objectName.propertyName
objectName["propertyName"]
Examples
person.lastName;
person["lastName"];
JavaScript Object Properties
An Object is an Unordered Collection of
Properties
Properties are the most important part of JavaScript objects.
Properties can be changed, added, deleted, and some are read only.
Accessing JavaScript Properties
// objectName.property
let age = person.age;
or
//objectName["property"]
let age = person["age"];
Adding New Properties
person.nationality = "English";
Deleting Properties
delete person.age;
or delete person["age"];
Nested Objects
myObj = {
name:"John",
age:30,
myCars: {
car1:"Ford",
car2:"BMW",
car3:"Fiat"
}
}
You can access nested objects
myObj.myCars.car2;
myObj.myCars["car2"];
myObj["myCars"]["car2"];
JavaScript Object Methods
Object methods are actions that can be performed on objects.
A method is a function definition stored as a property value.
const person = {
firstName: "John",
lastName: "Doe",
id: 5566,
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
this refers to the person object:
this.firstName means the firstName property of person.
this.lastName means the lastName property of person.
Accessing Object Methods
objectName.methodName()
If you invoke the fullName property with (), it will execute as a function:
name = person.fullName();
Adding a Method to an Object
person.name = function () {
return this.firstName + " " + this.lastName;
};
Using JavaScript Methods
This example uses the JavaScript toUpperCase() method to convert a
text to uppercase:
person.name = function () {
return (this.firstName + " " + this.lastName).toUpperCase();
};
How to Display JavaScript
Objects?
Some solutions to display JavaScript objects are:
Displaying the Object Properties by name
Displaying the Object Properties in a Loop
Displaying the Object using Object.values()
Displaying the Object using JSON.stringify()
Displaying Object Properties
// Create an Object
const person = {
name: "John",
age: 30,
city: "New York"
};
// Display Properties
document.getElementById("demo").innerHTML =
person.name + "," + person.age + "," + person.city;
Displaying Properties in a Loop
// Create an Object
const person = {
name: "John",
age: 30,
city: "New York"
};
// Build a Text
let text = "";
for (let x in person) {
text += person[x] + " ";
};
// Display the Text
document.getElementById("demo").innerHTML = text
You must use person[x] in the loop.
person.x will not work (Because x is the loop variable).
Using Object.values()
// Create an Object
const person = {
name: "John",
age: 30,
city: "New York"
};
// Create an Array
const myArray = Object.values(person);
// Display the Array
document.getElementById("demo").innerHTML = myArray;
Object Constructor Functions
Sometimes we need to create many objects of the same type.
To create an object type we use an object constructor function.
It is considered good practice to name constructor functions with an upper-case
first letter.
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
Now we can use new Person() to create many new Person objects:
const myFather = new Person("John", "Doe", 50, "blue");
const myMother = new Person("Sally", "Rally", 48, "green");
const mySister = new Person("Anna", "Rally", 18, "green");
const mySelf = new Person("Johnny", "Rally", 22, "green");
Adding a Method to an Object
myMother.changeName = function (name) {
this.lastName = name;
}
The new method will be added to myMother. Not to any other Person Objects.
Adding a Method to a Constructor
Adding a new method must be done to the constructor function prototype:
Person.prototype.changeName = function (name) {
this.lastName = name;
}
myMother.changeName("Doe");
JavaScript Events
HTML events are "things" that happen to HTML elements.
When JavaScript is used in HTML pages, JavaScript can "react" on these events.
Here are some examples of HTML events:
An HTML web page has finished loading
An HTML input field was changed
An HTML button was clicked
Often, when events happen, you may want to do something.
JavaScript lets you execute code when events are detected
In the following example, an onclick attribute (with code), is added to
a <button> element:
<button onclick="document.getElementById('demo').innerHTML =
Date()">The time is?</button>
JavaScript code is often several lines long. It is more common to see event
attributes calling functions:
<button onclick="displayDate()">The time is?</button>
Here is a list of some common HTML events:
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
JavaScript Event Handlers
Event handlers can be used to handle and verify user input, user actions, and
browser actions:
Things that should be done every time a page loads
Things that should be done when the page is closed
Action that should be performed when a user clicks a button
Content that should be verified when a user inputs data
And more ...
Many different methods can be used to let JavaScript work with events:
HTML event attributes can execute JavaScript code directly
HTML event attributes can call JavaScript functions
You can assign your own event handler functions to HTML elements
You can prevent events from being sent or being handled
And more ...
JavaScript Strings
Strings are for storing text
Strings are written with quotes
Using Quotes
let text = "John Doe";
let carName2 = 'Volvo XC60';
There is no difference between single or double quotes
Quotes Inside Quotes
let answer2 = "He is called 'Johnny'";
let answer3 = 'He is called "Johnny"';
String Length
To find the length of a string, use the built-in length property:
let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let length = text.length;
Escape Characters
let text = "We are the so-called \"Vikings\" from the north.";
let text= 'It\'s alright.';
JavaScript String Methods
Basic String Methods
String length: The length property returns the length of a string:
let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let length = text.length;
String charAt() and String at():return the character at a specified index
(position) in a string:
let text = "HELLO WORLD";
let char = text.charAt(0);
const name = "W3Schools";
let letter = name.at(2);
slice() and substring():
let text = "Apple, Banana, Kiwi";
let part = text.slice(7, 13);
String toUpperCase()
let text1 = "Hello World!";
let text2 = text1.toUpperCase();
String toLowerCase()
let text1 = "Hello World!"; // String
let text2 = text1.toLowerCase(); // text2 is text1 converted to
lower
String concat()
let text1 = "Hello";
let text2 = "World";
let text3 = text1.concat(" ", text2);
text = "Hello" + " " + "World!";
text = "Hello".concat(" ", "World!");
String trim():The trim() method removes whitespace from both sides of a
string
let text1 = " Hello World! ";
let text2 = text1.trim();
String trimStart():The trimStart() method works like trim(), but removes
whitespace only from the start of a string.
String trimEnd():The trimEnd() method works like trim(), but removes
whitespace only from the end of a string.
String repeat():The repeat() method returns a string with a number of copies
of a string
let text = "Hello world!";
let result = text.repeat(2);
String replace():The replace() method replaces a specified value with
another value in a string
let text = "Please visit Microsoft!";
let newText = text.replace("Microsoft", "W3Schools");
String split():A string can be converted to an array with the split() method
text.split(",")
String Search Methods
String indexOf():The indexOf() method returns the index (position) of
the first occurrence of a string in a string, or it returns -1 if the string is not
found
let text = "Please locate where 'locate' occurs!";
let index = text.indexOf("locate");
String lastIndexOf():The lastIndexOf() method returns the index of
the last occurrence of a specified text in a string
let text = "Please locate where 'locate' occurs!";
let index = text.lastIndexOf("locate");
String search():The search() method searches a string for a string (or a
regular expression) and returns the position of the match
let text = "Please locate where 'locate' occurs!";
text.search("locate");
String match():The match() method returns an array containing the results of
matching a string against a string (or a regular expression)
String matchAll()
String includes():The includes() method returns true if a string contains a
specified value
let text = "Hello world, welcome to the universe.";
text.includes("world");
String startsWith():The startsWith() method returns true if a string begins
with a specified value
let text = "Hello world, welcome to the universe.";
text.startsWith("Hello");
String endsWith():The endsWith() method returns true if a string ends with a
specified value.
let text = "John Doe";
text.endsWith("Doe");