JavaScript notes
JavaScript notes
• high-level,
• prototype-based,
• dynamic scripting language
• Used to create interactive web pages and applications.
Its flexibility and front and back-end capabilities make JavaScript a popular programming language.
JavaScript Applications
Frontend Development
Backend Development
Software Development
Console Applications
Mobile Apps Development
Web Animations
Games
AR and VR
2D and 3D
Machine Learning
Data Science
Some popular facts about JavaScript.
1. Javascript is the only client side programming language for web browser.
2. JavaScript can build interactivity Websites.
3. Javascript is Object Based with prototype inheritance model for OOPS.
4. Javascript is Case Sensitive.
5. Javascript can put dynamic content into a webpage. .
6. Javascript can react to events like Mouse Click, mouse hover, mouse out, form submit etc
known as JavaScript Events.
7. Javascript can validate form data.
Internal JavaScript
<script>
document.write("Hello Javascript");
</script>
Eg:-
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>Today's Date</title>
</head>
<body>
<script>
let d = new Date();
document.body.innerHTML = "<h1>Today's date is " + d + "</h1>"
</script>
</body>
</html>
External JavaScripts In External JavaScript, javascript code is written in external file with .js extension and then linked with
script tag
The benefits of using a separate JavaScript file include:
o Separating the HTML markup and JavaScript code to make both more straightforward
o Separate files makes maintenance easier
o When JavaScript files are cached, pages load more quickly
<script src="myscript.js"></script>
Inline Javascript
In Inline Javascript, javascript code is written directly inside html tags.
Eg:-
<button onclick="alert('Hello JS')">Check</button>
<marquee onmouseover="stop()" onmouseout="start()">Hello Javascript</marquee>
<a href="javascript:void(0)" onclick="print()">Print</a>
Project Structure
project/
├── css/
| └──mystyle.css
├── js/
| └── myscript.js
└── index.html
<script>
alert(x);
</script>
JS Prompt, prompt()
prompt() or window.prompt() dialog box is used to receive input from user. The default datatype of prompt object
is string. But id cancelled, it will return null.
<script>
alert(x);
</script>
JS Confirm, confirm()
confirm() or window.confirm() dialog box is used to get confirmation from user. This will show ok or Cancel in
dialog box. ok will return true and cancel will return false.
<script>
alert(x);
</script>
JavaScript Comments
Comments are used to write explanations, hints, and to stop execution of code. JavaScript use two
comments syntax. One is Single line comment, and second is Multi-line comment.
<script>
</script>
<script>
/* Multi-line Comment */
</script>
Variables in JavaScript
This is also knows as dynamic typing. Means a variable x (var x) can store any type of data, like string,
number, function, boolean, undefined, null, array or object.
<script>
var u; // u is undefined
</script>
➢ variables names cannot include javascript reserved keywords, like var, for, in, while,
true, false, null, class, let, const, function etc.
➢ variables cannot starts with numbers and hyphen, use alphabets, underscore(_) or
dollar ($).
➢ variables can have strings followed by numbers, like x1 and x2 are allowed but 1x, 2x
is not allowed.
➢ For separation in variable names, use underscore (_) or camel casing, do not use
hyphen (-) separation and white space, i.e, user_name is valid, username is also
valid, but user-name is invalid.
➢ variables names are case sensitive, i.e, x1 and X1 are different.
Variables declared outside function are global variables and variable declared inside function are local
variables.
Global Variables
Global variables have global scope. This means, a variable in <script> tag is by default global. Global Variable
once declared can be used anywhere, even inside a function.
Eg:-
console.log(y); // returns 88
function myFunction()
console.log(y); // returns 88
Local Variable
Variables declared inside functions are local variables. Local Variables have local scope. This means they are
accessible only within their function block, not outside.
function myFunction(){
let and const were introduced in ECMA 6(European Computer Manufacturers Association).
let is used to declare temporary values with block scope, inside {} . Whereas const is used to declare
permanent values, which can't be change. Like value of pi
JavaScript let
JavaScript let is used to declare variable in block scope. The value of let is only accessible inside block.
<script>
</script>
Eg:-
<script>
if(i==2)
console.log(i); // 3
console.log(i); // 2
</script>
JavaScript const
JavaScript const is used to declared immutable values, i.e fixed values which are not changeable.
Const can't be undefined.
<script>
</script>
<script>
const user="avi";
</script>
var is function scoped, but let and const are block scoped. let and const are replacement of var in JS ES6 and
onwards. Here is table of comparison of var, let and const.
Javascript DataTypes
As JavaScript and all scripting languages are loosely typed, there is no typecast in javascript. JS supports
dynamic typing . We can create any type of data using a single variable.
var means a variable which can store any type of data. Data type of variable is not declared.
Declaring var means creating a new variable in memory with variable name after white-space. Assignment
Operator (=) means assigning value to variable declared.
Datatypes in JavaScript
Primitive datatypes are the basic or common data types in javascript. Like string, numbers, boolean, undefined
and null. They are very commonly used data types.
var x; undefined
var x=undefined; undefined
Even Arrays and Functions are objects, but they are build-in objects.
typeof Operator
typeof operator in javascript is used to check data type of a variable. It can return string, number, boolean and
undefined. For reference type and null, typeof operator will return object.
var x; // undefined
Operators
JavaScript has both binary and unary operator including one ternary operator (conditional operator).
binary operator
Binary operators required two operands, one before and one after operator. x+y=z
Eg:-
Unary Operator
Unary operators required only one operand, either before or after operator. i++
x++
++x
Ternary Operator
+ Addition 2+3=5
- Subtraction 5-3=2
* Multiply 2*3=6
/ Divide 6/3=2
% Reminder 6%3=0
Logical Operators are used to check logic between two operators. and (&&), or (||) and not (!) are logical
operators.
&& and, when both are correct 2 < 5 && 2> 1 is true
|| or, when any one is correct var x=2, 2>5 || x==2 is true
Assignment Operators
Assignment operators ars used to assign some value to js variables. =, +=, -=, *=, /= are all assignment
operators in javascript.
Comparision Operators
If statement
Example:-
<html>
<body>
<!--
//-->
</script>
</body>
</html>
if...else statement
The 'if...else' statement is the next form of control statement that allows JavaScript to execute statements in a more controlled way.
Syntax
if (expression) {
} else {
}
Example
Try the following code to learn how to implement an if-else statement in JavaScript.
<html>
<body>
<!--
} else {
//-->
</script>
</body>
</html>
The if...else if... statement is an advanced form of if…else that allows JavaScript to make a correct decision out of several conditions.
Syntax
if (expression 1) {
} else if (expression 2) {
} else if (expression 3) {
} else {
Example
<html>
<body>
<!--
document.write("<b>Maths Book</b>");
document.write("<b>Economics Book</b>");
} else {
document.write("<b>Unknown Book</b>");
//-->
</script>
</body>
</html>
You can use multiple if...else…if statements, as in the previous chapter, to perform a multiway branch
Syntax
switch (expression) {
break;
break;
break;
default: statement(s)
Example
<html>
<body>
<!--
switch (grade) {
break;
break;
case 'C': document.write("Passed<br />");
break;
break;
break;
//-->
</script>
</body>
</html>
JavaScript -Loopings
Types
For loop
While loop
Do while loop
For loop
The 'for' loop is the most compact form of looping. It includes the following three important parts −
The loop initialization where we initialize our counter to a starting value. The initialization statement is executed before the loop begins.
The test statement which will test if a given condition is true or not. If the condition is true, then the code given inside the loop will be
executed, otherwise the control will come out of the loop.
The iteration statement where you can increase or decrease your counter.
Syntax
Example:-
<html>
<body>
<!--
var count;
document.write("Starting Loop" + "<br />");
document.write("<br />");
document.write("Loop stopped!");
//-->
</script>
</body>
</html>
While loop
Syntax
while (expression)
Example:-
<html>
<body>
<!--
var count = 0;
count++;
document.write("Loop stopped!");
//-->
</script>
</body>
</html>
The do...while Loop
The do...while loop is similar to the while loop except that the condition check happens at the end of the loop. This means
that the loop will always be executed at least once, even if the condition is false.
Syntax
do {
Statement(s) to be executed;
} while (expression);
Example
<html>
<body>
<!--
var count = 0;
do {
count++;
//-->
</script>
</body>
</html>
JavaScript Arrays
The Array object lets you store multiple values in a single variable.
An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the
same type.
Syntax
eg:-
<html>
<script>
var names=["raja","kumar","mani","ram","madan","martin"];
// or
names=new Array("raja","kumar","mani","ram","madan","martin");
document.write(names);
document.write("<br>"+names);
</script>
</html>
for(var i=0;i<2;i++)
for(var j=0;j<3;j++)
document.write(a[i][j]+"<br>");
array.splice(indexValue, 1);
<html>
<body>
<script>
x=new Array();
names=new Array();
age=new Array();
sal=new Array();
for(i=0;i<x;i++)
names[i]=prompt("enter name");
age[i]=prompt("enter age");
sal[i]=prompt("enter salary");
for(j=0;j<x;j++)
</script>
</body>
</html>
JavaScript Functions
What is functions?
A function is a group of reusable code which can be called anywhere in your program. T
This eliminates the need of writing the same code again and again.
Functions allow a programmer to divide a big program into a number of small and manageable functions.
Function Definition
The most common way to define a function in JavaScript is by using the function keyword, followed by a unique function
name, a list of parameters (that might be empty), and a statement block surrounded by curly braces.
Syntax
<!--
function functionname(parameter-list)
statements
//-->
</script>
<html>
<head>
function sayHello() {
</script>
</head>
<body>
<form>
</form>
</body>
</html>
Function Parameters
Example
Try the following example. We have modified our sayHello function here. Now it takes two parameters.
<html>
<head>
</script>
</head>
<body>
<form>
</form>
</body>
</html>
A JavaScript function can have an optional return statement. This is required if you want to return a value from a function.
This statement should be the last statement in a function.
<html>
<head>
var full;
return full;
function secondFunction() {
var result;
document.write (result );
</script>
</head>
<body>
<form>
</body>
</html>
JavaScript is an Object Oriented Programming (OOP) language. A programming language can be called object-oriented if it
provides four basic capabilities to developers −
Encapsulation − the capability to store related information, whether data or methods, together in an object.
Inheritance − the capability of a class to rely upon another class (or number of classes) for some of its properties and
methods.
Polymorphism − the capability to write one function or method that works in a variety of different ways.
The new operator is used to create an instance of an object. To create an object, the new operator is followed by the
constructor method.
In the following example, the constructor methods are Object(), Array(), and Date(). These constructors are built-in
JavaScript functions.
Example
<html>
<head>
<title>User-defined objects</title>
book.author = "Mohtashim";
book.price=1000.00;
book.pub="Abc";
</script>
</head>
<body>
document.write(book);
</script>
</body>
</html>
how to create an object with a User-Defined Function. Here this keyword is used to refer to the object that has been passed
to a function.
<html>
<head>
<title>User-defined objects</title>
title=”undefined”;
author=”undefined”;
this.title = title;
this.author = author;
</script>
</head>
<body>
</script>
</body>
</html>
Example
<html>
<script>
//Defining object
let person = {
first_name:'Mukul',
last_name: 'Latiyan',
//method
getFunction : function()
},
phone_number :
mobile:'12345',
landline:'6789'
console.log(person.getFunction());
console.log(person.phone_number.landline);
</script>
</html>
JavaScript Strings
Strings are collection of characters stored inside quotes ( double or single) or back tick (in ES6). Strings
represents text and can have lower case, upper case, special characters or numbers within quotes.
Strings can store data, like name, email id, age etc. Default datatype for input, select, textarea value is always a
string.
In JavaScript, Strings are declared inside double quotes "" or single quotes ''.
Eg:-
var x=3;
var y=5;
Template literals can also add multi-line strings. Till ES5, we use + operator to do the same. See example of
Multi line string .
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
</body>
</html>’;
String.length
x.length; // 8
String Methods
indexOf
indexOf methods returns index of first matched substring. The return value of indexOf methods is always a
number.
x.indexOf("i")
x.indexOf("m")
lastIndexOf
lastIndexOf methods returns index of last matched substring. The return value of lastIndexOf method will also
be number.
var x="Elysium";
x.indexOf("s")
x.lastIndexOf("y")
x.lastIndexOf("e")
concat
concat method is used to concatenate or merge two strings into one. The second string should be passed as
argument.
var x="Elysium";
var y="Academy”;
x.concat(y);
var x="Elysium";
var y="Academy”;
x+y;
charAt
var x="Elysium”;
x.charAt(0); // return E
x.charAt(1); // return l
x.charAt(x.length-1); // return m
charCodeAt
var x="Elysium”;
x.charCodeAt(0);
x.charCodeAt(1);
toUpperCase
x.toUpperCase();
x.toLowerCase();
substr
substr method return substrings from index (first argument ) to given no of characters (second argument). First
argument is always index and second is no of characters. If second argument is missing, it will return substrings
after first index.
var x="HelloWorld”;
search
search method search for a matched pattern between string and regular expression and return index of
matched pattern.
x.search("E"); // return 0
x.search("M"); // return -1
x=”AAdmin”
trim
Example
// defining a string
console.log(len);
// Output:
// 17
The charAt() method returns the character at the specified index in a string.
Example
// string declaration
// Output:
// Character at index 1 is e
The charCodeAt() method returns an integer between 0 and 65535 representing the UTF-16 code
unit at the given index.
Example
// string definition
console.log(result);
// Output: 109
Example
console.log(joinedString);
Example
console.log(joinedArrays);
/* Output:
2, 3, 5, 7,
2, 4, 6, 8
*/
The slice() method returns a shallow copy of a portion of an array into a new array object.
Example
console.log(newArray);
// Output: [ 7, 11, 13 ]
The some() method tests whether any of the array elements pass the given test function.
Example
function isEven(element) {
// defining an array
console.log(numbers.some(isEven));
// Output: true
The sort() method sorts the items of an array in a specific order (ascending or descending).
Example
console.log(sortedArray);
The splice() method returns an array by changing (adding/removing) its elements in place.
Example
console.log(removedElement);
console.log(prime_numbers);
// Output: [ 9 ]
// [ 2, 3, 5, 7, 13, 11 ]
The toLocaleString() method returns a string representing the elements of the array in a particular
locale.
Example
console.log(stringFromArray);
// Output:
// Nepal,1
The toString() method returns a string formed by the elements of the given array.
Example
// defining an array
console.log(itemsString);
// Output:
// JavaScript,1,a,3
The push() method adds zero or more elements to the end of the array.
Example
city.push("London");
console.log(city);
The reduce() method executes a reducer function on each element of the array and returns a single
output value.
Example
}
// reduce join each element of the string
console.log(joinedString);
Example
console.log(reversedArray);
// Output: [ 5, 4, 3, 2, 1 ]