Javascript Tutorial
Javascript Tutorial
Arindam Saha
What is Javascript?
JavaScript was developed by Brendan Eich in May 1995 while he was working at
Netscape Communications Corporation.
Javascript Variables
JavaScript Variables can be declared in 4 ways:
● Automatically
● Using var
● Using let
● Using const
Automatic Variables : x, y, and z are undeclared variables. They are automatically declared.
X = 5;
Y = 6;
Z = X+Y
Javascript Variables
With let you can not do this:
let x = 0;
objects, arrays, dates, maps, sets, intarrays, float, arrays, promises, and more.
JavaScript Can Change HTML Content
One of many JavaScript HTML methods is getElementById() . The example below "finds" an
HTML element (with id="demo"), and changes the element content (innerHTML) to "Hello
JavaScript":
To access an HTML element, you can use DOM feature such as the document.getElementById(id)
method. Use the id attribute to identify the HTML element. Then use the innerHTML property to
change the HTML content of the HTML element:
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
"<h2>Hello World</h2>";
</script>
JavaScript Comments
● Single Line Comments
Single line comments start with //.
Any text between // and the end of the line will be ignored by JavaScript (will not be executed).
● Multi-line Comments
Multi-line comments start with /* and end with */.
Function Invocation
The code inside the function will execute when "something" invokes (calls) the function:
Note: As you see from the examples above, toCelsius refers to the function object,
and toCelsius() refers to the function result.
JavaScript Objects
In real life, objects are things like: houses, cars, people, animals, or any other subjects. Here is a car
object example:
JavaScript Objects
Objects are variables too. But objects can contain many values. This code assigns
many values (Fiat, 500, white) to an object named car:
<h2>Creating an Object</h2>
<p id="demo"></p>
<script>
// Create an Object:
const car = {type:"Fiat", model:"500", color:"white"};
// Display Data from the Object:
document.getElementById("demo").innerHTML = "The car type is " + car.type;
</script>
JavaScript Objects
This example creates an empty JavaScript object, and then adds 4 properties:
// Create an Object
// Add Properties
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";
JavaScript Object Methods
Object methods are actions that can be performed on objects. A method is a function
definition stored as a property value.
JavaScript Object Constructors
Sometimes we need to create many objects of the same type. To create an object type we
use an object constructor function. It is considered good practice to name constructor
functions with an upper-case first letter.
Constructor Function Methods
HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.
JavaScript Events
In the following example, an onclick attribute (with code), is added to a <button> element:
Common HTML Events
Onchange Event
<h1>JavaScript HTML Events</h1>
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
</select>
Onclick Event
<button onclick="alert('Button clicked!')">Click Me</button>
Onmouseover Event
<div onmouseover="this.style.backgroundColor='yellow'">Hover over me!</div>
Onmouseout
<div onmouseout="this.style.backgroundColor='transparent'">Move mouse away from me!</div>
Onmouseout
<div onmouseout="this.style.backgroundColor='transparent'">Move mouse away from me!</div>
Onload Event
<!DOCTYPE html>
<html>
</body>
</html>
JavaScript Strings
Strings are for storing text, Strings are written with quotes.
Common Methods used in Strings : Javascript strings are primitive and immutable: All string
methods produce a new string without altering the original string.
Result:
String toLowerCase()
This function helps to make the string to Lowercase.
Results:
String concat()
The concat() method can be used instead of the plus operator. concat() joins two or more
strings.
Results:
String repeat()
The repeat() method returns a string with a number of copies of a string.The repeat()
method returns a new string. This method does not change the original string.
Results:
Replacing String Content
The replace() method replaces a specified value with another value in a string.
Results:
String ReplaceAll()
This function allows the user to replace all the regular expression to be replaced instead of
replacing a whole string.
Results:
String split()
A string can be converted to an array with the split() method.
Results:
String trim()
The trim() method removes whitespace from both sides of a string.
Results:
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).
Results:
String Length
The length property returns the length of a string.
Results:
String Search Methods
String search methods refer to techniques used to find or locate a substring within a larger string.
These methods are widely used in programming for tasks like pattern matching, searching for
specific words, or finding occurrences of substrings in text data. Some of the common techniques
are: indexOf(), search(), match(), matchAll() etc.
indexOf(): The indexOf() method returns the index (position) of the first occurrence
of a string in a string, or it returns -1 if the string is not found.
String Search Methods
search(): The search() method searches a string for a string (or a regular expression) and
returns the position of the match.
match(): The match() method returns an array containing the results of matching a string
against a string (or a regular expression).
JavaScript Arrays
In JavaScript, an array is a special type of object used to store multiple values in a single variable.
Arrays can hold elements of any data type, such as numbers, strings, objects, or even other
arrays. They are ordered collections, meaning that the elements inside the array have an index
(position) that can be used to access or modify the elements.
push(): The push() method adds a new element to an array (at the end).
pop(): The pop() method remove a element of an array (at the end).
Array Methods
splice(): The splice() method can be used to add new items to an array.
The first parameter (2) defines the position where new elements should be added (spliced
in). The second parameter (0) defines how many elements should be removed. The rest of
the parameters ("Lemon" , "Kiwi") define the new elements to be added.
slice(): The slice() method slices out a piece of an array into a new array.
Array Methods
sort(): The sort() methods is used to sort the array.
You can use the Boolean() function to find out if an expression (or a variable) is true.
If-else in Javascript
The if...else statement in JavaScript is used for decision-making.
#Syntax
if (condition) {
// Code to run if condition is true
} else {
// Code to run if condition is false
}
Example:
let age = 18;
Note: The switch expression is evaluated once. The value of the expression is compared with the values of
each case. If there is a match, the associated block of code is executed. If there is no match, the default
code block is executed.
Switch Case
The getDay() method returns the weekday as a number between 0 and 6 (Sunday=0, Monday=1, Tuesday=2
..). This example uses the weekday number to calculate the weekday name:
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
External JS
Linking an external JavaScript file to an HTML file is a common and clean way to organize
code.
function showMessage() {
alert("Hello from external JavaScript!");
}
class Greeter {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello, ${this.name}!`);
}
}
External JS
Linking an external JavaScript file to an HTML file is a common and clean way to organize
code.
Example:
JavaScript For-In
The JavaScript for in statement loops through the properties of an Object:
#Syntax
JavaScript For Of
The JavaScript for of statement loops through the values of an iterable object.
JavaScript While Loop
Loops can execute a block of code as long as a specified condition is true.
#Syntax
Example:
Do While Loop in Javascript
The do while loop is a variant of the while loop. This loop will execute the code block once, before
checking if the condition is true, then it will repeat the loop as long as the condition is true.
#Syntax
Example:
JavaScript Break and Continue
The Break Statement
You have already seen the break statement used in an earlier chapter of this tutorial. It was used to "jump out" of a
switch() statement.
add() Method:
has() Method:
Date & Time in Javascript
In JavaScript, date objects are created with new Date(), new Date() returns a date
object with the current date and time.
The get methods return information from existing date objects. In a date object,
the time is static. The "clock" is not "running". The time in a date object is NOT the
same as current time.
Date & Time in Javascript
Get Methods
Date & Time in Javascript
getFullYear()
getMonth()
getDate()
Date & Time in Javascript
getDay(): get weekends.
getHours():
getMinutes()
JavaScript Maps
The map() method is used with arrays to create a new array by applying a function to each element of
the original array. It does not modify the original array.
const numbers = [1, 2, 3, 4, 5];
console.log(doubled);
Here:
The search() method uses an expression to search for a match, and returns the position of the match.
The replace() method returns a modified string where the pattern is replaced.
String Formatting
Modern Style
let name = "John Doe";
let age = 25;
Old Style
var message = "Hello, my name is " + name + " and I am " + age + " years old.";
console.log(message);
Error Handling in Javascript
When executing JavaScript code, different errors can occur. Errors can be coding errors
made by the programmer, errors due to wrong input, and other unforeseeable things.
The finally statement defines a code block to run regardless of the result.
#Syntax
Error Handling in Javascript
Example:
function divideNumbers(a, b) {
try {
if (b === 0) {
throw new Error("Cannot divide by zero.");
}
let result = a / b;
console.log(`Result: ${result}`);
} catch (error) {
console.error(`Error occurred: ${error.message}`);
} finally {
console.log("Division attempt completed.");
}
}
// Test cases
divideNumbers(10, 2); // Result: 5
divideNumbers(10, 0); // Error: Cannot divide by zero
Error Handling in Javascript
Types of error
Javascript Classes
classes are a template for creating objects. They are introduced in ES6 (ECMAScript 2015) and provide a
cleaner, more structured way to create objects and deal with inheritance compared to traditional prototype-based
syntax.
Javascript Classes