Java Script - Detailed Syllabus
Java Script - Detailed Syllabus
Day-1........................................................................................................................................................8
What is JavaScript..............................................................................................................................8
Features of JavaScript......................................................................................................................8
History of JavaScript.........................................................................................................................9
Application of JavaScript.................................................................................................................9
JavaScript Example......................................................................................................................10
3 Places to put JavaScript code....................................................................................................10
1) JavaScript Example : code between the body tag...............................................................10
2) JavaScript Example : code between the head tag...............................................................11
External JavaScript file...........................................................................................................................11
Advantages of External JavaScript..............................................................................................12
Disadvantages of External JavaScript........................................................................................13
Day-2......................................................................................................................................................13
Editors and Their Features...................................................................................................................13
1. Atom..........................................................................................................................................13
2. Notepad++..............................................................................................................................14
3. Sublime Text...........................................................................................................................14
4. Adobe Dreamweaver CC....................................................................................................14
5. Visual Studio Code..............................................................................................................15
Day-3......................................................................................................................................................16
JavaScript output.......................................................................................................................................16
JavaScript Display Possibilities..........................................................................................16
Using innerHTML.........................................................................................................................16
Example........................................................................................................................................16
Using document.write()..........................................................................................................17
Example........................................................................................................................................17
Using window.alert()................................................................................................................17
Example........................................................................................................................................17
Using console.log()....................................................................................................................18
Example........................................................................................................................................18
JavaScript Print............................................................................................................................18
Example........................................................................................................................................18
JavaScript Operators..............................................................................................................................19
JavaScript Arithmetic Operators..................................................................................................19
JavaScript Comparison Operators...............................................................................................20
JavaScript Bitwise Operators........................................................................................................21
JavaScript Logical Operators........................................................................................................21
JavaScript Assignment Operators...............................................................................................22
JavaScript Special Operators........................................................................................................22
Practical on JavaScript operators...............................................................................................................24
JavaScript Assignment.............................................................................................................24
Assignment Examples..........................................................................................................24
JavaScript Addition....................................................................................................................25
Adding...........................................................................................................................................25
JavaScript Multiplication........................................................................................................25
Multiplying..................................................................................................................................26
JavaScript String Comparison..............................................................................................26
Example........................................................................................................................................27
JavaScript Type Operators.....................................................................................................28
JavaScript Bitwise Operators...............................................................................................28
JavaScript Data Types........................................................................................................................30
JavaScript has 8 Datatypes...............................................................................................30
The Object Datatype.............................................................................................................30
The Concept of Data Types...................................................................................................31
Note....................................................................................................................................................31
JavaScript:...................................................................................................................................32
JavaScript Types are Dynamic.............................................................................................32
Example........................................................................................................................................32
JavaScript Strings.......................................................................................................................32
Example........................................................................................................................................32
JavaScript If-else....................................................................................................................................34
JavaScript If statement................................................................................................................34
JavaScript If...else Statement....................................................................................................35
Flowchart of JavaScript If...else statement............................................................................36
avaScript If...else if statement...................................................................................................37
JavaScript Switch...................................................................................................................................38
JavaScript while loop......................................................................................................................39
JavaScript For loop..........................................................................................................................40
Functions...................................................................................................................................................42
Defining functions..................................................................................................................................42
Function declarations........................................................................................................................42
Function expressions.........................................................................................................................43
Calling functions....................................................................................................................................45
Function hoisting...............................................................................................................................46
Day-12...............................................................................................................................................47
Function scope......................................................................................................................................47
Scope and the function stack.................................................................................................................47
Recursion...........................................................................................................................................47
Nested functions and closures...........................................................................................................49
Preservation of variables...................................................................................................................50
Multiply-nested functions..................................................................................................................50
Name conflicts...................................................................................................................................51
Closures.................................................................................................................................................52
Using the arguments object...................................................................................................................54
Function parameters.............................................................................................................................55
Default parameters............................................................................................................................55
Rest parameters.................................................................................................................................55
Arrow functions.....................................................................................................................................56
Shorter functions...............................................................................................................................56
No separate this.................................................................................................................................56
JavaScript Arrays........................................................................................................................................58
Introduction......................................................................................................................................58
Creating an Array................................................................................................................................60
Day-15...............................................................................................................................................62
Indexing Arrays...................................................................................................................................62
Accessing Items in an Array..............................................................................................................63
Adding an Item to an Array................................................................................................................64
Removing an Item from an Array......................................................................................................66
Modifying Items in Arrays...................................................................................................................68
Looping Through an Array.................................................................................................................69
JavaScript Sorting Arrays..................................................................................................................71
Sorting an Array..........................................................................................................................71
Example........................................................................................................................................71
Reversing an Array....................................................................................................................71
Example........................................................................................................................................71
Numeric Sort.................................................................................................................................71
Example........................................................................................................................................72
Example........................................................................................................................................72
The Compare Function.............................................................................................................72
Sorting an Array in Random Order...................................................................................74
Example........................................................................................................................................74
The Fisher Yates Method........................................................................................................74
Example........................................................................................................................................75
Find the Lowest (or Highest) Array Value....................................................................75
Example........................................................................................................................................75
Example........................................................................................................................................75
Using Math.max() on an Array............................................................................................76
Example........................................................................................................................................76
Using Math.min() on an Array.............................................................................................76
Example........................................................................................................................................76
My Min / Max JavaScript Methods.....................................................................................76
Example (Find Max)...............................................................................................................76
Example (Find Min)................................................................................................................77
Sorting Object Arrays...............................................................................................................77
Example........................................................................................................................................77
Example........................................................................................................................................78
Example........................................................................................................................................78
Stable Array sort().....................................................................................................................78
What Is an Object?.................................................................................................................................80
JavaScript String.....................................................................................................................................85
1) By string literal.............................................................................................................................85
JavaScript String Methods................................................................................................................86
Note....................................................................................................................................................86
JavaScript String Length........................................................................................................86
Example........................................................................................................................................86
Extracting String Parts............................................................................................................86
JavaScript String slice()..........................................................................................................87
Example........................................................................................................................................87
Note....................................................................................................................................................87
Examples......................................................................................................................................87
JavaScript String substring()...............................................................................................87
Example........................................................................................................................................87
JavaScript String substr()......................................................................................................88
Example........................................................................................................................................88
Example........................................................................................................................................88
Example........................................................................................................................................88
Replacing String Content.......................................................................................................88
Example........................................................................................................................................88
JavaScript String ReplaceAll().............................................................................................89
Example........................................................................................................................................89
Example........................................................................................................................................89
Note....................................................................................................................................................89
Converting to Upper and Lower Case.............................................................................89
JavaScript String toUpperCase()........................................................................................90
Example........................................................................................................................................90
JavaScript String toLowerCase()........................................................................................90
Example........................................................................................................................................90
JavaScript String concat().....................................................................................................90
Example........................................................................................................................................90
Example........................................................................................................................................90
Note....................................................................................................................................................90
JavaScript String trim()...........................................................................................................91
Example........................................................................................................................................91
JavaScript String trimStart()................................................................................................91
Example........................................................................................................................................91
JavaScript Get Date Methods..........................................................................................................92
The new Date() Constructor.................................................................................................92
Get the Current Time............................................................................................................92
Date Get Methods.......................................................................................................................92
Note 1................................................................................................................................................93
Note 2................................................................................................................................................93
The getFullYear() Method......................................................................................................94
Examples......................................................................................................................................94
JavaScript Events................................................................................................................................95
HTML Events..................................................................................................................................95
Example........................................................................................................................................96
Example........................................................................................................................................96
Example........................................................................................................................................96
Common HTML Events.............................................................................................................96
JavaScript Event Handlers.....................................................................................................97
AngularJS Introduction.......................................................................................................................98
AngularJS is a JavaScript Framework..............................................................................98
AngularJS Extends HTML........................................................................................................98
AngularJS Example.................................................................................................................99
AngularJS Directives...............................................................................................................100
AngularJS Example...............................................................................................................100
AngularJS Example...............................................................................................................100
AngularJS Expressions...........................................................................................................100
AngularJS Example...............................................................................................................100
AngularJS Example...............................................................................................................101
AngularJS ng-model Directive.......................................................................................................102
The ng-model Directive.........................................................................................................102
Example......................................................................................................................................102
Two-Way Binding.......................................................................................................................102
Example......................................................................................................................................103
Validate User Input..................................................................................................................103
Example......................................................................................................................................103
Application Status....................................................................................................................103
Example......................................................................................................................................103
CSS Classes..................................................................................................................................104
Example......................................................................................................................................104
Data Model...................................................................................................................................105
Example......................................................................................................................................105
HTML View....................................................................................................................................105
Example......................................................................................................................................105
Example......................................................................................................................................105
The ng-model Directive...........................................................................................................106
Example......................................................................................................................................106
Two-way Binding.......................................................................................................................106
Example......................................................................................................................................106
AngularJS Controller...............................................................................................................107
Example......................................................................................................................................107
AngularJS Filters.................................................................................................................................108
AngularJS Filters.......................................................................................................................108
Adding Filters to Expressions............................................................................................108
Example......................................................................................................................................108
Example......................................................................................................................................109
Adding Filters to Directives................................................................................................109
Example......................................................................................................................................109
The currency Filter..................................................................................................................109
Example......................................................................................................................................110
The filter Filter...........................................................................................................................110
Example......................................................................................................................................110
Filter an Array Based on User Input..............................................................................110
Example......................................................................................................................................111
Sort an Array Based on User Input.................................................................................111
Example......................................................................................................................................112
Custom Filters............................................................................................................................113
Example......................................................................................................................................113
Day-1
What is JavaScript
JavaScript (js) is a light-weight object-oriented programming language which
is used by several websites for scripting the webpages. It is an interpreted,
full-fledged programming language that enables dynamic interactivity on
websites when applied to an HTML document. It was introduced in the year
1995 for adding programs to the webpages in the Netscape Navigator
browser. Since then, it has been adopted by all other graphical web
browsers. With JavaScript, users can build modern web applications to
interact directly without reloading the page every time. The traditional
website uses js to provide several forms of interactivity and simplicity.
Features of JavaScript
There are following features of JavaScript:
1. All popular web browsers support JavaScript as they provide built-in execution
environments.
2. JavaScript follows the syntax and structure of the C programming language.
Thus, it is a structured programming language.
3. JavaScript is a weakly typed language, where certain types are implicitly cast
(depending on the operation).
4. JavaScript is an object-oriented programming language that uses prototypes
rather than using classes for inheritance.
5. It is a light-weighted and interpreted language.
6. It is a case-sensitive language.
7. JavaScript is supportable in several operating systems including, Windows,
macOS, etc.
8. It provides good control to the users over the web browsers.
History of JavaScript
In 1993, Mosaic, the first popular web browser, came into existence. In
the year 1994, Netscape was founded by Marc Andreessen. He realized
that the web needed to become more dynamic. Thus, a 'glue language' was
believed to be provided to HTML to make web designing easy for designers
and part-time programmers. Consequently, in 1995, the company
recruited Brendan Eich intending to implement and embed Scheme
programming language to the browser. But, before Brendan could start, the
company merged with Sun Microsystems for adding Java into its Navigator
so that it could compete with Microsoft over the web technologies and
platforms. Now, two languages were there: Java and the scripting language.
Further, Netscape decided to give a similar name to the scripting language
as Java's. It led to 'Javascript'. Finally, in May 1995, Marc Andreessen coined
the first code of Javascript named 'Mocha'. Later, the marketing team
replaced the name with 'LiveScript'. But, due to trademark reasons and
certain other reasons, in December 1995, the language was finally renamed
to 'JavaScript'. From then, JavaScript came into existence.
Application of JavaScript
JavaScript is used to create interactive websites. It is mainly used for:
o Client-side validation,
o Dynamic drop-down menus,
o Displaying date and time,
o Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm
dialog box and prompt dialog box),
o Displaying clocks etc.
JavaScript Example
<script>
document.write("Hello JavaScript by JavaScript");
</script>
1. <script type="text/javascript">
2. document.write("JavaScript is a simple language for javatpoint learners");
3. </script>
1. <script type="text/javascript">
2. alert("Hello Javatpoint");
3. </script>
2) JavaScript Example : code between the head tag
Let’s see the same example of displaying alert dialog box of JavaScript that
is contained inside the head tag.
To call function, you need to work on event. Here we are using onclick event
to call msg() function.
1. <html>
2. <head>
3. <script type="text/javascript">
4. function msg(){
5. alert("Hello Javatpoint");
6. }
7. </script>
8. </head>
9. <body>
10.<p>Welcome to JavaScript</p>
11. <form>
12.<input type="button" value="click" onclick="msg()"/>
13. </form>
14.</body>
15. </html>
Let's create an external JavaScript file that prints Hello Javatpoint in a alert
dialog box.
message.js
1. function msg(){
2. alert("Hello Javatpoint");
3. }
Let's include the JavaScript file into html page. It calls the JavaScript
function on button click.
index.html
1. <html>
2. <head>
3. <script type="text/javascript" src="message.js"></script>
4. </head>
5. <body>
6. <p>Welcome to JavaScript</p>
7. <form>
8. <input type="button" value="click" onclick="msg()"/>
9. </form>
10.</body>
11. </html>
Advantages of External JavaScript
There will be following benefits if a user creates an external javascript:
1. The stealer may download the coder's code using the url of the js file.
2. If two js files are dependent on one another, then a failure in one file may
affect the execution of the other dependent file.
3. The web browser needs to make an additional http request to get the js code.
4. A tiny to a large change in the js code may cause unexpected results in all its
dependent files.
5. We need to check each file that depends on the commonly created external
javascript file.
6. If it is a few lines of code, then better to implement the internal javascript
code.
Day-2
1. Atom
Atom is an open source and free code editor. It was released by
GitHub in 2014.
GitHub and can be used by the developers to extend and edit its
source code.
Atom supports multiple sections within a single interface thus
helping the developers to write code side by side.
It also provides flexible auto-completion and syntax correction
along with cross-platform editing.
2. Notepad++
Notepad++ is a free,open-source, multi-language code editor which
was initially developed for Windows-based computers. It uses
‘Scintilla’ as the editing component and is written in C++.
Key Features
It has the provision of simultaneous editing i.e. it is possible to
apply changes to several domains at a particular time.
It provides many actions such as- command palette, file
switching,goto symbols,multi-edit,alignment,bracket-
highlighter,etc.
Sublime falls under the category of freemium software i.e. we
need to pay additional money to enjoy all its features.
Some of the packages of sublime are open-source and are
available on git.
4. Adobe Dreamweaver CC
Adobe Dreamweaver CC has been developed by Adobe Inc.
However, it is a closed-source software and works well only within
an Adobe ecosystem.
Key Features
It has proven to be an important tool in the domain of web-
Key Features
It has the features of built-in Git commands, debugging of code
right from the editor, live preview of the web from server, smart
code-completion using IntelliSense and many more.
It’s a free and open-source software that is one of the most
popular developers’ tool.
The most prominent feature of Visual Studio Code is its
interactive debugger which enables execution of debugging
commands on the console.
IntelliSense of VS Code has proven to be extremely beneficial
for code understanding, navigation and refactoring.
Day-3
JavaScript output
JavaScript Display Possibilities
Using innerHTML
To access an HTML element, JavaScript can use
the document.getElementById(id) method.
The id attribute defines the HTML element. The innerHTML property defines the
HTML content:
Example
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
</html>
Using document.write()
For testing purposes, it is convenient to use document.write():
Example
<!DOCTYPE html>
<html>
<body>
<script>
document.write(5 + 6);
</script>
</body>
</html>
Using window.alert()
You can use an alert box to display data:
Example
<!DOCTYPE html>
<html>
<body>
<script>
window.alert(5 + 6);
</script>
</body>
</html>
Using console.log()
For debugging purposes, you can call the console.log() method in the browser
to display data.
Example
<!DOCTYPE html>
<html>
<body>
<script>
console.log(5 + 6);
</script>
</body>
</html>
JavaScript Print
JavaScript does not have any print object or print methods.
The only exception is that you can call the window.print() method in the browser
to print the content of the current window.
Example
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Day-4
JavaScript Operators
JavaScript operators are symbols that are used to perform operations on
operands. For example:
1. var sum=10+20;
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators
+ Addition 10+20 = 30
- Subtraction 20-10 = 10
* Multiplication 10*20 = 200
/ Division 20/10 = 2
= Assign 10+10 = 20
Operator Description
(?:) Conditional Operator returns value based on the condition. It is like if-
else.
Assignment Examples
let x = 10;
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Operators</h1>
<h2>The Assignment (=) Operator</h2>
<p id="demo"></p>
<script>
// Assign the value 5 to x
let x = 5;
// Assign the value 2 to y
let y = 2;
// Assign the value x + y to z
let z = x + y;
// Display z
document.getElementById("demo").innerHTML = "The sum of x + y is: " + z;
</script>
</body>
</html>
JavaScript Addition
The Addition Operator (+) adds numbers:
Adding
let x = 5;
let y = 2;
let z = x + y;
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arithmetic</h1>
<h2>The * Operator</h2>
<p id="demo"></p>
<script>
let x = 5;
let y = 2;
let z = x * y;
document.getElementById("demo").innerHTML = z;
</script>
</body>
</html>
JavaScript Multiplication
The Multiplication Operator (*) multiplies numbers:
Multiplying
let x = 5;
let y = 2;
let z = x * y;
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arithmetic</h1>
<h2>The * Operator</h2>
<p id="demo"></p>
<script>
let x = 5;
let y = 2;
let z = x * y;
document.getElementById("demo").innerHTML = z;
</script>
</body>
</html>
Example
let text1 = "A";
let text2 = "B";
let result = text1 < text2;
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
let text1 = "A";
let text2 = "B";
let result = text1 < text2;
document.getElementById("demo").innerHTML = "Is A less than B? " +
result;
</script>
</body>
</html>
Any numeric operand in the operation is converted into a 32 bit number. The
result is converted back to a JavaScript number.
1. An object
2. An array
3. A date
// Numbers:
let length = 16;
let weight = 7.5;
// Strings:
let color = "Yellow";
let lastName = "Johnson";
// Booleans
let x = true;
let y = false;
// Object:
const person = {firstName:"John", lastName:"Doe"};
// Array object:
const cars = ["Saab", "Volvo", "BMW"];
// Date object:
const date = new Date("2022-03-25");
let x = 16 + "Volvo";
Does it make any sense to add "Volvo" to sixteen? Will it produce an error or will
it produce a result?
Note
When adding a number and a string, JavaScript will treat the number as a string.
let x = 16 + "Volvo";
let x = "Volvo" + 16;
Example
let x; // Now x is undefined
x = 5; // Now x is a Number
x = "John"; // Now x is a String
JavaScript Strings
A string (or a text string) is a series of characters like "John Doe".
Strings are written with quotes. You can use single or double quotes:
Example
// Using double quotes:
let carName1 = "Volvo XC60";
You can use quotes inside a string, as long as they don't match the quotes
surrounding the string:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Strings</h2>
<p>You can use quotes inside a string, as long as they don't match the
quotes surrounding the string:</p>
<p id="demo"></p>
<script>
let answer1 = "It's alright";
let answer2 = "He is called 'Johnny'";
let answer3 = 'He is called "Johnny"';
document.getElementById("demo").innerHTML =
answer1 + "<br>" +
answer2 + "<br>" +
answer3;
</script>
</body>
</html>
Day-7
JavaScript If-else
The JavaScript if-else statement is used to execute the code whether
condition is true or false. There are three forms of if statement in JavaScript.
1. If Statement
2. If else statement
3. if else if statement
JavaScript If statement
It evaluates the content only if expression is true. The signature of JavaScript
if statement is given below.
if(expression){
//content to be evaluated
}
Flowchart of JavaScript If statement
Let’s see the simple example of if statement in java script.
1. <script>
2. var a=20;
3. if(a>10){
4. document.write("value of a is greater than 10");
5. }
6. </script>
1. if(expression){
2. //content to be evaluated if condition is true
3. }
4. else{
5. //content to be evaluated if condition is false
6. }
Flowchart of JavaScript If...else statement
Let’s see the example of if-else statement in JavaScript to find out the even
or odd number.
<script>
var a=20;
if(a%2==0){
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>
if(expression1){
//content to be evaluated if expression1 is true
}
else if(expression2){
//content to be evaluated if expression2 is true
}
else if(expression3){
//content to be evaluated if expression3 is true
}
else{
//content to be evaluated if no expression is true
}
<script>
var a=20;
if(a==10){
document.write("a is equal to 10");
}
else if(a==15){
document.write("a is equal to 15");
}
else if(a==20){
document.write("a is equal to 20");
}
else{
document.write("a is not equal to 10, 15 or 20");
}
</script>
JavaScript Switch
The JavaScript switch statement is used to execute one code from
multiple expressions. It is just like else if statement that we have learned in
previous page. But it is convenient than if..else..if because it can be used
with numbers, characters etc.
<script>
var grade='B';
var result;
switch(grade){
case 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade";
}
document.write(result);
</script>
Day-8
JavaScript while loop
The JavaScript while loop iterates the elements for the infinite number of
times. It should be used if number of iteration is not known. The syntax of
while loop is given below.
while (condition)
{
code to be executed
}
<!DOCTYPE html>
<html>
<body>
<script>
var i=11;
while (i<=15)
{
document.write(i + "<br/>");
i++;
}
</script>
</body>
</html>
Day-9
JavaScript For loop
<!DOCTYPE html>
<html>
<body>
<script>
document.write(i + "<br/>")
</script>
</body>
</html>
Day-11
Functions
Functions are one of the fundamental building blocks in JavaScript. A function in
JavaScript is similar to a procedure—a set of statements that performs a task or
calculates a value, but for a procedure to qualify as a function, it should take some
input and return an output where there is some obvious relationship between the
input and the output. To use a function, you must define it somewhere in the scope
from which you wish to call it.
Defining functions
Function declarations
For example, the following code defines a simple function named square:
JSCopy to Clipboard
function square(number) {
return number * number;
}
The function square takes one parameter, called number. The function consists of one statement
that says to return the parameter of the function (that is, number) multiplied by itself.
The return statement specifies the value returned by the function, which is number * number.
Parameters are essentially passed to functions by value — so if the code within the body of a
function assigns a completely new value to a parameter that was passed to the function, the
change is not reflected globally or in the code which called that function.
When you pass an object as a parameter, if the function changes the object's properties, that
change is visible outside the function, as shown in the following example:
JSCopy to Clipboard
function myFunc(theObject) {
theObject.make = "Toyota";
}
const mycar = {
make: "Honda",
model: "Accord",
year: 1998,
};
console.log(mycar.make); // "Honda"
myFunc(mycar);
console.log(mycar.make); // "Toyota"
When you pass an array as a parameter, if the function changes any of the array's values, that
change is visible outside the function, as shown in the following example:
JSCopy to Clipboard
function myFunc(theArr) {
theArr[0] = 30;
}
console.log(arr[0]); // 45
myFunc(arr);
console.log(arr[0]); // 30
Function expressions
While the function declaration above is syntactically a statement, functions can also be created
by a function expression.
Such a function can be anonymous; it does not have to have a name. For example, the
function square could have been defined as:
JSCopy to Clipboard
const square = function (number) {
return number * number;
};
console.log(square(4)); // 16
However, a name can be provided with a function expression. Providing a name allows the
function to refer to itself, and also makes it easier to identify the function in a debugger's stack
traces:
JSCopy to Clipboard
const factorial = function fac(n) {
return n < 2 ? 1 : n * fac(n - 1);
};
console.log(factorial(3)); // 6
Function expressions are convenient when passing a function as an argument to another function.
The following example shows a map function that should receive a function as first argument
and an array as second argument:
JSCopy to Clipboard
function map(f, a) {
const result = new Array(a.length);
for (let i = 0; i < a.length; i++) {
result[i] = f(a[i]);
}
return result;
}
In the following code, the function receives a function defined by a function expression and
executes it for every element of the array received as a second argument:
JSCopy to Clipboard
function map(f, a) {
const result = new Array(a.length);
for (let i = 0; i < a.length; i++) {
result[i] = f(a[i]);
}
return result;
}
In JavaScript, a function can be defined based on a condition. For example, the following
function definition defines myFunc only if num equals 0:
JSCopy to Clipboard
let myFunc;
if (num === 0) {
myFunc = function (theObject) {
theObject.make = "Toyota";
};
}
In addition to defining functions as described here, you can also use the Function constructor to
create functions from a string at runtime, much like eval().
A method is a function that is a property of an object. Read more about objects and methods
in Working with objects.
Calling functions
Defining a function does not execute it. Defining it names the function and specifies what to do
when the function is called.
Calling the function actually performs the specified actions with the indicated parameters. For
example, if you define the function square, you could call it as follows:
JSCopy to Clipboard
square(5);
The preceding statement calls the function with an argument of 5. The function executes its
statements and returns the value 25.
Functions must be in scope when they are called, but the function declaration can
be hoisted (appear below the call in the code). The scope of a function declaration is the function
in which it is declared (or the entire program, if it is declared at the top level).
The arguments of a function are not limited to strings and numbers. You can pass whole objects
to a function. The showProps() function (defined in Working with objects) is an example of a
function that takes an object as an argument.
A function can call itself. For example, here is a function that computes factorials recursively:
JSCopy to Clipboard
function factorial(n) {
if (n === 0 || n === 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
JSCopy to Clipboard
console.log(factorial(1)); // 1
console.log(factorial(2)); // 2
console.log(factorial(3)); // 6
console.log(factorial(4)); // 24
console.log(factorial(5)); // 120
There are other ways to call functions. There are often cases where a function needs to be called
dynamically, or the number of arguments to a function vary, or in which the context of the
function call needs to be set to a specific object determined at runtime.
It turns out that functions are themselves objects — and in turn, these objects have methods. (See
the Function object.) The call() and apply() methods can be used to achieve this goal.
Function hoisting
JSCopy to Clipboard
console.log(square(5)); // 25
function square(n) {
return n * n;
}
This code runs without any error, despite the square() function being called before it's declared.
This is because the JavaScript interpreter hoists the entire function declaration to the top of the
current scope, so the code above is equivalent to:
JSCopy to Clipboard
// All function declarations are effectively at the top of the scope
function square(n) {
return n * n;
}
console.log(square(5)); // 25
Function hoisting only works with function declarations — not with function expressions. The
following code will not work:
JSCopy to Clipboard
console.log(square(5)); // ReferenceError: Cannot access 'square' before initialization
const square = function (n) {
return n * n;
};
Day-12
Function scope
Variables defined inside a function cannot be accessed from anywhere outside the function,
because the variable is defined only in the scope of the function. However, a function can access
all variables and functions defined inside the scope in which it is defined.
In other words, a function defined in the global scope can access all variables defined in the
global scope. A function defined inside another function can also access all variables defined in
its parent function, and any other variables to which the parent function has access.
JSCopy to Clipboard
// The following variables are defined in the global scope
const num1 = 20;
const num2 = 3;
const name = "Chamakh";
console.log(multiply()); // 60
function add() {
return `${name} scored ${num1 + num2}`;
}
return add();
}
A function can refer to and call itself. There are three ways for a function to refer to itself:
1. bar()
2. arguments.callee()
3. foo()
A function that calls itself is called a recursive function. In some ways, recursion is analogous to
a loop. Both execute the same code multiple times, and both require a condition (to avoid an
infinite loop, or rather, infinite recursion in this case).
JSCopy to Clipboard
let x = 0;
// "x < 10" is the loop condition
while (x < 10) {
// do stuff
x++;
}
It can be converted into a recursive function declaration, followed by a call to that function:
JSCopy to Clipboard
function loop(x) {
// "x >= 10" is the exit condition (equivalent to "!(x < 10)")
if (x >= 10) {
return;
}
// do stuff
loop(x + 1); // the recursive call
}
loop(0);
However, some algorithms cannot be simple iterative loops. For example, getting all the nodes of
a tree structure (such as the DOM) is easier via recursion:
JSCopy to Clipboard
function walkTree(node) {
if (node === null) {
return;
}
// do something with node
for (let i = 0; i < node.childNodes.length; i++) {
walkTree(node.childNodes[i]);
}
}
Compared to the function loop, each recursive call itself makes many recursive calls here.
It is possible to convert any recursive algorithm to a non-recursive one, but the logic is often
much more complex, and doing so requires the use of a stack.
In fact, recursion itself uses a stack: the function stack. The stack-like behavior can be seen in the
following example:
JSCopy to Clipboard
function foo(i) {
if (i < 0) {
return;
}
console.log(`begin: ${i}`);
foo(i - 1);
console.log(`end: ${i}`);
}
foo(3);
// Logs:
// begin: 3
// begin: 2
// begin: 1
// begin: 0
// end: 0
// end: 1
// end: 2
// end: 3
Nested functions and closures
You may nest a function within another function. The nested (inner) function is private to its
containing (outer) function.
It also forms a closure. A closure is an expression (most commonly, a function) that can have
free variables together with an environment that binds those variables (that "closes" the
expression).
Since a nested function is a closure, this means that a nested function can "inherit" the arguments
and variables of its containing function. In other words, the inner function contains the scope of
the outer function.
To summarize:
The inner function can be accessed only from statements in the outer function.
The inner function forms a closure: the inner function can use the arguments and variables of
the outer function, while the outer function cannot use the arguments and variables of the inner
function.
console.log(addSquares(2, 3)); // 13
console.log(addSquares(3, 4)); // 25
console.log(addSquares(4, 5)); // 41
Since the inner function forms a closure, you can call the outer function and specify arguments
for both the outer and inner function:
JSCopy to Clipboard
function outside(x) {
function inside(y) {
return x + y;
}
return inside;
}
const fnInside = outside(3); // Think of it like: give me a function that adds 3 to whatever
you give it
console.log(fnInside(5)); // 8
console.log(outside(3)(5)); // 8
Preservation of variables
Notice how x is preserved when inside is returned. A closure must preserve the arguments and
variables in all scopes it references. Since each call provides potentially different arguments, a
new closure is created for each call to outside. The memory can be freed only when the
returned inside is no longer accessible.
This is not different from storing references in other objects, but is often less obvious because
one does not set the references directly and cannot inspect them.
Multiply-nested functions
A function (A) contains a function (B), which itself contains a function (C).
Both functions B and C form closures here. So, B can access A, and C can access B.
In addition, since C can access B which can access A, C can also access A.
Thus, the closures can contain multiple scopes; they recursively contain the scope of the
functions containing it. This is called scope chaining. (The reason it is called "chaining" is
explained later.)
Consider the following example:
JSCopy to Clipboard
function A(x) {
function B(y) {
function C(z) {
console.log(x + y + z);
}
C(3);
}
B(2);
}
A(1); // Logs 6 (which is 1 + 2 + 3)
1. B forms a closure including A (i.e., B can access A's arguments and variables).
2. C forms a closure including B.
3. Because C's closure includes B and B's closure includes A, then C's closure also includes A. This
means C can access both B and A's arguments and variables. In other words, C chains the
scopes of B and A, in that order.
The reverse, however, is not true. A cannot access C, because A cannot access any argument or
variable of B, which C is a variable of. Thus, C remains private to only B.
Name conflicts
When two arguments or variables in the scopes of a closure have the same name, there is a name
conflict. More nested scopes take precedence. So, the innermost scope takes the highest
precedence, while the outermost scope takes the lowest. This is the scope chain. The first on the
chain is the innermost scope, and the last is the outermost scope. Consider the following:
JSCopy to Clipboard
function outside() {
const x = 5;
function inside(x) {
return x * 2;
}
return inside;
}
The name conflict happens at the statement return x * 2 and is between inside's
parameter x and outside's variable x. The scope chain here is {inside, outside, global object}.
Therefore, inside's x takes precedences over outside's x, and 20 (inside's x) is returned instead
of 10 (outside's x).
Closures
Closures are one of the most powerful features of JavaScript. JavaScript allows for the nesting of
functions and grants the inner function full access to all the variables and functions defined
inside the outer function (and all other variables and functions that the outer function has access
to).
However, the outer function does not have access to the variables and functions defined inside
the inner function. This provides a sort of encapsulation for the variables of the inner function.
Also, since the inner function has access to the scope of the outer function, the variables and
functions defined in the outer function will live longer than the duration of the outer function
execution, if the inner function manages to survive beyond the life of the outer function. A
closure is created when the inner function is somehow made available to any scope outside the
outer function.
JSCopy to Clipboard
// The outer function defines a variable called "name"
const pet = function (name) {
const getName = function () {
// The inner function has access to the "name" variable of the outer function
return name;
};
return getName; // Return the inner function, thereby exposing it to outer scopes
};
const myPet = pet("Vivie");
console.log(myPet()); // "Vivie"
It can be much more complex than the code above. An object containing methods for
manipulating the inner variables of the outer function can be returned.
JSCopy to Clipboard
const createPet = function (name) {
let sex;
const pet = {
// setName(newName) is equivalent to setName: function (newName)
// in this context
setName(newName) {
name = newName;
},
getName() {
return name;
},
getSex() {
return sex;
},
setSex(newSex) {
if (
typeof newSex === "string" &&
(newSex.toLowerCase() === "male" || newSex.toLowerCase() === "female")
){
sex = newSex;
}
},
};
return pet;
};
pet.setName("Oliver");
pet.setSex("male");
console.log(pet.getSex()); // male
console.log(pet.getName()); // Oliver
In the code above, the name variable of the outer function is accessible to the inner functions,
and there is no other way to access the inner variables except through the inner functions. The
inner variables of the inner functions act as safe stores for the outer arguments and variables.
They hold "persistent" and "encapsulated" data for the inner functions to work with. The
functions do not even have to be assigned to a variable, or have a name.
JSCopy to Clipboard
const getCode = (function () {
const apiCode = "0]Eal(eh&2"; // A code we do not want outsiders to be able to modify…
return function () {
return apiCode;
};
})();
console.log(getCode()); // "0]Eal(eh&2"
Note: There are a number of pitfalls to watch out for when using closures!
If an enclosed function defines a variable with the same name as a variable in the outer scope,
then there is no way to refer to the variable in the outer scope again. (The inner scope variable
"overrides" the outer one, until the program exits the inner scope. It can be thought of as a name
conflict.)
JSCopy to Clipboard
const createPet = function (name) {
// The outer function defines a variable called "name".
return {
setName(name) {
// The enclosed function also defines a variable called "name".
name = name; // How do we access the "name" defined by the outer function?
},
};
};
Using the arguments object
The arguments of a function are maintained in an array-like object. Within a function, you can
address the arguments passed to it as follows:
JSCopy to Clipboard
arguments[i];
where i is the ordinal number of the argument, starting at 0. So, the first argument passed to a
function would be arguments[0]. The total number of arguments is indicated
by arguments.length.
Using the arguments object, you can call a function with more arguments than it is formally
declared to accept. This is often useful if you don't know in advance how many arguments will
be passed to the function. You can use arguments.length to determine the number of arguments
actually passed to the function, and then access each argument using the arguments object.
For example, consider a function that concatenates several strings. The only formal argument for
the function is a string that specifies the characters that separate the items to concatenate. The
function is defined as follows:
JSCopy to Clipboard
function myConcat(separator) {
let result = ""; // initialize list
// iterate through arguments
for (let i = 1; i < arguments.length; i++) {
result += arguments[i] + separator;
}
return result;
}
You can pass any number of arguments to this function, and it concatenates each argument into a
string "list":
JSCopy to Clipboard
console.log(myConcat(", ", "red", "orange", "blue"));
// "red, orange, blue, "
Function parameters
There are two special kinds of parameter syntax: default parameters and rest parameters.
Default parameters
In the past, the general strategy for setting defaults was to test parameter values in the body of
the function and assign a value if they are undefined.
In the following example, if no value is provided for b, its value would be undefined when
evaluating a*b, and a call to multiply would normally have returned NaN. However, this is
prevented by the second line in this example:
JSCopy to Clipboard
function multiply(a, b) {
b = typeof b !== "undefined" ? b : 1;
return a * b;
}
console.log(multiply(5)); // 5
With default parameters, a manual check in the function body is no longer necessary. You can
put 1 as the default value for b in the function head:
JSCopy to Clipboard
function multiply(a, b = 1) {
return a * b;
}
console.log(multiply(5)); // 5
Rest parameters
The rest parameter syntax allows us to represent an indefinite number of arguments as an array.
In the following example, the function multiply uses rest parameters to collect arguments from
the second one to the end. The function then multiplies these by the first argument.
JSCopy to Clipboard
function multiply(multiplier, ...theArgs) {
return theArgs.map((x) => multiplier * x);
}
An arrow function expression (also called a fat arrow to distinguish from a hypothetical -
> syntax in future JavaScript) has a shorter syntax compared to function expressions and does
not have its own this, arguments, super, or new.target. Arrow functions are always
anonymous.
Two factors influenced the introduction of arrow functions: shorter functions and non-
binding of this.
Shorter functions
JSCopy to Clipboard
const a = ["Hydrogen", "Helium", "Lithium", "Beryllium"];
console.log(a2); // [8, 6, 7, 9]
console.log(a3); // [8, 6, 7, 9]
No separate this
Until arrow functions, every new function defined its own this value (a new object in the case of
a constructor, undefined in strict mode function calls, the base object if the function is called as
an "object method", etc.). This proved to be less than ideal with an object-oriented style of
programming.
JSCopy to Clipboard
function Person() {
// The Person() constructor defines `this` as itself.
this.age = 0;
setInterval(function growUp() {
// In nonstrict mode, the growUp() function defines `this`
// as the global object, which is different from the `this`
// defined by the Person() constructor.
this.age++;
}, 1000);
}
const p = new Person();
In ECMAScript 3/5, this issue was fixed by assigning the value in this to a variable that could be
closed over.
JSCopy to Clipboard
function Person() {
// Some choose `that` instead of `self`.
// Choose one and be consistent.
const self = this;
self.age = 0;
setInterval(function growUp() {
// The callback refers to the `self` variable of which
// the value is the expected object.
self.age++;
}, 1000);
}
Alternatively, a bound function could be created so that the proper this value would be passed to
the growUp() function.
An arrow function does not have its own this; the this value of the enclosing execution context is
used. Thus, in the following code, the this within the function that is passed to setInterval has
the same value as this in the enclosing function:
JSCopy to Clipboard
function Person() {
this.age = 0;
setInterval(() => {
this.age++; // `this` properly refers to the person object
}, 1000);
}
To demonstrate how arrays can be useful, consider assigning the five oceans of the
world to their own variables.
oceans.js
This method is very verbose, and can quickly become difficult to maintain and keep
track of.
oceans.js
Output
Pacific
In this tutorial, we will learn how to create arrays; how they are indexed; how to add,
modify, remove, or access items in an array; and how to loop through arrays.
Day-14
Creating an Array
Now here is the same data created with the array constructor, which is initialized
with new Array().
sharks.js
Both methods will create an array. However, the array literal (square brackets) method
is much more common and preferred, as the new Array() constructor method may
have inconsistencies and unexpected results. It’s useful to be aware of the array
constructor in case you encounter it down the line.
We can print out an entire array, which will display the same as our input.
Output
[ 'Hammerhead', 'Great White', 'Tiger' ]
Arrays are often used to group together lists of similar data types, but they can
technically contain any value or a mix of values, including other arrays.
After creating an array, we can manipulate them in many ways, but first we must
understand how arrays are indexed.
Note: You may see the last item in an array with or without a final comma. This is known as
a trailing comma. It is common to see them omitted, but generally it is becomming preferred
to include them in your code, as this makes version control diffs more clear, and makes it
easier to add and remove items without errors. Note that trailing commas are not allowed
in JSON files.
Day-15
Indexing Arrays
If you’ve learned about indexing and manipulating strings in JavaScript, you may be
familiar with the concept of indexing arrays already, as a string is similar to an array.
Arrays do not have name/value pairs. Instead, they are indexed with integer values
beginning with 0. Here is an example array, assigned to seaCreatures.
seacreatures.js
let seaCreatures = [
"octopus",
"squid",
"shark",
"seahorse",
"starfish",
];
Copy
0 1 2 3 4
The first item in the array is octopus, which is indexed at 0. The last item is starfish,
which is indexed at 4. Counting starts with 0 in indices, which goes against our natural
intuition to start counting at 1, so special care must be taken to remember this until it
becomes natural.
We can find out how many items are in an array with the length property.
seaCreatures.length;
Copy
Output
5
Although the indices of seaCreatures consist of 0 to 4, the length property will output
the actual amount of items in the array, starting with 1.
If we want to find out the index number of a specific item in an array, such as seahorse,
we can use the indexOf() method.
seaCreatures.indexOf("seahorse");
Copy
Output
3
If an index number is not found, such as for a value that does not exist, the console will
return -1.
seaCreatures.indexOf("cuttlefish");
Copy
Output
-1
With index numbers that correspond to items within an array, we’re able to access each
item discretely in order to work with those items.
An item in a JavaScript array is accessed by referring to the index number of the item in
square brackets.
seaCreatures[1];
Copy
Output
squid
We know 0 will always output the first item in an array. We can also find the last item in
an array by performing an operation on the length property and applying that as the
new index number.
const lastIndex = seaCreatures.length - 1;
seaCreatures[lastIndex];
Copy
Output
starfish
Attempting to access an item that doesn’t exist will return undefined.
seaCreatures[10];
Copy
Output
undefined
In order to access items in a nested array, you would add another index number to
correspond to the inner array.
let nestedArray = [
[
"salmon",
"halibut",
],
[
"coral",
"reef",
]
];
nestedArray[1][0];
Copy
Output
coral
In the above example, we accessed the array at position 1 of the nestedArray variable,
then the item at position 0 in the inner array.
Adding an Item to an Array
In our seaCreatures variable we had five items, which consisted of the indices
from 0 to 4. If we want to add a new item to the array, we can assign a value to the next
index.
seaCreatures[5] = "whale";
seaCreatures;
Copy
Output
[ 'octopus',
'squid',
'shark',
'seahorse',
'starfish',
'whale' ]
If we add an item and accidentally skip an index, it will create an undefined item in the
array.
seaCreatures[7] = "pufferfish";
seaCreatures;
Copy
Output
[ 'octopus',
'squid',
'shark',
'seahorse',
'starfish',
'whale',
,
'pufferfish' ]
Attempting to access the extra array item will return undefined.
seaCreatures[6]
Copy
Output
undefined
Issues like that can be avoided by using the push() method, which adds an item to the
end of an array.
// Append lobster to the end of the seaCreatures array
seaCreatures.push("lobster");
seaCreatures;
Copy
Output
[ 'octopus',
'squid',
'shark',
'seahorse',
'starfish',
,
'whale',
'pufferfish',
'lobster' ]
On the other end of the spectrum, the unshift() method will add an item to the
beginning of an array.
// Append dragonfish to the beginning of the seaCreatures array
seaCreatures.unshift("dragonfish");
seaCreatures;
Copy
Output
[ 'dragonfish',
'octopus',
'squid',
'shark',
'seahorse',
'starfish',
'whale',
,
'pufferfish',
'lobster' ]
Between push() and unshift() you will be able to apend items to the beginning and
end of an array.
Removing an Item from an Array
When we want to remove a specific item from an array, we use the splice() method.
In the seaCreatures array, we accidentally created an undefined array item earlier, so
let’s remove that now.
seaCreatures.splice(7, 1);
seaCreatures;
Copy
Output
[ 'dragonfish',
'octopus',
'squid',
'shark',
'seahorse',
'starfish',
'whale',
'pufferfish',
'lobster' ]
In the splice() method, the first parameter stands for the index number to be removed
(in this case, 7), and the second parameter is how many items should be removed. We
put 1, signifying that only one item will be removed.
The splice() method will change the original variable. If you would like the original
variable to remain unchanged, use slice() and assign the result to a new variable.
Here we will assign two variables, one that uses slice() to store
the seaCreatures array from the first element until whale, and a second variable to
store the elements pufferfish and lobster. To join the two arrays, we’ll use
the concat() method to return the new array.
let firstArray = seaCreatures.slice(0, 7);
let secondArray = seaCreatures.slice(8, 10);
firstArray.concat(secondArray);
Copy
Output
[ 'dragonfish',
'octopus',
'squid',
'shark',
'seahorse',
'starfish',
'whale',
'pufferfish',
'lobster' ]
Notice that when calling the seaCreatures variable, the items in the array remain
unchanged.
seaCreatures;
Copy
Output
[ 'dragonfish',
'octopus',
'squid',
'shark',
'seahorse',
'starfish',
'whale',
,
'pufferfish',
'lobster' ]
The pop() method will remove the last item in an array.
// Remove the last item from the seaCreatures array
seaCreatures.pop();
seaCreatures;
Copy
Output
[ 'dragonfish',
'octopus',
'squid',
'shark',
'seahorse',
'starfish',
'whale',
'pufferfish' ]
lobster has been removed as the last item of the array. In order to remove the first
item of the array, we will use the shift() method.
// Remove the first item from the seaCreatures array
seaCreatures.shift();
seaCreatures;
Copy
Output
[ 'octopus',
'squid',
'shark',
'seahorse',
'starfish',
'whale',
'pufferfish' ]
By using pop() and shift(), we can remove items from the beginning and the end of
arrays. Using pop() is preferred wherever possible, as the rest of the items in the array
retain their original index numbers.
Modifying Items in Arrays
We can overwrite any value in an array by assigning a new value using the assignment
operator, just like we would with a regular variable.
seaCreatures;
Copy
Output
[ 'manatee',
'squid',
'shark',
'seahorse',
'starfish',
'whale',
'pufferfish' ]
Another way to modify a value is using the splice() method with a new parameter. If
we wanted to change the value of seahorse, which is the item at index 3, we could
remove it and add a new item in its place.
// Replace seahorse with sea lion using splice method
seaCreatures.splice(3, 1, "sea lion");
seaCreatures();
Copy
Output
[ 'manatee',
'squid',
'shark',
'sea lion',
'starfish',
'whale',
'pufferfish' ]
In the above example, we removed seahorse from the array, and pushed a new value
into index 3.
Looping Through an Array
We can loop through the entirety of the array with the for keyword, taking advantage of
the length property. In this example, we can create an array of shellfish and print out
each index number as well as each value to the console.
// Create an array of shellfish species
let shellfish = [
"oyster",
"shrimp",
"clam",
"mussel",
];
Output
0 'oyster'
1 'shrimp'
2 'clam'
3 'mussel'
We can also use the for...of loop, a newer feature of JavaScript.
// Create an array of aquatic mammals
let mammals = [
"dolphin",
"whale",
"manatee",
];
Output
dolphin
whale
manatee
The for...of loop does not retrieve the index number of the elements in the array, but
it is generally a simpler, more concise way to loop through an array.
Day-16
JavaScript Sorting Arrays
Sorting an Array
The sort() method sorts an array alphabetically:
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
Reversing an Array
The reverse() method reverses the elements in an array.
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
fruits.reverse();
Numeric Sort
By default, the sort() function sorts values as strings.
However, if numbers are sorted as strings, "25" is bigger than "100", because
"2" is bigger than "1".
Because of this, the sort() method will produce incorrect result when sorting
numbers.
Example
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b - a});
function(a, b){return a - b}
When the sort() function compares two values, it sends the values to the
compare function, and sorts the values according to the returned (negative,
zero, positive) value.
If the result is 0, no changes are done with the sort order of the two values.
Example:
The compare function compares all the values in the array, two values at a
time (a, b).
When comparing 40 and 100, the sort() method calls the compare function(40,
100).
The function calculates 40 - 100 (a - b), and since the result is negative (-60),
the sort function will sort 40 as a value lower than 100.
You can use this code snippet to experiment with numerically and alphabetically
sorting:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The sort() Method</h2>
<p id="demo"></p>
<script>
const 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>
</body>
</html>
The most popular correct method, is called the Fisher Yates shuffle, and was
introduced in data science as early as 1938!
Example
const points = [40, 100, 1, 5, 25, 10];
However, after you have sorted an array, you can use the index to obtain the
highest and lowest values.
Sorting ascending:
Example
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b});
// now points[0] contains the lowest value
// and points[points.length-1] contains the highest value
Sorting descending:
Example
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b - a});
// now points[0] contains the highest value
// and points[points.length-1] contains the lowest value
Sorting a whole array is a very inefficient method if you only want to find the
highest (or lowest) value.
Example
function myArrayMin(arr) {
return Math.min.apply(null, arr);
}
This function loops through an array comparing each value with the highest
value found:
This function loops through an array comparing each value with the lowest value
found:
Example
const cars = [
{type:"Volvo", year:2016},
{type:"Saab", year:2001},
{type:"BMW", year:2010}
];
Even if objects have properties of different data types, the sort() method can
be used to sort the array.
Example
cars.sort(function(a, b){return a.year - b.year});
When sorting elements on a value, the elements must keep their relative
position to other elements with the same value.
const myArr = [
{name:"X00",price:100 },
{name:"X01",price:100 },
{name:"X02",price:100 },
{name:"X03",price:100 },
{name:"X04",price:110 },
{name:"X05",price:110 },
{name:"X06",price:110 },
{name:"X07",price:110 }
];
In the example above, when sorting on price, the result is not allowed to come
out with the names in an other relative position like this:
X01 100
X03 100
X00 100
X03 100
X05 110
X04 110
X06 110
X07 110
Day-17
What Is an Object?
Objects are key to understanding object-oriented technology. Look around right now
and you'll find many examples of real-world objects: your dog, your desk, your television
set, your bicycle.
Real-world objects share two characteristics: They all have state and behavior. Dogs
have state (name, color, breed, hungry) and behavior (barking, fetching, wagging tail).
Bicycles also have state (current gear, current pedal cadence, current speed) and
behavior (changing gear, changing pedal cadence, applying brakes). Identifying the
state and behavior for real-world objects is a great way to begin thinking in terms of
object-oriented programming.
Take a minute right now to observe the real-world objects that are in your immediate
area. For each object that you see, ask yourself two questions: "What possible states
can this object be in?" and "What possible behavior can this object perform?". Make
sure to write down your observations. As you do, you'll notice that real-world objects
vary in complexity; your desktop lamp may have only two possible states (on and off)
and two possible behaviors (turn on, turn off), but your desktop radio might have
additional states (on, off, current volume, current station) and behavior (turn on, turn off,
increase volume, decrease volume, seek, scan, and tune). You may also notice that
some objects, in turn, will also contain other objects. These real-world observations all
translate into the world of object-oriented programming.
Software objects are conceptually similar to real-world objects: they too consist of state
and related behavior. An object stores its state in fields (variables in some programming
languages) and exposes its behavior through methods (functions in some programming
languages). Methods operate on an object's internal state and serve as the primary
mechanism for object-to-object communication. Hiding internal state and requiring all
interaction to be performed through an object's methods is known as data
encapsulation — a fundamental principle of object-oriented programming.
By attributing state (current speed, current pedal cadence, and current gear) and
providing methods for changing that state, the object remains in control of how the
outside world is allowed to use it. For example, if the bicycle only has 6 gears, a method
to change gears could reject any value that is less than 1 or greater than 6.
Bundling code into individual software objects provides a number of benefits, including:
1. Modularity: The source code for an object can be written and maintained
independently of the source code for other objects. Once created, an object can
be easily passed around inside the system.
2. Information-hiding: By interacting only with an object's methods, the details of its
internal implementation remain hidden from the outside world.
3. Code re-use: If an object already exists (perhaps written by another software
developer), you can use that object in your program. This allows specialists to
implement/test/debug complex, task-specific objects, which you can then trust to
run in your own code.
4. Pluggability and debugging ease: If a particular object turns out to be
problematic, you can simply remove it from your application and plug in a
different object as its replacement. This is analogous to fixing mechanical
problems in the real world. If a bolt breaks, you replace it, not the entire machine.
Day-18
Class & Object
n the real world, you'll often find many individual objects all of the same kind. There may
be thousands of other bicycles in existence, all of the same make and model. Each
bicycle was built from the same set of blueprints and therefore contains the same
components. In object-oriented terms, we say that your bicycle is an instance of
the class of objects known as bicycles. A class is the blueprint from which individual
objects are created.
class Bicycle {
int cadence = 0;
int speed = 0;
int gear = 1;
void printStates() {
System.out.println("cadence:" +
cadence + " speed:" +
speed + " gear:" + gear);
}
}
The syntax of the Java programming language will look new to you, but the design of
this class is based on the previous discussion of bicycle objects. The
fields cadence, speed, and gear represent the object's state, and the methods
(changeCadence, changeGear, speedUp etc.) define its interaction with the outside
world.
You may have noticed that the Bicycle class does not contain a main method. That's
because it's not a complete application; it's just the blueprint for bicycles that might
be used in an application. The responsibility of creating and using
new Bicycle objects belongs to some other class in your application.
Here's a BicycleDemo class that creates two separate Bicycle objects and invokes
their methods:
class BicycleDemo {
public static void main(String[] args) {
// Invoke methods on
// those objects
bike1.changeCadence(50);
bike1.speedUp(10);
bike1.changeGear(2);
bike1.printStates();
bike2.changeCadence(50);
bike2.speedUp(10);
bike2.changeGear(2);
bike2.changeCadence(40);
bike2.speedUp(10);
bike2.changeGear(3);
bike2.printStates();
}
}
The output of this test prints the ending pedal cadence, speed, and gear for the two
bicycles:
1. By string literal
2. By string object (using new keyword)
1) By string literal
The string literal is created using double quotes. The syntax of creating
string using string literal is given below:
<script>
var str="This is string literal";
document.write(str);
</script>
Day-20
JavaScript String Methods
String length String trim()
String slice() String trimStart()
String substring() String trimEnd()
String substr() String padStart()
String replace() String padEnd()
String replaceAll() String charAt()
String toUpperCase() String charCodeAt()
String toLowerCase() String split()
String concat()
Note
String search methods are covered in the next chapter.
Example
let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let length = text.length;
slice(start, end)
substring(start, end)
substr(start, length)
JavaScript String slice()
slice() extracts a part of a string and returns the extracted part in a new string.
The method takes 2 parameters: start position, and end position (end not
included).
Example
Slice out a portion of a string from position 7 to position 13:
Note
JavaScript counts positions from zero.
First position is 0.
Second position is 1.
Examples
If you omit the second parameter, the method will slice out the rest of the
string:
The difference is that start and end values less than 0 are treated as 0
in substring().
Example
let str = "Apple, Banana, Kiwi";
let part = str.substring(7, 13);
If you omit the second parameter, substring() will slice out the rest of the string.
JavaScript String substr()
substr() is similar to slice().
The difference is that the second parameter specifies the length of the
extracted part.
Example
let str = "Apple, Banana, Kiwi";
let part = str.substr(7, 6);
If you omit the second parameter, substr() will slice out the rest of the string.
Example
let str = "Apple, Banana, Kiwi";
let part = str.substr(7);
If the first parameter is negative, the position counts from the end of the string.
Example
let str = "Apple, Banana, Kiwi";
let part = str.substr(-4);
Example
let text = "Please visit Microsoft!";
let newText = text.replace("Microsoft", "W3Schools");
If the parameter is a regular expression, the global flag (g) must be set,
otherwise a TypeError is thrown.
Example
text = text.replaceAll(/Cats/g,"Dogs");
text = text.replaceAll(/cats/g,"dogs");
Note
replaceAll() is an ES2021 feature.
Example
let text1 = "Hello";
let text2 = "World";
let text3 = text1.concat(" ", text2);
The concat() method can be used instead of the plus operator. These two lines
do the same:
Example
text = "Hello" + " " + "World!";
text = "Hello".concat(" ", "World!");
Note
All string methods return a new string. They don't modify the original string.
Formally said:
The trimStart() method works like trim(), but removes whitespace only from
the start of a string.
Example
let text1 = " Hello World! ";
let text2 = text1.trimStart();
Day-21
JavaScript Get Date Methods
The new Date() Constructor
In JavaScript, date objects are created with new Date().
new Date() returns a date object with the current date and time.
Note 1
The get methods above return Local time.
Note 2
The get methods return information from existing date objects.
Examples
const d = new Date("2021-03-25");
d.getFullYear();
const d = new Date();
d.getFullYear();
Day-22
JavaScript Events
HTML events are "things" that happen to HTML elements.
HTML Events
An HTML event can be something the browser does, or something a user does.
In the example above, the JavaScript code changes the content of the element
with id="demo".
In the next example, the code changes the content of its own element
(using this.innerHTML):
Example
<button onclick="this.innerHTML = Date()">The time is?</button>
JavaScript code is often several lines long. It is more common to see event
attributes calling functions:
Example
<button onclick="displayDate()">The time is?</button>
Event Description
onmouseout The user moves the mouse away from an HTML element
Many different methods can be used to let JavaScript work with events:
You will learn a lot more about events and event handlers in the HTML DOM
chapters.
Day-23
AngularJS Introduction
AngularJS is a JavaScript framework. It can be added to an HTML page
with a <script> tag.
AngularJS extends HTML attributes with Directives, and binds data to HTML
with Expressions.
AngularJS is a JavaScript
Framework
AngularJS is a JavaScript framework written in JavaScript.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/
1.6.9/angular.min.js"></script>
The ng-model directive binds the value of HTML controls (input, select,
textarea) to application data.
<div ng-app="">
<p>Name: <input type="text" ng-model="name"></p>
<p ng-bind="name"></p>
</div>
</body>
</html>
Example explained:
The ng-app directive tells AngularJS that the <div> element is the "owner" of
an AngularJS application.
The ng-model directive binds the value of the input field to the application
variable name.
The ng-bind directive binds the content of the <p> element to the application
variable name.
Day-24
AngularJS Directives
As you have already seen, AngularJS directives are HTML attributes with
an ng prefix.
AngularJS Example
<div ng-app="" ng-init="firstName='John'">
</div>
AngularJS Example
<div data-ng-app="" data-ng-init="firstName='John'">
</div>
AngularJS Expressions
AngularJS expressions are written inside double braces: {{ expression }}.
AngularJS Example
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/
angular.min.js"></script>
<body>
<div ng-app="">
<p>My first expression: {{ 5 + 5 }}</p>
</div>
</body>
</html>
AngularJS expressions bind AngularJS data to HTML the same way as the ng-
bind directive.
AngularJS Example
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/
angular.min.js"></script>
<body>
<div ng-app="">
<p>Name: <input type="text" ng-model="name"></p>
<p>{{name}}</p>
</div>
</body>
</html>
Day-25
AngularJS ng-model Directive
The ng-model directive binds the value of HTML controls (input, select,
textarea) to application data.
Example
<div ng-app="myApp" ng-controller="myCtrl">
Name: <input ng-model="name">
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.name = "John Doe";
});
</script>
Two-Way Binding
The binding goes both ways. If the user changes the value inside the input field,
the AngularJS property will also change its value:
Example
<div ng-app="myApp" ng-controller="myCtrl">
Name: <input ng-model="name">
<h1>You entered: {{name}}</h1>
</div>
Example
<form ng-app="" name="myForm">
Email:
<input type="email" name="myAddress" ng-model="text">
<span ng-show="myForm.myAddress.$error.email">Not a valid e-mail
address</span>
</form>
In the example above, the span will be displayed only if the expression in
the ng-show attribute returns true.
If the property in the ng-model attribute does not exist, AngularJS will create one
for you.
Application Status
The ng-model directive can provide status for application data (valid, dirty,
touched, error):
Example
<form ng-app="" name="myForm" ng-init="myText = '[email protected]'">
Email:
<input type="email" name="myAddress" ng-model="myText" required>
<h1>Status</h1>
{{myForm.myAddress.$valid}}
{{myForm.myAddress.$dirty}}
{{myForm.myAddress.$touched}}
</form>
CSS Classes
The ng-model directive provides CSS classes for HTML elements, depending on
their status:
Example
<style>
input.ng-invalid {
background-color: lightblue;
}
</style>
<body>
ng-empty
ng-not-empty
ng-touched
ng-untouched
ng-valid
ng-invalid
ng-dirty
ng-pending
ng-pristine
Data binding in AngularJS is the synchronization between the model and the
view.
Data Model
AngularJS applications usually have a data model. The data model is a collection
of data available for the application.
Example
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstname = "John";
$scope.lastname = "Doe";
});
HTML View
The HTML container where the AngularJS application is displayed, is called the
view.
The view has access to the model, and there are several ways of displaying
model data in the view.
You can use the ng-bind directive, which will bind the innerHTML of the element
to the specified model property:
Example
<p ng-bind="firstname"></p>
You can also use double braces {{ }} to display content from the model:
Example
<p>First name: {{firstname}}</p>
Or you can use the ng-model directive on HTML controls to bind the model to the
view.
Example
<input ng-model="firstname">
The ng-model directive provides a two-way binding between the model and the
view.
Two-way Binding
Data binding in AngularJS is the synchronization between the model and the
view.
When data in the model changes, the view reflects the change, and when data
in the view changes, the model is updated as well. This happens immediately
and automatically, which makes sure that the model and the view is updated at
all times.
Example
<div ng-app="myApp" ng-controller="myCtrl">
Name: <input ng-model="firstname">
<h1>{{firstname}}</h1>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstname = "John";
$scope.lastname = "Doe";
});
</script>
AngularJS Controller
Applications in AngularJS are controlled by controllers. Read about controllers in
the AngularJS Controllers chapter.
Because of the immediate synchronization of the model and the view, the
controller can be completely separated from the view, and simply concentrate
on the model data. Thanks to the data binding in AngularJS, the view will reflect
any changes made in the controller.
Example
<div ng-app="myApp" ng-controller="myCtrl">
<h1 ng-click="changeName()">{{firstname}}</h1>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstname = "John";
$scope.changeName = function() {
$scope.firstname = "Nelly";
}
});
</script>
Day-26
AngularJS Filters
Filters can be added in AngularJS to format data.
AngularJS Filters
AngularJS provides filters to transform data:
Example
<div ng-app="myApp" ng-controller="personCtrl">
</div>
The lowercase filter format strings to lower case:
Example
<div ng-app="myApp" ng-controller="personCtrl">
</div>
Example
The orderBy filter sorts an array:
<ul>
<li ng-repeat="x in names | orderBy:'country'">
{{ x.name + ', ' + x.country }}
</li>
</ul>
</div>
Example
<div ng-app="myApp" ng-controller="costCtrl">
</div>
The filter Filter
The filter filter selects a subset of an array.
The filter filter can only be used on arrays, and it returns an array containing
only the matching items.
Example
Return the names that contains the letter "i":
<ul>
<li ng-repeat="x in names | filter : 'i'">
{{ x }}
</li>
</ul>
</div>
Type a letter in the input field, and the list will shrink/grow depending on the
match:
Jani
Carl
Margareth
Hege
Joe
Gustav
Birgit
Mary
Kai
Example
<div ng-app="myApp" ng-controller="namesCtrl">
<ul>
<li ng-repeat="x in names | filter : test">
{{ x }}
</li>
</ul>
</div>
Name Country
Jani Norway
Carl Sweden
Margareth England
Hege Norway
Joe Denmark
Gustav Sweden
Birgit Denmark
Mary England
Kai Norway
By adding the ng-click directive on the table headers, we can run a function
that changes the sorting order of the array:
Example
<div ng-app="myApp" ng-controller="namesCtrl">
</div>
<script>
angular.module('myApp',
[]).controller('namesCtrl', function($scope) {
$scope.names = [
{name:'Jani',country:'Norway'},
{name:'Carl',country:'Sweden'},
{name:'Margareth',country:'England'},
{name:'Hege',country:'Norway'},
{name:'Joe',country:'Denmark'},
{name:'Gustav',country:'Sweden'},
{name:'Birgit',country:'Denmark'},
{name:'Mary',country:'England'},
{name:'Kai',country:'Norway'}
];
$scope.orderByMe = function(x) {
$scope.myOrderBy = x;
}
});
</script>
Custom Filters
You can make your own filters by registering a new filter factory function with
your module:
Example
Make a custom filter called "myFormat":
<script>
var app = angular.module('myApp', []);
app.filter('myFormat', function() {
return function(x) {
var i, c, txt = "";
for (i = 0; i < x.length; i++) {
c = x[i];
if (i % 2 == 0) {
c = c.toUpperCase();
}
txt += c;
}
return txt;
};
});
app.controller('namesCtrl', function($scope) {
$scope.names =
['Jani', 'Carl', 'Margareth', 'Hege', 'Joe', 'Gustav', 'Birgit', 'M
ary', 'Kai'];
});
</script>