Modern Javascript 2020 Notes
Modern Javascript 2020 Notes
Modern Javascript
2020 Notes
Table of Contents
Module 1: Getting started with Javascript ............................................................ 2
Module 2: Variables, data types, type conversion and more ............................... 3
Module 3: Operators ........................................................................................... 14
Module 4: Strings ................................................................................................ 24
Module 5: Numbers ............................................................................................ 33
Module 6: Conditional statements ..................................................................... 45
Module 7: Arrays ................................................................................................. 55
Module 8: Date, Date methods & Math object................................................... 59
Module 9: Functions............................................................................................ 61
Module 10: Javascript objects (basics) ................................................................ 77
Module 11: Javascript Document Object Model (DOM) ..................................... 79
Module 12: Javascript Regular Expressions Basics.............................................. 87
Copyright @ DigiFisk.com
Page 2 of 88
Console code:
Log outputs into your console.
console.log("hello");
Comments:
Comments on the code – won’t be read by the browser
// - single line comment
/* */ - multi-line comment
Copyright @ DigiFisk.com
Page 3 of 88
Use strict
This was an ES5 specification that came out in 2009. Enables the latest
modifications, basically, activates modern Javascript.
Use at the top of the code.
'use strict';
Or
"use strict";
Variables
Variables are containers of information. They store certain values, be it numbers,
characters, strings, etc.
To create or declare a variable in Javascript, you should use the keyword let, like
this.
let variableName;
There are some rules to what the variable name could be.
1. The first character of the variable name should be an alphabet or an
underscore or dollar sign ($)
2. The rest of the characters can be alphabets, underscore or numbers or
dollar signs ($)
3. Variables are case sensitive. So, apple is not equal to Apple.
4. Reserved words, or keywords, cannot be used. For example, var is a
reserved word, so it can’t be a variable name.
So, taking all these rules into account,
Copyright @ DigiFisk.com
Page 4 of 88
let _apple;
let app_le12;
let $apple;
let apple;
Are all correct
But,
let 12apple;
Is not correct, because numbers should not be the first character of a variable.
Reserved words
Words that have special meaning in Javascript – can’t use in variable declaration.
There is a list:
Let, var, const, break, case, catch, class, continue, debugger, default, delete, do,
else, export, extends, finally, for, function, if, import, in, instanceof, new, return,
super, switch, this, throw, try, typeof, void, while, with, yield
Var
Before ES2015, that is, in ES5 and before that, variables were declared using the
keyword var.
It’s still in use, and it works, but it is not considered good practice to use var to
declare variables anymore because it has a function scope and not a block scope
like “let” does.
var a = 5;
Constants
Copyright @ DigiFisk.com
Page 5 of 88
Copyright @ DigiFisk.com
Page 6 of 88
This type of naming variables is called Camel casing, where the first word is all
small letters and after that, every word has the first letter capitalized. This is the
naming convention for pretty much every big programming language, so it’s
better to follow it for variables with multiple words.
Dynamic variables
Can reassign different types to the same variable.
For example,
let a = 12;
Now, a is a number.
a = "apple";
I’ve made a a string now.
a = false;
Now, it’s a Boolean value. This is how you can change the type of your variable
any way you want.
Copyright @ DigiFisk.com
Page 7 of 88
More on strings
Double quotes, single quotes, backtick.
let a = "apple";
let a = 'apple';
console.log("This is an " + a);
With backtick, you don’t need the + operator. You can do everything within
backticks. I’ll show you.
console.log(`This is an ${a}`);
Can design sentences too.
For example, if we need a newline with double or single quotes, this is how you’ll
do it.
console.log("Hello!\nGood morning");
With backtick, its very simple:
console.log(`Hello!
Good morning!`);
Can do operations with backticks too:
console.log(`1+2=${1+2}`);
Can do like this by adding variables too:
let a = 1, b=2;
console.log(`1+2=${a+b}`);
Copyright @ DigiFisk.com
Page 8 of 88
Boolean
let bool = "true";
console.log(bool);
let bool = "false";
let bool = 1>2; //false
Typeof operator
The typeof operator is used to find the type of the variable or value.
This is how it’s written:
let a = 5;
typeof a; //number
Copyright @ DigiFisk.com
Page 9 of 88
Undefined
When a variable is just declared and it hasn’t been assigned a value, it has no
value. When you check its type, it’ll say undefined, because the browser does not
know what the type of the yet to be declared value is.
let a;
typeof a; //undefined
a = 5;
typeof a; //number
You can also set the value of a variable to undefined to empty it of its value. You
might want to fill it with something else later on.
So,
a = undefined;
typeof a; //undefined
But, an empty string is still recognized as a string. It won’t be called empty or
undefined.
typeof "";
There is also the null data type. It basically means nothing. That is, it doesn’t exist.
Copyright @ DigiFisk.com
Page 10 of 88
But the data type of null is actually object, and not null.
But, it can be used to make an object null.
let a = {name:"Mary", age:18, hair:"blonde"};
a = null;
typeof a; //object
But, you can set the value to undefined, so the type is also undefined.
a = undefined;
alert(typeof a; ) //undefined
So, the difference between undefined and null is the type, even though both
make the variable devoid of its values:
typeof undefined; //undefined
typeof null; //object
null == undefined; //true because they do have the same value, that is, nothing
null === undefined; //false because one is of type object and the other is of type
undefined
Type conversion:
Can convert values from one type to another by using pre-defined type
conversion functions of javascript.
String conversion:
let a = 1;
console.log(typeof a);
Now, let’s perform conversion from number to string.
a = String(a);
Copyright @ DigiFisk.com
Page 11 of 88
console.log(typeof a);
This works for Boolean too.
Number conversion:
Now, let’s convert to number.
let a = "1";
console.log(typeof a);
a = Number(a);
console.log(typeof a);
Spaces will be removed and the rest will be converted to a number.
let a = " 1 ";
a = Number(a);
console.log(a);
let a = " 12 "; //works
let a = " 1 2 "; //will give NaN because there’s space in between.
Long strings that aren’t just one number won’t work either.
let a = "Hello"; //This is NaN too
Copyright @ DigiFisk.com
Page 12 of 88
Boolean conversion:
let a = 1;
console.log(Boolean(a));
let a = 0; //false
let a = "Hello!"; //true
let a = ""; //false
let a = "0"; //This is true too. Basically any string with anything inside it is true.
let a = -1; //except 0, any other number is true, even negative numbers
Getting outputs
Alert boxes
Alert boxes are the easiest ways of getting outputs.
alert("Hello there!");
Can output values in variables too.
let a = "Hello there!";
alert(a);
Copyright @ DigiFisk.com
Page 13 of 88
Prompt boxes
Can prompt for values with the pre-defined function prompt in Javascript.
let age = prompt("What is your age?", 15);
The second parameter is optional and displays the default value if the user does
not input anything.
alert("Your age is " + age);
Can write like this too:
alert(`Your age is ${age}`);
Confirm boxes
Confirm can be used to get yes or no answers, and if assigned to something, it will
apply true or false Boolean values to it.
let age = confirm("Are you less than 5 years old?");
if(age == true) {
alert("You're a baby");
}
else {
alert("You've grown up!")
}
Can do calculations and other things based on that.
Copyright @ DigiFisk.com
Page 14 of 88
Module 3: Operators
Assignment operator:
Assign values to variables with the assignment operator (Equal to ‘=’).
let a;
a = 2;
let a = 2;
Different from equal to operator (==, ===)
let a = 10, b = 5;
a = a + b;
Undefined:
let car;
Right now, the value of car is undefined because it has no value assigned to it
(yet).
let a = 2;
a = 3;
Copyright @ DigiFisk.com
Page 15 of 88
Now a has a value of 3. Because previous value of a was replaced by the latest
value. Only latest value counts.
Modulus might be unfamiliar for you. It’s very simple. % gives the reminder of the
division of the 2 operands.
For example, 3%2 = 1, because the quotient is one and the remainder is 1, so it’ll
output the remainder.
Complicated operations
Copyright @ DigiFisk.com
Page 16 of 88
let a = 5;
let b = ++a;
Both b and a will be 6.
Pre increment – increments a first, and then assigns the new value to b.
Similarly:
Copyright @ DigiFisk.com
Page 17 of 88
String concatenation:
+ operator, wen used with strings, concatenates them, not calculates.
let a = "hello " + "world";
alert(a);
+= can also be used for string concatenation:
let a = "hello ";
a += "world";
Basically means, a = a + "world";
let a = 1 + “hello” + 2;
Output: 1hello2
let a = "hello";
let b = "world";
let c = a + " " + b; //without having the mention the space in one of the words
Output: hello world
Copyright @ DigiFisk.com
Page 18 of 88
let a = 1 + 2 + “hello”;
Output: 3hello
let a = “hello” + 1 + 2;
Output: hello12
Comparison operators
Comparison operators are used in logical statements to compare two variables or
values. This could be comparison to find the equality between the two variables,
or differences.
== -> equal to in value alone
5 == 5 – true
6 == 5 – false
5 == “5” – true, even though they are different types, the value is still 5. It’ll
recognize them as equals.
“hello” == “hello” -> true -> Not just numbers, for strings too. Any type.
Copyright @ DigiFisk.com
Page 19 of 88
5 !== “5” -> True, because both aren’t of the same type
Copyright @ DigiFisk.com
Page 20 of 88
String comparisons
"A" > "Z" -> False
"Boo" > "Bo" -> True
Rules:
Compares first character, and if it finds a comparison, done. If equal, then next
character, then next, and so on. If both strings end with same length and same
characters, then equal.
If both strings end with same length, but the last character is different, then looks
at the ASCII of both and decides which is bigger.
If one string has a bigger length than the other, then the bigger one is greater by
default if everything else is equal. Compares with ASCII values (Unicode),
"a" > "A" -> True, because ASCII of a is 97 and ASCII of A is 65.
"ABCD" > "abc" -> False
ASCII is an international number standard for characters. Every letter and special
character has an ASCII number.
Copyright @ DigiFisk.com
Page 21 of 88
“5” < “hello” -> Converts both to number, but “hello” is converted to NaN and
comparison against NaN is always false.
“5” < “15” -> False – when converting strings to number, 5 is greater tan 15
because 1 is lesser than 5 and that’ll be the first comparison made.
That is, 1 vs 5 will be the first comparison made and the output will be based on
that, not like with full numbers.
Logical operators
Used to determine the logic between two variables or values.
There are three logical operators.
&& - And
Statement 1 && statement 2
If both statements return a value of true, then the entire statement with the &&
operator is true. Otherwise, the statement is false.
This is how it works:
True, True = True
True, False = False
False, True = False
False, False = False
For example:
(5 <= 5) && (6 > 5) - > True && True -> True
(5 < 5) && (6 > 5) -> False && True -> False
|| - Or
Copyright @ DigiFisk.com
Page 22 of 88
Statement 1 || statement 2
If any one of the statements on either side of the or operator is true, then the
entire statement is true. The statement returns false only when both statements
are false.
True, True = True
True, False = True
False, True = True
False, False = False
! – Not
If the statement is false, then Not of that statement will return false. If the
statement is true, Not of that statement will return true.
!(statement)
!(5 == 5) -> false
!(5 < 4) -> True
Copyright @ DigiFisk.com
Page 23 of 88
Since, age is equal to 5, which makes the condition given true, the value of output
will be “Toddler”, and it’ll be printed out in the alert statement.
Change value to 6, and “kid” will be printed out.
Operator precedence
So, the precedence is as follows
()
Postfix increment and decrement
Prefix increment and decrement
Multiplication, division, modulus
Addition, subtraction
Then come the bitwise operators, comparison operators and logical operators.
Copyright @ DigiFisk.com
Page 24 of 88
Module 4: Strings
Creating strings
Now, let’s look more into strings. As you already know, strings are a string of
characters, hence the name.
let a = "hello";
That’s a string.
We can either write strings within double quotes or single quotes.
a = 'hello';
The above works the same as the first statement.
You can even write entire sentences within strings.
a = "Hello, I am here to teach you Javascript";
You can also write quotes within strings. But, the quotes in the string should not
match the quote outside it.
For example:
a = "He said, 'I am going home'.";
or
a = 'He said, "I am going home".';
Both are allowed, but using double quotes inside when there are double quotes
outside, or single quotes inside when there are single quotes outside will produce
errors.
a = "He said, "I am going home".";
Now, a will only have “he said,” because the browser will think the string ends
where the 2nd double quote appears. That’s why there should be a difference in
quotes between the strings and the quotes surrounding it, so the browser knows
which is which.
Copyright @ DigiFisk.com
Page 25 of 88
Copyright @ DigiFisk.com
Page 26 of 88
But, comparing 2 objects is always false, because they are different objects.
So, if
let b = new String(“hello”);
Even though both a and b are objects with same values,
a == b -> False
a === b -> False
Both false.
String methods
String length
a = "hello";
Syntax to find length of the string:
stringName.length
Example:
alert(a.length);
Can find length of string, no matter how big it is.
Copyright @ DigiFisk.com
Page 27 of 88
let y = x.indexOf(“javascript”);
It returns -1, because J is not equal to j. So, Javascript is not equal to javascript.
When a given sub string is not found in the string we are searching in, browser
will return -1.
indexOf returns the first position of the first occurrence of the string. If the same
sub string is present in the string more than once, it’ll still only consider the first
string.
let x = "That that that that that";
let y = x.indexOf("that");
Answer is 5, though there are more than 1 this in x.
But, on the other hand, the lastIndexOf() method will return the last occurrence
of the given string.
So, in the same example.
y = x.lastIndexOf("that");
Answer is 20. Because that’s the position of the last occurrence of “that” (count
and show).
Again for lastIndexOf method, if the search string is not present in the string, it’ll
return a -1.
y = x.lastIndexOf(“hello”); //returns -1
For both indexOf and lastIndexOf methods, you can mention a second parameter
that specifies from where you want the search to start.
So, for the last example, for indexOf, let’s start the search from the 12th index
position instead of the default 0.
let y = x.indexOf("that", 12);
Copyright @ DigiFisk.com
Page 28 of 88
The answer is 15 because the search starts from 12, so the first occurrence of the
given substring is the third “that”.
Search method
You also have another method called search, which allows you to search for a
string within your given string, and return the position of occurrence.
let y = x.search("that");
No second parameter.
Slicing strings
You can extract a part of the string and place it another variable by using the slice
method.
It literally slices the string and takes it out.
But, it won’t affect the original string. The original string says the same, it’s just
that the slice will be duplicated and placed in the new variable.
The slice() method takes 2 parameters, the start position of slicing and the end
position.
let x = "This is an example string";
let y = x.slice(8,15);
console.log(y);
Answer is “an exam”
But x is still the same.
If we give negative values for the parameters, it’ll calculate the position from the
end of the string.
let y = x.slice(-7,-2);
Copyright @ DigiFisk.com
Page 29 of 88
If you don’t give the second parameter, it’ll slice out from the first index position
to the end of the string.
let y = x.slice(8);
Can do the same with negative value.
let y = x.slice(-7);
We have a similar method called substring(). But this method does not accept
negative parameters.
let y = x.substring(8,15);
let y = x.substring(8); //rest of the string
Replace content
Replace the content of string using replace() method. Again, does not change the
actual content of original string. Just creates a new string with replaced value.
let x = "This is an example string";
let y = x.replace("an example", "a sample");
If you want to make it case insensitive, you can use a simple regular expression.
Copyright @ DigiFisk.com
Page 30 of 88
Also, by default, it’ll only replace the first occurrence of the word.
let x = "this this this this";
let y = x.replace("this", "That");
But, by using the regular expression g, we can make it replace every occurrence of
the word in the string.
let y = x.replace(/this/g, "That");
Concat strings
To concat two strings, we usually use the “+” operator.
let x = "Hello";
let z = "World";
Copyright @ DigiFisk.com
Page 31 of 88
Trim string
Use trim() method to remove white space from both sides of the string.
let x = " This That This ";
alert(x);
let y = x.trim();
alert(y);
Character codes
Can find characters by mentioning their position.
let x = "This is an example string";
let y = x.charAt(5);
console.log(y);
let y = x.charAt(12);
Can also get the character code of the character at a particular position.
As you know, in computers, every character has an ASCII code.
Small a is 97. Big A is 65, etc (explain more by showing all examples).
You can find the character code of a character at a particular position:
let y = x.charCodeAt(5);
Copyright @ DigiFisk.com
Page 32 of 88
Copyright @ DigiFisk.com
Page 33 of 88
Module 5: Numbers
Creating numbers in Javascript
You can store both whole numbers and decimal numbers.
Whole numbers are called integers and decimal numbers are called floating point
numbers.
let a = 5; //integer – whole number
let b = 5.5 //floating point – decimal
Can also store very large or very small numbers by using exponentiation.
So, to store 5000000, you can store it as
let a = 5e6; //means 5 into 1000000
This is how you store big numbers
To store 5/1000000 or 0.0000005, you make it
let a = 5e-6; //how you store very small numbers
Copyright @ DigiFisk.com
Page 34 of 88
NaN
Copyright @ DigiFisk.com
Page 35 of 88
NaN is of type number though, but still, it has no value, because you can’t
perform calculations with numbers and a string of letters right?
typeof(NaN); //says number
You can also find if a number is NaN by using the isNaN() function, which is a
predefined method in javascript.
let a = 30 * "hello";
console.log(isNaN(a));
let b = 30 * 10;
console.log(isNaN(b));
If you know a variable that has NaN in a mathematical operation, the result will
also be NaN, if the other value is a number.
let c = a + b;
console.log(c);
If the other value is a string, the result will be concatenation.
let a = 30 * "hello";
let b = "Hello";
let c = a + b;
console.log(c);
Infinity
Just like NaN, infinity is also a number.
console.log(typeof Infinity);
console.log(typeof -Infinity);
Any operation against infinity is obviously infinity.
let a = 10 * Infinity;
Copyright @ DigiFisk.com
Page 36 of 88
console.log(a);
console.log("<br/>");
let b = 10 * -Infinity;
console.log(b);
Copyright @ DigiFisk.com
Page 37 of 88
Hexadecimal: ${c}
Octal: ${d}
Binary: ${e}`;
Output:
Decimal: 50
Hexadecimal: 32
Octal: 62
Binary: 110010
Exponentiation method
toExponential() method returns a decimal point number after converting it to
exponentials, with the number of decimal points mentioned.
So, there is a single number, rest will be converted to decimals, and the digits
taken are compensated with exponents.
let a = 50.4578;
let b = a.toExponential(2);
let c = a.toExponential(3);
let d = a.toExponential(5);
console.log(b + "\n" + c + "\n" + d);
Output:
5.05e+1
5.046e+1
5.04578e+1
Copyright @ DigiFisk.com
Page 38 of 88
Output:
5.045780000000e+1
Now with a bigger number.
let a = 50000.4578;
Output:
5.00e+4
5.000e+4
5.000045780000e+4
Copyright @ DigiFisk.com
Page 39 of 88
Copyright @ DigiFisk.com
Page 40 of 88
10
NaN
Strings will always return NaN, even if there are numbers inside the string quotes,
the browser will not be able to read them as numbers.
You can also use to convert dates to numbers using the Number method.
In this case, you will get back the value of the number of milliseconds passed
since 1.1.1970 till the date you gave.
The format of giving the date should be like this:
“Year-Month-Day”
Let’s try with one.
let a = Number(new Date("2018-07-12"));
console.log(a);
Output: 1531353600000
What happens if you give a year before 1970? You’ll get a negative value.
let a = Number(new Date("1969-07-12"));
console.log(a);
Output: -14947200000
In the Number() method, if there are spaces between two numbers, it’ll consider
it as an unreadable string, and return NaN.
let a = Number("20 30");
ParseInt method
Copyright @ DigiFisk.com
Page 41 of 88
The next is parseInt() method, which parses the given string into a whole number.
In here, spaces is allowed, unlike the Number() method.
Even if there are decimal numbers, it’ll still convert it to a whole number.
Let’s see some examples.
console.log(
parseInt("2.4552") + "\n" +
parseInt("568") + "\n" +
parseInt("55 97") + "\n" +
parseInt(" 10.004 ") + "\n" +
parseInt("Hello 20") + "\n" +
parseInt(" 20 Hello"));
Output:
2
568
55
10
NaN
20
Converts decimals to whole number. Even if there are space between two
numbers, it’ll still convert the first string to whole number.
It doesn’t matter if a number has space around it.
If the first instance of the string is a word or a letter, it’ll return NaN.
If the first occurrence of the string is a number, it doesn’t matter if the
subsequent occurrences are letters, it’ll convert that first number and leave it at
that.
ParseFloat method
Copyright @ DigiFisk.com
Page 42 of 88
Copyright @ DigiFisk.com
Page 43 of 88
You can’t use these properties on variables though. You’ll get an undefined. These
can only be used on Number, because it returns values that are predefined.
let a = 100;
console.log(a.MAX_VALUE);
Output: undefined
Copyright @ DigiFisk.com
Page 44 of 88
Copyright @ DigiFisk.com
Page 45 of 88
If, else
So, if else is just like it sounds. In English, this is what it means:
If something is true,
Do this
Else,
Do this
That’s it.
In javascript language, this is how it’ll be written
if (condition) {
}
else {
}
So, to find out if the condition is true or not, we’ll use some comparison
operators. Some of the commonly used ones are:
== - Equal to
Copyright @ DigiFisk.com
Page 46 of 88
>-Greater than
<-Less than
>= - Greater than or equal to
<= - Less than or equal to
let num1 = 5;
let num2 = 6;
if (num1 > num2) {
alert("Good!");
}
else {
alert("Not good");
}
Else if statements:
Else if statement is used to specify a new condition if the first condition is false.
You can specify as many conditions as you want like this, and at the end, if none
of those conditions were true, the else statement will be executed.
if(condition1) {
Statements set 1
}
else if (condition2) {
Statements set 2
}
else if (condition 3) {
Statements set 3
Copyright @ DigiFisk.com
Page 47 of 88
}
.
.
.
else {
Statements set n
}
Let’s look at an example.
let num = 5;
let secretNum = 10;
if(num < secretNum) {
console.log("Go a bit higher");
}
else if(num > secretNum) {
console.log("Go a bit lower");
}
else {
console.log("You guessed it right!");
}
Switch:
With switch, you can take up multiple conditions. This is the syntax of a switch
statement:
switch (variable or condition) {
Copyright @ DigiFisk.com
Page 48 of 88
Copyright @ DigiFisk.com
Page 49 of 88
Loops
Loops allow a programmer to execute the same statement or a set of statements
again and again, for a number of times specified.
There are 3 kinds of loops: For loop, while loop and do while loop.
So, any loop basically does this:
It checks for a condition, and as long as the condition is true, it’ll execute the
statements within the loop. Once the condition becomes false, it’ll stop executing.
For loop
The syntax of the for loop is as follows:
for (initialization; condition; increment) {
Statements;
}
Example:
for (i = 1; i <= 5; i++) {
console.log(i);
}
Output: 12345
Copyright @ DigiFisk.com
Page 50 of 88
While loop
Syntax:
Initialization;
while(condition) {
Block of code;
Increment;
}
Ex:
let i=1;
Copyright @ DigiFisk.com
Page 51 of 88
while(i<=10) {
console.log(i + "<br/>");
i++;
}
Don’t forget to include increment or decrement condition within the loop, or the
loop will run endlessly and crash the browser.
For loops and while loops have similar syntaxes. One can be converted to
another. Convert the above into a for loop.
for(let j=1; j<=10; j++) {
console.log(j);
}
If you omit the first and last statements in the for loop, it looks similar to the
while loop.
let j=1;
for(;j<=10; ) {
console.log(j);
j++;
}
Do while loop
While loop will not execute if the condition is false.
let i=11;
while(i<=10) {
console.log(i);
i++;
Copyright @ DigiFisk.com
Page 52 of 88
}
No output. But, do while is a variant of while loop where it executes at least once,
regardless of whether the condition is false or true.
Syntax is as follows:
Initialization;
do {
Block of code;
Increment;
}while (condition);
Copyright @ DigiFisk.com
Page 53 of 88
}
console.log(i);
i++;
}
Copyright @ DigiFisk.com
Page 54 of 88
i++;
}
Only 6 will not be printed. Rest won’t printed.
Copyright @ DigiFisk.com
Page 55 of 88
Module 7: Arrays
Arrays allow you to store an array of values inside a variable, and access them
separately, or together.
Creating/declaring an array:
let number = new Array();
Assigning values to an array:
number = [1, 2, 3, 4, 5];
Accessing values in an array (starts from index 0):
alert(number[0]);
The output is 1.
We can also change values, or add values this way.
number[5] = 6;
number[4] = 7;
Now,
alert(number[6]);
We get 7, instead of the 5 we originally gave.
We can also store strings and Boolean values, not just numbers.
let number = ["one", "two", "three"];
Copyright @ DigiFisk.com
Page 56 of 88
Copyright @ DigiFisk.com
Page 57 of 88
Array length
You can find the number of items in an array using the length property.
console.log(array1.length);
Push method
You can also use the push method, which is a built in javascript method, to add
new items at the end of the array.
array1.push(5);
console.log(array1);
If you want to push a string:
array1.push("string");
console.log(array1);
You can also push a variable inside the array.
let x = 20;
array1.push(x)
console.log(array1);
Also, if you assign the push statement to another variable, you’ll get the new
length of the array.
let y = array1.push("New");
console.log("New length of array: " + y);
Pop method
you can pop items out of the array. Use the pop method to pop the last element
in the array.
let array1 = [2, 6, 4, 9, 3, 7];
Copyright @ DigiFisk.com
Page 58 of 88
array1.pop();
console.log(array1);
Can also assign the popped item to a variable.
let x = array1.pop();
console.log(x);
Join method
let array1 = [2, 6, 4, 9, 3, 7];
let newString = array1.join();
console.log(newString);
console.log(typeof newString);
Similar to above.
Now, different separators.
let string2 = array1.join(".");
console.log(string2);
let string3 = array1.join(" | "); //can give space, or multiple characters as
separators
console.log(string3);
let string4 = array1.join(" *^ ");
console.log(string4);
Copyright @ DigiFisk.com
Page 59 of 88
Get PI value
let p = Math.PI;
You can round a given number to its nearest value by using the round() method of
the Math object, like this:
console.log(Math.round(5.5));
console.log(Math.round(5.6));
console.log(Math.round(5.4));
You can round a number to its ceiling value by using the ceil() method.
console.log(Math.ceil(5.4));
You can round a number to its floor value by using the floor() method.
console.log(Math.floor(5.6));
Copyright @ DigiFisk.com
Page 60 of 88
You can find the square root of a number by using the sqrt() method.
console.log(Math.sqrt(25));
You can use the trunc() method to find the integer value of a given decimal
number.
console.log(Math.trunc(5.36));
You can use the abs() method to find the absolute value of a number, that is,
positive value of a number.
console.log(Math.abs(-15));
You can find the minimum and maximum value of a set of values as well.
Math.min(10,25,-50,50,100,0);
Math.max(10,25,-50,50,100,0);
Copyright @ DigiFisk.com
Page 61 of 88
Module 9: Functions
A javascript function is a block of code that performs something, like calculations,
comparisons, etc. Functions are used for a lot of purposes in programs.
They save lines of code and time, since a function can be called again and again to
execute the same block of code within them.
Syntax:
Function declaration/definition:
function functionName() {
}
Function call:
functionName();
Example:
Prints “Hello there” when the function is called.
function printHello() {
alert("Hello there!");
}
printHello();
Copyright @ DigiFisk.com
Page 62 of 88
Local variables:
Variables created within functions only have scope within them. They are called
local variables.
function name() {
let num;
}
alert(num);
Reference error: num not defined. That’s because num is a local variable that is
created within the function “name” and only works within that. It has local scope
or function scope.
Copyright @ DigiFisk.com
Page 63 of 88
addNum();
Can be string or Boolean too, not just numbers.
function whoIsThis(child = true, message = "Child!") {
if(child === true) {
alert(message);
}
else {
alert("Nope!");
}
}
whoIsThis();
whoIsThis(false);
whoIsThis(true);
whoIsThis(true,"Baby!");
Copyright @ DigiFisk.com
Page 64 of 88
console.log(mul);
return mul;
}
Functions as values
Functions can be used as values in calculations as well, like this:
"use strict";
function addNum(num1, num2) {
let sum = num1 + num2;
return sum;
}
let mul = addNum(5,2) * 3;
alert(mul);
Copyright @ DigiFisk.com
Page 65 of 88
Copyright @ DigiFisk.com
Page 66 of 88
console.log(age);
When we alert age, we get the function definition. It’s the string representation of
the function. That’s what happens.
But, alternatively, you can call the function and let it run like this:
age();
It works similar to a normal function call.
This function can be copied to another variable like this:
let age1 = age;
age1();
Also, function declarations created within code blocks have a block scope and
cannot be called from outside the block.
var bool = true;
var age;
if(bool == true) {
age = function(a = 5) {
alert(a);
}
}
age();
Self-Invoking functions
Copyright @ DigiFisk.com
Page 67 of 88
You can make function expressions self-invoking. Basically, you can make them
call themselves.
You can’t make function declarations self-invoking though, only function
expressions.
Add a () after the function to indicate that it’s self-invoking.
"use strict";
(function() {
alert("I am a self-invoking function!");
})();
Or, you can use a traditional function expression and make it self-invoking as well,
like this:
var age = function() {
alert("Hello child!");
}();
Arrow functions
It’s an ES6 update. These are also called as Fat arrows.
They are used to shorten the functions.
Originally:
let helloFunc = function() {
return "Hello world";
}
console.log(helloFunc());
Shorten it:
Copyright @ DigiFisk.com
Page 68 of 88
Shorten it further:
If there is only one line of code in the function.
let helloFunc = () => "Hello world";
console.log(helloFunc());
Or:
let helloFunc = () => alert("Hello world");
helloFunc();
Shorten it:
let sumNum = (a,b) => a + b;
console.log(sumNum(5,6));
Copyright @ DigiFisk.com
Page 69 of 88
Without parentheses:
If only one parameter, then no need for brackets:
let dispString = a => alert(a);
console.log(dispString("Hello World!"));
Doesn’t work with multiple parameters
Arguments object
There’s a built-in object called the arguments object that’ll store all the
arguments in the form of an array.
You can access the arguments later as you would with array items, and also
calculate the length with the length method, if needed.
If there are too many arguments in a function call, the arguments object is a great
way to access them.
"use strict";
function addNum() {
let sum = 0;
for(let i=0; i<arguments.length; i++) {
sum += arguments[i];
}
alert(sum);
}
let valSum = addNum(15,66,73,24,99,16,49,89,35,26,14);
Recursive functions
Recursive functions are functions that call themselves.
Copyright @ DigiFisk.com
Page 70 of 88
Copyright @ DigiFisk.com
Page 71 of 88
Copyright @ DigiFisk.com
Page 72 of 88
You can use the spread syntax with pre-defined functions as well:
To find the max of given numbers using the pre-defined max function, use the
below line of code:
console.log(Math.max(4,6,-4,2));
If we use arrays, we’ll get an array, but we can use the spread syntax for that as
well.
let arr = [4,6,-4,2]
console.log(Math.max(...arr));
Can use for multiple arrays too:
let arr = [4,6,-4,2];
let arr2 = [15,6,-32,54];
console.log(Math.max(...arr, ...arr2));
Rest parameters
If a function is sent extra arguments, there won’t be an error. They just won’t be
taken into account.
For example, look at the below lines of code:
function addNum(num1,num2) {
let sum = num1 + num2;
Copyright @ DigiFisk.com
Page 73 of 88
return sum;
}
console.log(addNum(5,3,6,7,3));
There won’t be an error even though you’re sending too many extra arguments.
They just won’t be taken into account at all.
But there is a way to take the extra arguments into account, accept just the
extras, or the entire arguments list into an array and use them in the function.
You can use the rest syntax to do that.
We’ll be using the same “…”, but this time, in the function definition.
function addNum(num1,num2,...arr) {
let sum = num1 + num2;
console.log(arr);
return sum;
}
console.log(addNum(5,3,6,7,3));
We can use the array inside the function as well:
function addNum(num1,num2,...arr) {
let sum = num1 + num2;
for(let a of arr) {
sum += a;
}
return sum;
}
console.log(addNum(5,3,6,7,3));
We can accept the entire list of arguments into a user defined array name as well:
Copyright @ DigiFisk.com
Page 74 of 88
function addNum(...arr) {
let sum = 0;
for(let a of arr) { //explain this syntax
sum += a;
}
Copyright @ DigiFisk.com
Page 75 of 88
function helloThere(name) {
alert("Hello there, " + name + "!");
}
setTimeout(helloThere, 2000, "John"); //after 2 second delay
You can also run pre-defined functions like alerts from within the setTimeout call.
Give them as strings and your browser will piece everything together and run it as
a function.
setTimeout("alert('Hello there!')", 2000);
You can give the same as an arrow function. In fact, it’s recommended that you
do so.
setTimeout(()=>alert('Hello there!'), 2000);
We can cancel this time out if needed. Assign this to another variable. It returns a
timer identifier, and you can use the clearTimeout function, with the timer
identifier as the argument to cancel the Time out you set.
let tr = setTimeout(()=>alert('Hello there!'), 2000);
console.log(tr);
clearTimeout(tr);
console.log(tr);
The timer identifier is returned as a number.
Since we cancelled it, nothing happens.
We can give conditions based on this as well (for cancellation), if needed.
With the setInterval function, you can run the function repeatedly based on the
given time interval. ‘I’ is caps here and its case sensitive.
Copyright @ DigiFisk.com
Page 76 of 88
Example:
Outputs in console every 2 seconds. Keeps running.
let count = 0;
setInterval(()=>console.log(++count + " alert"),2000);
Copyright @ DigiFisk.com
Page 77 of 88
Copyright @ DigiFisk.com
Page 78 of 88
Copyright @ DigiFisk.com
Page 79 of 88
Copyright @ DigiFisk.com
Page 80 of 88
Copyright @ DigiFisk.com
Page 81 of 88
types
attributes
etc.
For example, add a div to your example:
<div class="grp">This is a new div</div>
Now, if you used byClassName, you’ll get the div added as well.
What if you wanted only the paragraphs with the class “grp” to be considered?
let x = document.querySelectorAll("p.grp");
Now it’ll work as you want it to.
Copyright @ DigiFisk.com
Page 82 of 88
Copyright @ DigiFisk.com
Page 83 of 88
Events
Events can be used to create an action-reaction effect.
We can create a click event that does something when a HTML element is clicked,
like this:
<button id="button1" onclick="buttonClick()">Button</button>
buttonClick() {
alert("Thanks for clicking!");
}
Copyright @ DigiFisk.com
Page 84 of 88
So, whenever the button is clicked, an alert that says, “Thanks for clicking” would
pop up.
You can achieve the same result without having the function call in your HTML
code.
It’s always best practice to separate your HTML, CSS and Javascript codes into
separate files.
You can use event listeners to achieve the same result, like this:
Retrieve the element first and then create a click event listener on it:
document.getElementById("button1").addEventListener("click", buttonClick);
Or, do it like this:
let button1 = document.getElementById("button1");
button1.addEventListener("click", buttonClick);
Mouse down:
Does something when the mouse button (left) is pressed down on the element.
Copyright @ DigiFisk.com
Page 85 of 88
<div id="mouseTest"><div>
Let’s create a quick border for it, so you know where it is.
#mouseTest {
border: 1px solid black;
}
So, first retrieve the div element.
let mouseTest = document.getElementById("mouseTest");
Now, create a mousedown event for this
mouseTest.addEventListener("mousedown", downEvent);
function downEvent() {
mouseTest.style.backgroundColor = "red";
}
Now, create an event for what happens when the mouse pointer moves on the
given element:
mouseTest.addEventListener("mousemove", moveEvent);
function moveEvent() {
mouseTest.style.backgroundColor = "yellow";
}
Other events:
keypress – when an element is pressed on by a keyboard key
keydown – when the key is pressed
keyup – when the key is let up
Copyright @ DigiFisk.com
Page 86 of 88
mousedown – when mouse button is clicked over element or one of its children
mouseup – mouse pointer stops pressing over element
mouseenter – mouse pointer enters element
mouseleave – mouse pointer leaves element
mousemove – mouse pointer moving over an element
Copyright @ DigiFisk.com
Page 87 of 88
Match method:
let check = string.match(rex);
console.log(check);
Copyright @ DigiFisk.com
Page 88 of 88
Copyright @ DigiFisk.com