JavaScript is a scripting or programming language that allows you to implement complex features on the web pages. Whenever a web page displaying more complex contents viz. use of interactive maps, animated 2D/3D graphics, scrolling video jukeboxes and so on, JavaScript is used. It is the third layer of standard web technologies (First layer HTML and Second layer CSS) and having grater importance in the web page designing.
Variables are containers for storing data. Three Methods for declaring a JavaScript Variable are:
Using ‘var’
var x = 5;
var y = 6;
var z = x + y;
Using ‘let’
let x = 5;
let y = 6;
let z = x + y;
Using ‘const’
const x = 5;
const y = 6;
let z = x + y;
The Difference between let and var is the variables defined with ‘let’ cannot be re-declared while the variables defined with ‘const’ can be re-declared.
Example:
let x = "John Doe";
let x = 0; (NOT ALLOWED)
var x = "John Doe";
var x = 0; (ALLOWED)
Const
A ‘const’ variable cannot be reassigned
.
Example
const PI = 3.141592653589793;
PI = 3.14; // This will give an error
PI = PI + 10; // This will also give an error
Console
In this section we will learn how to run JavaScript in the Chrome Console. We can open our console in the web browser by pressing Ctrl + Shift + K, or by right-clicking on any webpage and selecting Inspect, from which we can see the site's source code, CSS code and JavaScript code that powers animations and more. It also includes a console option where we can run our JavaScript code. A console is a JavaScript object that provides access to the browser's debugging console. This object provides us with a variety of methods such as log(), error(), table() and so on. Each method can use for different purposes. These methods are mentioned below:
Method
Description
clear()
This function clears the console.
count()
The number of times this particular call to count() has been made is logged. An error message is printed to the console.
error()
In the console, this function adds a new inline group. Following console messages are indented by an additional level until console. groupEnd() is used.
group()
In the console, this function adds a new inline group. However, the newly formed group collapsed. To expand it, the user must use the disclosure button.
groupCollapsed()
The current inline group in the console is exited.
groupEnd()
The console receives an informational message.
log()
Displays tabular data in the form of a table.
table()
Sets a timer (can track how long an operation takes)
time()
If an assertion is false, an error message is written to the console.
timeEnd()
Stops a previously started timer by console. time()
warn()
The console receives a warning message.
clear()
This method prints a warning message to the console. The warning message is highlighted with yellow by default.
console.clear();count()
The console.count() method is used to count the number of times for which function is called.
for (let i = 0; i < 5; i++) {
console.count();
}
error()
This function is used to log error messages to the console. This is useful for code testing. The error message will be highlighted in red by default.
console.error("You made a mistake");
group() and groupEnd()
The console object's group() and groupEnd() methods allow us to group contents in a separate indented block. They accept the label, which has the same value as time() and timeEnd().
console.log("Hello world!");
console.group();
console.log("Hello again, this time inside a group!");
console.groupEnd();
console.log("and we are back.");
log()
The method log() prints the output to the console. We can print anything by writing inside the log (“......”). It could be an array, object, string, boolean, or something else.
console.log("Hello world!");
table()
We use the console.table() method to create a table within a console. The input must be an array or an object that will be displayed in the form of a table. In this example, the object is used as an input.
console.table(["Audi", "Volvo", "Ford"]);
time() and timeEnd()
The time and timeEnd() function is used to start and end a timer in the javascript console.
warn()
This method is used to generate a warning message and log it to the console. The warning message will be highlighted in yellow by default.
console.warn("This is a warning!");
operators
Operators are the building blocks of any programming language. Operators can be defined as symbols that allow us to perform specific mathematical and logical computations on operands. To put it another way, an operator controls the operands.
Types of operator:
Arithmetic Operators
Assignment Operators
Comparison Operators
Logical Operators
Arithmetic Operators
Operator
Description
+
Addition
-
Subtraction
*
Multiplication
**
Exponentiation (ES2016)
/
Division
%
Modulus (Division Remainder)
++
Increment
--
Decrement
Arithmetic operators are the operator used for arithmetic operations like addition, subtraction, multiplication, division etc.
let a = 3;
let x = (100 + 50) * a;
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
Assignment operators are used for assigning values in javascript.
let x = 10;
x += 5;
Comparison Operators
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
Comparison operators are used for comparing the operand of the given expression.
Logical Operators
Operator
Description
&&
logical and
||
logical or
!
logical not
DOM - Documemt Object Model
Document Object Model – DOM
The Document Object Model (DOM) is a data representation of the objects that make up a web document's structure and content. The DOM is a web document programming interface. It represents the page so that programmes can change the structure, style, and content of the document. The document is represented by the DOM as nodes and objects, allowing programming languages to interact with the page. A web page is a document that can be viewed in the browser window or as HTML source code. It is the same document in both cases, but the Document Object Model (DOM) representation allows it to be manipulated. It can be modified with a scripting language such as JavaScript because it is an object-oriented representation of the web page.
Name
Description
getElementById()
Returns the element having the given id value.
getElementsByName()
Returns all the elements having the given name value.
getElementsByTagName()
Returns all the elements having the given tag name.
getElementsByClassName()
Returns all the elements having the given class name.
getElementById()
The method getElementById() returns an element with the specified value. If the element does not exist, the getElementById() method returns null. One of the most common methods in the HTML DOM is getElementById(). It is almost always used when you want to read or edit an HTML element.
The getElementsByName() method returns a list of elements with the specified names. The method getElementsByName() returns a live NodeList.
NodeList: A NodeList is a collection (list) of nodes that looks like an array. The nodes in the list are accessible via index. The index begins at 0.
let elements = document.getElementsByName("fname");
Cats:
Dogs:
Number of elements with name="animal" is:
getElementsByTagName()
The method getElementsByTagName() returns a collection of all elements that have the specified tag name. The method getElementsByTagName() returns an HTMLCollection. The property getElementsByTagName() is read-only.
The getElementsByClassName() method returns a collection of elements that belong to the specified class(s). The method getElementsByClassName() returns an HTML collection. The property getElementsByClassName() is read-only.
An Event is a change in the state of an object. There are various events in HTML that represent some activity performed by the user or the browser. When javascript code is embedded in HTML, it reacts to these events and allows the code to run. Event Handling refers to the process of reacting to events. Thus, JavaScript handles HTML events through event handlers.
An HTML event can be initiated by the browser or by the user.
Here are some HTML event examples:
An HTML web page has completed loading.
An HTML input field was modified.
An HTML button was pressed.
Events
Event
Description
onchange
An HTML element has been modified.
onclick
The user selects an HTML element and clicks it.
onmouseover
The mouse is moved over an HTML element by the user.
onmouseout
The mouse is moved away from an HTML element by the user.
onkeydown
A keyboard key is pressed by the user.
onload
The page has been fully loaded by the browser.
Loops
Loops are a quick and easiest way to repeat functions/events. This section will guide JavaScript's various loop statements. A loop can be thought of as a computerised version of the game where you tell someone to take X steps in one direction, then Y steps in the opposite direction. For example, "Go five steps to the east" could be expressed as a loop in this manner.
Types of loops
For loop
For in loop
For of loop
While loops
For loop
‘For’ loop statement creates a loop with 3 optional expressions.
for (let i = 0; i < 5; i++) {
text += "The number is " + i + " ";
}
For in loop
The JavaScript for in statement loops through the properties of an Object.
const person = {fname:"John", lname:"Doe", age:25};
let text = "";
for (let x in person) {
text += person[x];
}
For of loop
The JavaScript for of statement loops through the values of an iterable object.
const cars = ["BMW", "Volvo", "Mini"];
let text = "";
for (let x of cars) {
text += x;
}
While loop
The while loop statement loops through a block of code as long as a specified condition is true.
while (i < 10) {
text += "The number is " + i;
i++;
}
Conditions
If, else if, else
By using the ‘if’ statement a block of statements will be executed until the condition is true. If the condition is false, then the block of statements will not be executed. If we want to execute more than one condition, then we use ‘else’/’’else if’ statement with ‘if’.
let hour = new Date().getHours();
if (hour < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
Switch
The switch statement is a type of conditional statement in JavaScript, which is used to perform one condition out of different conditions. This is an excellent choice for long, nested if/else statements. The switch statement is used to evaluate an expression. The expression's value is then compared to the values of each case in the structure. If a match is found, the associated block of code is executed.
switch(expression) {
case n:
code block
break;
case n:
code block
break;
default:
default code block
}
Function
A JavaScript function is a piece of code that is designed to perform a specific task. When someone calls a JavaScript function, it executes it (calls it). The function keyword is followed by a name, followed by parentheses, to define a JavaScript function(). Letters, digits, underscores, and dollar signs can be used in function names (same rules as variables). Parameter names separated by commas may be included in the parentheses. The function's code to be executed is enclosed in curly brackets {}
function myFunction(p1, p2) {
return p1 * p2;
}
function name(parameter1, parameter2, parameter3) {
// code to be executed
}
Function Return
The function will stop executing when it reaches a return statement in JavaScript. If the function was called from a statement, JavaScript will "return" to run the code after the statement that called it. Functions frequently generate a return value. The result is "returned" to the "caller."
let x = myFunction(4, 3); // Function is called, return value will end up in x
function myFunction(a, b) {
return a * b; // Function returns the product of a and b
}
Array
A JavaScript array is a single variable that stores multiple elements. It is frequently used when we need to store a list of elements and access them using a single variable. In contrast to most languages, where an array is a reference to multiple variables, an array in JavaScript is a single variable that stores multiple elements. Arrays allow us to store multiple values of the same data type in a single variable name; otherwise, we have to declare separate variables for each value. If you want to loop over a larger number of elements, it is more efficient to store the values in an array rather than writing the same code for each value repeatedly.
Strings can be used to store data that can be represented in text form. Some of the most common string operations are length checking, building and concatenating strings with the + and += string operators, checking for the existence or location of substrings with the indexOf() method, and extracting substrings with the substring() method.
let text = "John Doe";
Escape Sequence
Code
Result
\b
Backspace
\f
Form Feed
\n
New Line
\r
Carriage Return
\t
Horizontal Tabulator
\v
Vertical Tabulator
\'
'
\"
'
\\
'
String Method
String length
String slice()
String substring()
String substr()
String replace()
String replaceAll()
String toUpperCase()
String toLowerCase()
String concat()
String trim()
String trimStart()
String trimEnd()
String padStart()
String padEnd()
String charAt()
String charCodeAt()
String split()
String indexOf()
String lastIndexOf()
String search()
String match()
String matchAll()
String includes()
String startsWith()
String endsWith()
String length()
The length property returns the length of a string.
let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let length = text.length;
String slice()
Slice property extracts a portion of a string and returns it in a new string.
let text = "Apple, Banana, Kiwi";
let part = text.slice(7, 13);
String substring()
Substring property is similar to slice. The difference is that in substring, start and end values less than 0 are treated as 0.
let str = "Apple, Banana, Kiwi";
let part = str.substring(7, 13);
String substr()
Substring function is similar to slice function. The second parameter, on the other hand, specifies the length of the extracted part.
let str = "Apple, Banana, Kiwi";
let part = str.substr(7, 6);
String replace()
The replace() method in a string replaces a specified value with another value.
let text = "Please visit Microsoft!";
let newText = text.replace("Microsoft", "W3Schools");
String replaceAll()
Instead of a string to be replaced, the replaceAll() method allows you to specify a regular expression.
text = text.replaceAll(/Cats/g,"Dogs");
text = text.replaceAll(/cats/g,"dogs");
String toUpperCase()
A string is converted to upper case with toUpperCase()
let text1 = "Hello World!";
let text2 = text1.toUpperCase();
String toLowerCase()
A string is converted to lower case with toLowerCase()
let text1 = "Hello World!";
let text2 = text1.toLowerCase();
String concat()
concat() joins two or more strings
let text1 = "Hello";
let text2 = "World";
let text3 = text1.concat(" ", text2);
String trim()
Trim() removes all whitespace from both sides of a string.
let text1 = " Hello World! ";
let text2 = text1.trimStart();
String trimStart()
The trimStart() method works like trim(), but removes whitespace only from the start of a string.
let text1 = " Hello World! ";
let text2 = text1.trimStart();
String trimEnd()
The trimEnd() method works like trim(), but removes whitespace only from the end of a string.
let text1 = " Hello World! ";
let text2 = text1.trimEnd();
String padStart()
The padStart() method pads a string with another string
let text = "5";
let padded = text.padStart(4,"x");
String padEnd()
The padEnd() method pads a string with another string
let text = "5";
let padded = text.padEnd(4,"x");
String charAt()
The charAt() method returns the character at a specified index (position) in a string.
let text = "HELLO WORLD";
let char = text.charAt(0);
String charCodeAt()
The charCodeAt() method returns the unicode of the character at a specified index in a string
let text = "HELLO WORLD";
let char = text.charCodeAt(0);
String split()
A string can be converted to an array with the split() method.
text.split(",") // Split on commas
text.split(" ") // Split on spaces
text.split("|") // Split on pipe
String indexOf()
The indexOf() method returns the index of (position of) the first occurrence of a string in a string
let str = "Please locate where 'locate' occurs!";
str.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!";
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 str = "Please locate where 'locate' occurs!";
str.search("locate");
String match()
The match() method returns an array containing the results of matching a string against a string
let text = "The rain in SPAIN stays mainly in the plain";
text.match("ain");
String matchAll()
The matchAll() method returns an iterator containing the results of matching a string against a string
const iterator = text.matchAll("Cats");
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");
Classes
Classes serve as a starting point for the creation of objects. They encapsulate data with code that allows them to work with it. Classes in JS are built on prototypes, but they also have their own syntax and semantics.
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
}
let myCar1 = new Car("Ford", 2014);
let myCar2 = new Car("Audi", 2019);
Class with constructor
Class methods are created in the same way that object methods are. To create a class, use the keyword class. Include a function Object() { [native code] }() method at all times. Then you can add as many methods as you want.
Objects, in JavaScript are the most important data type and form the building blocks for modern JavaScript. These objects are quite different from JavaScript’s primitive data types (Number, String, Boolean, null, undefined, and symbol) in the sense that these primitive data types all store a single value each.
setDate method allow to set the date values (years, months, days, hours, minutes, seconds, milliseconds) for a Date Object
Set Method
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)
setDate
The setDate() method sets the day of a date object (1-31).
const d = new Date();
d.setDate(15);
setFullYear
The setFullYear() method can optionally set month and day
const d = new Date();
d.setFullYear(2020, 11, 3);
setHours
The setHours() method sets the hours of a date object (0-23).
const d = new Date();
d.setHours(22);
getMilliseconds()
getMilliseconds() returns the milliseconds (0 to 999) of a date.
const d = new Date("July 21, 1983 01:15:00:526");
let ms = d.getMilliseconds();
setMinutes
The setMinutes() method sets the minutes of a date object (0-59).
const d = new Date();
d.setMinutes(30);
setMonth
The setMonth() method sets the month of a date object (0-11)
const d = new Date();
d.setMonth(11);
setSeconds
The setSeconds() method sets the seconds of a date object (0-59).
const d = new Date();
d.setSeconds(30);
setTime
Add 1332403882588 milliseconds to January 1, 1970.
const d = new Date();
d.setTime(1332403882588);
Alert Prompt Confirm
Alert
If you want to ensure that information reaches the user, an alert box is frequently used. To proceed, the user must click "OK" when an alert box appears.
alert("I am an alert box!");
Confirm
A confirm box is frequently used when you want the user to confirm or accept something. To proceed further, the user must click "OK" or "Cancel" when a confirmation box appears. If the user presses the "OK" button, the box returns true. If the user presses the "Cancel" button, the box returns false and confirmation box disappears.
if (confirm("Press a button!")) {
txt = "You pressed OK!";
} else {
txt = "You pressed Cancel!";
}
Prompt
A prompt box is frequently used when you want the user to enter a value before proceeding to the next page. When a prompt box appears, the user must select "OK" or "Cancel" to proceed after entering an input value. When the user clicks "OK," the box returns the value entered. If the user presses the "Cancel" button, the box returns null.
let person = prompt("Please enter your name", "Harry Potter");
let text;
if (person == null || person == "") {
text = "User cancelled the prompt.";
} else {
text = "Hello " + person + "! How are you today?";
}
Sets
This article will go over the Set object provided by ES6. A set is a collection of unique items, meaning that no element can be repeated. In ES6, sets are ordered: set elements can be iterated in the insertion order. Any type of value, whether primitive or object, can be stored in a set.
Method
Description
new Set()
Creates a new Set
add()
Adds a new element to the Set
forEach()
Invokes a callback for each element in the Set
values()
Returns an iterator with all the values in a Set
new Set()
You can create a set by passing an Array to the new set() constructor.
const letters = new Set(["a","b","c"]);
forEach()
The forEach() method invokes (calls) a function for each Set element.
const letters = new Set(["a","b","c"]);let text = "";
letters.forEach (function(value) {
text += value;
})
values()
The values() method returns a new iterator object containing all the values in a Set.
letters.values()
Maps
map() generates a new array by invoking a function for each array element. For each element in an array, map() calls a function once. For empty elements, map() does not execute the function. The original array is not changed by map().
Method
Description
new Map()
Makes a new Map
set()
Sets the value of a Map key.
get()
Retrieves the value of a key in a Map.
delete()
Removes the key-specified Map element.
has()
If a key exists in a Map, this function returns true.
forEach()
For each key/value pair in a Map, this method calls a function.
entries()
Iterates through the [key, value] pairs in a Map.
setTime()
Set the time (milliseconds since January 1, 1970)
new Map()
You can create a Map by passing an Array to the new Map() constructor.
The get() method can also be used to change existing Map values.
fruits.get("apples");
Size()
The size property returns the number of elements in a Map.
fruits.size;
delete()
The delete() method removes a Map element.
fruits.delete("apples");
has()
The has() method returns true if a key exists in a Map.
fruits.has("apples");
forEach()
The forEach() method calls a function for each key/value pair in a Map.
let text = "";
fruits.forEach (function(value, key) {
text += key + ' = ' + value;
});
entries()
The entries() method returns an iterator object with the [key, values] in a Map.
let text = "";
for (const x of fruits.entries()) {
text += x;
}
Arrow
Arrow functions are one of the popular features of ES6 syntax for writing JavaScript function expressions. Arrow function expressions cannot be used as constructors. Arrow functions also called “fat arrow” functions, there are a more concise syntax for writing function expressions. By using arrow functions, we avoid having to type the function keyword, return keyword and curly brackets.