Introduction to JavaScript Basics
Introduction to JavaScript Basics
MODULE III
JavaScript
1
JavaScript
What is JavaScript ?
JavaScript is a dynamic computer programming language. It is lightweight and most
commonly used as a part of web pages.
It allow client-side script to interact with the user and make dynamic pages. It is an
interpreted programming language with object-oriented capabilities.
Syntax:
<script ...>
JavaScript code
</script>
Example:
<html>
<body>
<script language="javascript" type="text/javascript">
[Link]("Hello World!");
</script>
</body>
</html>
Client-side JavaScript
Client-side JavaScript is the most common form of javascript language. The script
should be included in HTML document for the code to be interpreted by the browser.
Dynamic web pages can be created by integrating javascript code to HTML content.
The JavaScript client-side mechanism provides many advantages over traditional CGI
server-side scripts. For example, you might use JavaScript to check if the user has
entered a valid e-mail address in a form [Link] JavaScript code is executed when the
user submits the form, and only if all the entries are valid, they would be submitted to
the Web Server.
2
JavaScript
JavaScript can be used to trap user-initiated events such as button clicks, link
navigation, and other actions that the user initiates explicitly or implicitly.
Advantages of JavaScript
The merits of using JavaScript are −
Less server interaction − You can validate user input before sending the page off to the
server. This saves server traffic, which means less load on your server.
Immediate feedback to the visitors − They don't have to wait for a page reload to see if
they have forgotten to enter something.
Increased interactivity − You can create interfaces that react when the user hovers over
them with a mouse or activates them via the keyboard.
Richer interfaces − You can use JavaScript to include such items as drag-and-drop
components and sliders to give a Rich Interface to your site visitors.
<html>
<head>
<script type = "text/javascript">
function sayHello()
{
alert("Hello World")
}
</script>
</head>
3
JavaScript
<body>
<input type = "button" value = "Say Hello" />
</body>
</html>
<html>
<head>
</head>
<body>
<script type = "text/javascript">
[Link]("Hello World")
</script>
4
JavaScript
<html>
<head>
<script type = "text/javascript">
function sayHello()
{
alert("Hello World")
}
</script>
</head>
<body>
<script type = "text/javascript">
[Link]("Hello World")
</script>
5
JavaScript
You are not restricted to be maintaining identical code in multiple HTML files. The script tag
provides a mechanism to allow you to store JavaScript in an external file and then include it
into your HTML files.
Here is an example to show how you can include an external JavaScript file in your HTML code
using script tag and its src attribute.
<html>
<head>
<script type = "text/javascript" src = "[Link]" ></script>
</head>
<body>
.......
</body>
</html>
To use JavaScript from an external file source, you need to write all your JavaScript source
code in a simple text file with the extension ".js" and then include that file as shown above.
6
JavaScript
For example, you can keep the following content in [Link] file and then you can
use sayHello function in your HTML file after including the [Link] file.
function sayHello()
{
alert("Hello World")
}
JavaScript Variables
Like many other programming languages, JavaScript has variables. Variables can be
thought of as named containers. You can place data into these containers and then
refer to the data simply by naming the container.
Before you use a variable in a JavaScript program, you must declare it. Variables are
declared with the var keyword as follows.
7
JavaScript
Global Variables − A global variable has global scope which means it can be defined
anywhere in your JavaScript code.
Local Variables − A local variable will be visible only within a function where it is
defined. Function parameters are always local to that function.
1. Arithmetic Operators
2. Comparison Operators
4. Assignment Operators
1. Arithmetic Operators
JavaScript supports the following arithmetic operators − Assume variable A holds 10 and
variable B holds 20, then −
1 + (Addition)
Adds two operands
Ex: A + B will give 30
8
JavaScript
2 - (Subtraction)
Subtracts the second operand from the first
Ex: A - B will give -10
3 * (Multiplication)
Multiply both operands
Ex: A * B will give 200
4 / (Division)
Divide the numerator by the denominator
Ex: B / A will give 2
5 % (Modulus)
Outputs the remainder of an integer division
Ex: B % A will give 0
6 ++ (Increment)
Increases an integer value by one
Ex: A++ will give 11
7 -- (Decrement)
Decreases an integer value by one
Ex: A-- will give 9
2. Comparison Operators
JavaScript supports the following comparison operators − Assume variable A holds 10 and
variable B holds 20, then −
1 = = (Equal)
Checks if the value of two operands are equal or not, if yes, then the condition
becomes true.
Ex: (A == B) is not true.
2 != (Not Equal)
Checks if the value of two operands are equal or not, if the values are not equal,
9
JavaScript
3. Logical Operators
JavaScript supports the following logical operators −Assume variable A holds 10 and variable B
holds 20, then −
2 || (Logical OR)
If any of the two operands are non-zero, then the condition becomes true.
Ex: (A || B) is true.
10
JavaScript
3 ! (Logical NOT)
Reverses the logical state of its operand. If a condition is true, then the Logical
NOT operator will make it false.
Ex: ! (A && B) is false.
4. Bitwise Operators
JavaScript supports the following bitwise operators −Assume variable A holds 2 and variable B
holds 3, then −
2 | (BitWise OR)
It performs a Boolean OR operation on each bit of its integer arguments.
Ex: (A | B) is 3.
11
JavaScript
5. Assignment Operators
JavaScript supports the following assignment operators −
1 = (Simple Assignment )
Assigns values from the right side operand to the left side operand
Ex: C = A + B will assign the value of A + B into C
Miscellaneous Operator
We will discuss two operators here that are quite useful in JavaScript: the conditional
operator (? :) and the typeof operator.
12
JavaScript
7. Conditional Operator (? :)
The conditional operator first evaluates an expression for a true or false value and then
executes one of the two given statements depending upon the result of the evaluation.
1 ? : (Conditional )
8. typeof Operator
The typeof operator evaluates to "number", "string", or "boolean" if its operand is a number,
string, or boolean value and returns true or false based on the evaluation.
One of the most fundamental characteristics of a programming language is the set of data
types it supports. These are the type of values that can be represented and manipulated in a
programming language.
JavaScript also defines two trivial data types, null and undefined, each of which defines only a
single value. In addition to these primitive data types, JavaScript supports a composite data
type known as object.
13
JavaScript
Example
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = [Link];
Output : sln=26
2. indexOf() method returns the index of (the position of) the first occurrence of a specified
text in a string:
Example
var str = "Please locate where 'locate' occurs!";
var pos = [Link]("locate");
JavaScript counts positions from zero.
0 is the first position in a string, 1 is the second, 2 is the third ...
Pos returnd the value 8
3. Searching for a String in a String :The search() method searches a string for a specified
value and returns the position of the match:
Example
var str = "Please locate where 'locate' occurs!";
var pos = [Link]("locate");
4. Extracting String Parts :There are 3 methods for extracting a part of a string:
1. slice(start, end)
2. substring(start, end)
3. substr(start, length)
14
JavaScript
slice() extracts a part of a string and returns the extracted part in a new string.
The method takes 2 parameters: the start position, and the end position (end not included).
This example slices out a portion of a string from position 7 to position 12 (13-1):
Example
var str = "Apple, Banana, Kiwi";
var res = [Link](7, 13);
The result of res will be:
Banana
The replace() method replaces a specified value with another value in a string:
Example
str = "Please visit Microsoft!";
var n = [Link]("Microsoft", "MACAS");
Output : Please visit MACAS
15
JavaScript
Example
var text1 = "Hello World!"; // String
var text2 = [Link](); // text2 is text1 converted to upper
A string is converted to lower case with toLowerCase():
Example
var text1 = "Hello World!"; // String
var text2 = [Link](); // text2 is text1 converted to lower
Example
var text1 = "Hello";
var text2 = "World";
var text3 = [Link](" ", text2);
The concat() method can be used instead of the plus operator. These two lines do the same:
8. [Link]()
[Link]() removes whitespace from both sides of a string.
Example
var str = " Hello World! ";
alert([Link]());
16
JavaScript
[Link](0); // returns H
The charCodeAt() Method
The charCodeAt() method returns the unicode of the character at a specified index in a string:
Example
var str = "HELLO WORLD";
[Link](0); // returns 72
Syntax
Use the following syntax to create an Array object –
The Array parameter is a list of strings or integers. When you specify a single numeric
parameter with the Array constructor, you specify the initial length of the array. The maximum
length allowed for an array is 4,294,967,295.
You will use ordinal numbers to access and to set values inside an array as follows.
17
JavaScript
Array Properties
Here is a list of the properties of the Array object along with their description.
1 constructor
2 index
The property represents the zero-based index of the match in the string
3 input
4 length
In the following sections, we will have a few examples to illustrate the usage of Array
properties.
FUNTIONS IN JAVASCRIPT
A function is a group of programming code which can be called anywhere in your
program. This eliminates the need of writing the same code again and again. It helps
programmers in writing modular codes. Functions allow a programmer to divide a big
program into a number of small and manageable functions.
Like any other advanced programming language, JavaScript also supports all the
features necessary to write modular code using functions.
JavaScript allows us to write our own functions as well. This section explains how to
write your own functions in JavaScript.
18
JavaScript
Function Definition
Before we use a function, we need to define it. The most common way to define a function in
JavaScript is by using the function keyword, followed by a unique function name, a list of
parameters (that might be empty), and a statement block surrounded by curly braces.
Syntax
The basic syntax is shown here.
<script type="text/javascript">
function functionname(parameter-list)
{
statements
}
</script>
Example
Try the following example. It defines a function called sayHello that takes no parameters –
<script type="text/javascript">
function sayHello()
{
alert("Hello there");
}
</script>
Calling a Function
To invoke a function somewhere later in the script, you would simply need to write the name
of that function as shown in the following code.
19
JavaScript
<html>
<head>
<script type="text/javascript">
function sayHello()
{
[Link] ("Hello there!");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" value="Say Hello">
</form>
Objects in JavaScript
Objects are composed of attributes. If an attribute contains a function, it is considered to be a
method of the object, otherwise the attribute is considered a property.
Object Properties
Object properties can be any of the three primitive data types, or any of the abstract data
types, such as another object. Object properties are usually variables that are used internally
in the object's methods, but can also be globally visible variables that are used throughout the
page.
[Link] = propertyValue;
20
JavaScript
For example − The following code gets the document title using the "title"property of
the document object.
Object Methods
Methods are the functions that let the object do something or let something be done to it.
There is a small difference between a function and a method – at a function is a standalone
unit of statements and a method is attached to an object and can be referenced by
the this keyword.
For example − Following is a simple example to show how to use the write() method of
document object to write any content on the document.
[Link]("This is test");
The Date object is a datatype built into the JavaScript language. Date objects are created with
the new Date( ) as shown below.
Once a Date object is created, a number of methods allow you to operate on it. Most methods
simply allow you to get and set the year, month, day, hour, minute, second, and millisecond
fields of the object, using either local time or UTC (universal, or GMT) time.
You can use any of the following syntaxes to create a Date object using Date() constructor.
new Date( )
new Date(milliseconds)
new Date(datestring)
21
JavaScript
1. if statement
2. if...else statement
1. if statement
The if statement is the fundamental control statement that allows JavaScript to make
decisions and execute statements conditionally.
Syntax
The syntax for a basic if statement is as follows −
if (expression)
{
Statement(s) to be executed if expression is true
}
Here a JavaScript expression is evaluated. If the resulting value is true, the given statement(s)
are executed. If the expression is false, then no statement would be not executed. Most of the
times, you will use comparison operators while making decisions.
22
JavaScript
Example
Try the following example to understand how the if statement works.
2. if...else statement
The 'if...else' statement is the next form of control statement that allows JavaScript to execute
statements in a more controlled way.
Syntax
if (expression)
{
Statement(s) to be executed if expression is true
}
else
{
Statement(s) to be executed if expression is false
}
Here JavaScript expression is evaluated. If the resulting value is true, the given statement(s) in
the ‘if’ block, are executed. If the expression is false, then the given statement(s) in the else
block are executed.
Example
Try the following code to learn how to implement an if-else statement in JavaScript.
23
JavaScript
Syntax
The syntax of an if-else-if statement is as follows −
if (expression 1)
{
Statement(s) to be executed if expression 1 is true
}
else if (expression 2)
{
Statement(s) to be executed if expression 2 is true
}
else if (expression 3)
{
Statement(s) to be executed if expression 3 is true
}
else
{
Statement(s) to be executed if no expression is true
}
There is nothing special about this code. It is just a series of if statements, where each if is a
part of the else clause of the previous statement. Statement(s) are executed based on the true
condition, if none of the conditions is true, then the else block is executed.
24
JavaScript
Example
Try the following code to learn how to implement an if-else-if statement in JavaScript.
Output
Maths Book
Set the variable to different value and then try...
You can use multiple if...else…if statements, as in the previous chapter, to perform a multiway
branch. However, this is not always the best solution, especially when all of the branches
depend on the value of a single variable.
Starting with JavaScript 1.2, you can use a switch statement which handles exactly this
situation, and it does so more efficiently than repeated if...else ifstatements.
4. switch Statement
The following flow chart explains a switch-case statement works.
The objective of a switch statement is to give an expression to evaluate and several different
statements to execute based on the value of the expression. The interpreter checks
each case against the value of the expression until a match is found. If nothing matches,
a default condition will be used.
25
JavaScript
switch (expression)
{
case condition 1:
statement(s)
break;
case condition 2:
statement(s)
break;
...
case condition n:
statement(s)
break;
default: statement(s)
}
The break statements indicate the end of a particular case. If they were omitted, the
interpreter would continue executing each statement in each of the following cases.
Example
Try the following example to implement switch-case statement.
case 'B':
[Link]("Pretty good<br />");
break;
case 'C':
[Link]("Passed<br />");
break;
case 'D':
26
JavaScript
case 'F':
[Link]("Failed<br />");
break;
default:
[Link]("Unknown grade<br />")
}
[Link]("Exiting switch block");
</script>
Output
Entering switch block
Good job
Exiting switch block
Set the variable to different value and then try...
Looping in JavaScript
While writing a program, you may encounter a situation where you need to perform an action
over and over again. In such situations, you would need to write loop statements to reduce the
number of lines.
JavaScript supports all the necessary loops to ease down the pressure of programming.
Syntax
The syntax of while loop in JavaScript is as follows −
while (expression)
{
Statement(s) to be executed if expression is true
}
27
JavaScript
Example
Try the following example to implement while loop.
<script type="text/javascript">
var i = 0;
while (i < 10)
{
[Link]( i + "<br />");
count++;
}
</script>
Output
1
2
3
4
5
6
7
8
9
10
3. The do...while Loop
The do...while loop is similar to the while loop except that the condition check happens at the
end of the loop. This means that the loop will always be executed at least once, even if the
condition is false.
Syntax
The syntax for do-while loop in JavaScript is as follows −
Do
{
Statement(s) to be executed;
}
while (expression);
28
JavaScript
Example
<script type="text/javascript">
var i= 0;
do
{
[Link]( i + "<br />");
i++;
}
while (i < 5);
</script>
Output
1
2
3
4
5
4. The 'for' loop
It is the most compact form of looping. It includes the following three important parts −
The loop initialization where we initialize our counter to a starting value. The
initialization statement is executed before the loop begins.
The test statement which will test if a given condition is true or not. If the condition is
true, then the code given inside the loop will be executed, otherwise the control will
come out of the loop.
The iteration statement where you can increase or decrease your counter.
You can put all the three parts in a single line separated by semicolons.
Syntax
The syntax of for loop is JavaScript is as follows −
29
JavaScript
Example
Try the following example to learn how a for loop works in JavaScript.
Output
1
2
3
4
The break Statement
The break statement, which was briefly introduced with the switch statement, is used to exit a
loop early, breaking out of the enclosing curly braces.
Example
The following example illustrates the use of a break statement with a while loop. Notice how
the loop breaks out early once x reaches 5 and reaches to [Link] (..) statement just
below to the closing curly brace −
<script type="text/javascript">
var x = 1;
while (x < 20)
{
if (x == 5){
break; // breaks out of loop completely
}
x = x + 1;
[Link]( x + "<br />");
}
</script>
30
JavaScript
Output
1
2
3
4
5
The continue Statement
The continue statement tells the interpreter to immediately start the next iteration of the loop
and skip the remaining code block. When a continuestatement is encountered, the program
flow moves to the loop check expression immediately and if the condition remains true, then it
starts the next iteration, otherwise the control comes out of the loop.
Example
This example illustrates the use of a continue statement with a while loop. Notice how
the continue statement is used to skip printing when the index held in variable x reaches 5 −
<script type="text/javascript">
var x = 1;
while (x < 10)
{
x = x + 1;
if (x == 5){
continue; // skip rest of the loop body
}
[Link]( x + "<br />");
}
</script>
Output
Entering the loop
2
3
4
6
7
8
9
10
31
JavaScript
What is an Event ?
JavaScript's interaction with HTML is handled through events that occur when the user
or the browser manipulates a page.
When the page loads, it is called an event. When the user clicks a button, that click too
is an event. Other examples include events like pressing any key, closing a window,
resizing a window, etc.
Developers can use these events to execute JavaScript coded responses, which cause
buttons to close windows, messages to be displayed to users, data to be validated, and
virtually any other type of response imaginable.
Events are a part of the Document Object Model (DOM) Level 3 and every HTML
element contains a set of events which can trigger JavaScript Code.
Here we will see a few examples to understand a relation between Event and JavaScript –
Example
Try the following example.
32
JavaScript
<html>
<head>
<script type="text/javascript">
function sayHello()
{
alert("Hello World")
}
</script>
</head>
<body>
<p>Click the following button and see result</p>
<form>
<input type="button" value="Say Hello" />
</form>
</body>
</html>
Example
The following example shows how to use onsubmit. Here we are calling a validate() function
before submitting a form data to the webserver. If validate() function returns true, the form
will be submitted, otherwise it will not submit the data.
<html>
<head>
33
JavaScript
<script type="text/javascript">
function validation()
{
</head>
<body>
</body>
</html>
<html>
<head>
<script type="text/javascript">
function over()
{
[Link] ("Mouse Over");
}
function out()
{
[Link] ("Mouse Out");
}
</script>
34
JavaScript
</head>
<body>
<p>Bring your mouse inside the division to see the result:</p>
</body>
</html>
Nonetheless, an alert box can still be used for friendlier messages. Alert box gives only one
button "OK" to select and proceed.
Example
<html>
<head>
<script type="text/javascript">
<!--
function Warn()
{
alert ("This is a warning message!");
}
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
35
JavaScript
<form>
<input type="button" value="Click Me" />
</form>
</body>
</html>
Output
If the user clicks on the OK button, the window method confirm() will return true. If the user
clicks on the Cancel button, then confirm() returns false. You can use a confirmation dialog box
as follows.
Example
<html>
<head>
<script type="text/javascript">
function getConfirmation()
{
36
JavaScript
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type="button" value="Click Me" />
</form>
</body>
</html>
Output
37
JavaScript
The prompt dialog box is very useful when you want to pop-up a text box to get user input.
Thus, it enables you to interact with the user. The user needs to fill in the field and then click
OK.
This dialog box is displayed using a method called prompt() which takes two parameters: (i) a
label which you want to display in the text box and (ii) a default string to display in the text
box.
This dialog box has two buttons: OK and Cancel. If the user clicks the OK button, the window
method prompt() will return the entered value from the text box. If the user clicks the Cancel
button, the window method prompt()returns null.
Example
The following example shows how to use a prompt dialog box −
<html>
<head>
<script type="text/javascript">
<!--
function getValue()
{
var retVal = prompt("Enter your name : ", "your name here");
[Link]("You have entered : " + retVal);
}
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type="button" value="Click Me" />
</form>
</body>
</html>
38
JavaScript
Output
39
JavaScript
Syntax Errors
Syntax errors, also called parsing errors, occur at compile time in traditional programming
languages and at interpret time in JavaScript
Runtime Errors
Runtime errors, also called exceptions, occur during execution (after
compilation/interpretation).
Logical Errors
Logic errors can be the most difficult type of errors to track down. These errors are not the
result of a syntax or runtime error. Instead, they occur when you make a mistake in the logic
that drives your script and you do not get the result you expected.
Exception Handling
The latest versions of JavaScript added exception handling capabilities. JavaScript implements the try...catch...finally
construct as well as the throw operator to handle exceptions.
You can catch programmer-generated and runtime exceptions, but you cannot catch
JavaScript syntax errors.
Here is the try...catch...finally block syntax –
try
// Code to run
40
JavaScript
}
catch ( e )
{
}
finally
{
// Code that is always executed regardless of
// an exception occurring
}
</script>
JavaScript querySelector
The querySelector is a JavaScript method that plays a vital role in the searching of elements. In this
section, we will understand and discuss the querySelector () method, its use and also look over an
example to understand the concept of the querySelector () method practically.
Syntax
The querySelector () method is a method of document interface and so it has such syntax. It has one
parameter, 'selectors', which is a DOM string and has one or more valid CSS selectors.
Return Type It may return 'null' if no match is found, and if the first element matches the specified CSS
selectors (if any), it will return that element. However, if there is not any valid CSS selector, it will throw a
'Syntax Error' exception.
41
JavaScript
So, we will now implement an example under which we will cover a CSS selector and retain its first
element value by using the querySelector () method.
Code Explanation
42
JavaScript
Let's also see and use the same example for other CSS selectors also. Just replace the element selector
code with these selector codes described below:
Class Selector
We need to use the (.) operator with the class name for finding the class first element. In the output, you
will see that the querySelector () searches from the starting of the code and the search get completed on
the h1 class element and so its return has a specified value as you can see below:
ID Selector
Attribute Selector
43
JavaScript
The output of the above code will be 'null' because, in our code, we have not used any such attribute as
shown below:
So, there are various CSS selectors and can be used if one has complete knowledge and understanding of
the CSS selectors and its types.
The querySelector () method of JavaScript is used for selecting only the first element from the code. But
what in case we want to retain more than one CSS selector value from the code. So, for such a case, we
use another method of the Document interface, which is known as the querySelectorAll () method. The
querySelectorAll () method is a method that is used to return all the matching values of the specified CSS
selector or group of a CSS selector.
Syntax
In the syntax, it contains selectors as an argument which holds one or more selectors with which we may
match the values.
Return
If the matching list or selector is found, it will return the specified value of those. Else it will return
an empty nodeList if no match is found.
Also, in case the specified CSS selectors have CSS pseudo-element, it will return an empty list.
Syntax Error
If there is a syntax error, it will return a syntax error exception that the specified selector's string is not
valid.
Example
Below is the same example we have used for explaining the querySelector () method, let's look at the
same example to understand the difference between both the methods:
44
JavaScript
Now, you can see the difference between the code that in the first example, we used the querySelector ()
method and it outputted only the first matching selector value. But, when you observe the output of this
second example, you will see that it has returned all the matching values of the specified selectors or
group of selectors. The output of the above code is shown below:
Code Explanation
45
JavaScript
() method for various selectors, and the method will find the match and will return atleast one matching
value of the specified element.
DOM Manipulation
In the example above, we changed the content of the headerElement to New Header Text. This is a simple
yet powerful way to update the text within an element.
46
JavaScript
Console in JavaScript
The console object is a useful tool for logging, debugging, and interacting with the browser's developer
tools (DevTools). It provides methods for outputting messages, measuring performance, and inspecting
values, which helps developers during the development process.
Here are detailed explanations of some commonly used methods within the console object:
1. [Link]()
The most commonly used method, [Link](), outputs general information, variables, or objects to the
console.
Usage: Display any message or value, like strings, numbers, arrays, or objects.
Example:
[Link]("Hello, world!"); // Outputs: Hello, world!
let name = "Alice";
[Link](name); // Outputs: Alice
// Logging multiple values
let age = 25;
[Link]("Name:", name, "Age:", age); // Outputs: Name: Alice Age: 25
47
JavaScript
2. [Link]()
The [Link]() method is used to output error messages. It usually highlights the error in the console
with a red color (depending on the browser), making it stand out.
Usage: Display error messages to the console for better visibility.
Example:
[Link]("This is an error message!"); // Outputs a red error message
3. [Link]()
The [Link]() method is used to output warning messages. Warnings are usually displayed in yellow
or orange in the DevTools console, making them stand out as less severe than errors but still important.
Usage: Display warning messages, often used for potential issues that should be looked into but aren't
errors.
Example:
[Link]("This is a warning!"); // Outputs a yellow warning message
4. [Link]()
The [Link]() method is similar to [Link](), but it is generally used for informational messages. It
provides the same output as [Link]() but can be used semantically to signify that the message is
meant to inform rather than just log general output.
Usage: Display informational messages, often for status updates or additional context.
Example:
[Link]("This is an info message."); // Outputs the message as informational
[Link]()
The [Link]() method displays tabular data in a neat, formatted table in the console. It's particularly
useful when logging arrays or objects with multiple properties.
Usage: Log arrays or objects in a table format for better readability.
Example:
48
JavaScript
7. [Link]()
The [Link]() method logs the number of times it has been called with the same label. It can be
used for counting function calls or occurrences of certain events.
Usage: Track how many times a particular point in the code has been reached.
Example:
[Link]("Function Call");
[Link]("Function Call");
[Link]("Function Call");
Output: Function Call: 1
Function Call: 2
Function Call: 3
8. [Link]() and [Link]()
[Link]() and [Link]() are used to measure how long a piece of code takes to execute. You
can give them a label to identify multiple timers.
Usage: Measure execution time of a particular block of code.
Example:
49
JavaScript
[Link]("Timer1");
for (let i = 0; i < 1000000; i++) {} // Some heavy operation
[Link]("Timer1"); // Outputs: Timer1: <time>ms
Output:
Timer1: 12.34ms
9. [Link]()
The [Link]() method is used to log an error message if the given expression evaluates to false. If
the expression is true, nothing is logged.
Usage: Perform assertions to check conditions in your code, and only log messages if the condition fails.
Example:
let number = 5;
[Link](number > 10, "Number is not greater than 10");
// This will print: Assertion failed: Number is not greater than 10
[Link](number < 10, "Number is less than 10");
// This will not log anything because the assertion is true.
10. [Link]()
The [Link]() method outputs a stack trace to the console, which shows the call path that led to the
point where the trace was called.
Usage: Get a stack trace to trace function calls and find where an issue originated.
Example:
function level1() {
level2();
}
function level2() {
level3();
}
function level3() {
[Link](); // Outputs stack trace
}
level1();
Output:
Trace
at level3 ([Link])
at level2 ([Link])
at level1 ([Link])
at <anonymous> ([Link])
11. [Link]()
50
JavaScript
[Link] [Link]() method displays an interactive list of the properties of a specified JavaScript object.
It's particularly useful when you want to inspect an object in a more structured way than with
[Link]().
Usage: Explore the properties of an object, including non-enumerable ones.
Example:
const person = { name: "Alice", age: 25, greet() { [Link]("Hello"); } };
[Link](person); // Shows all properties of the person object
In Regular Functions: The value of this is determined by how the function is called. It can refer to
the global object, the object calling the function, or be explicitly bound using call(), apply(), or
bind().
In Arrow Functions: Arrow functions do not have their own this context. Instead, they inherit this
from the enclosing lexical scope (the context where the function is created).
51
JavaScript
Here, in the ArrowFunction, this correctly refers to the instance of ArrowFunction because arrow
functions inherit this from their surrounding scope.
Arrow Functions with Methods (Objects)
Arrow functions are often used in objects, but there is a caveat when using them for object methods:
since arrow functions don’t have their own this, they can't be used as methods that refer to the object's
own properties.
Example with Regular Method:
const person = {
name: "Alice",
greet() {
[Link](`Hello, my name is ${[Link]}`);
}
};
[Link](); // Outputs: Hello, my name is Alice
Intervals in JavaScript
In JavaScript, intervals are used to repeatedly execute a function at specified time intervals. The most
common way to work with intervals is through the setInterval() method, which is part of the Web API.
1. setInterval()
The setInterval() method is used to execute a specified function repeatedly, with a fixed time delay
between each call.
Syntax:
const intervalId = setInterval(callback, delay, ...args);
callback: The function to be executed.
delay: The time, in milliseconds, to wait between each execution of the function (1000ms = 1
second).
...args (optional): Arguments to pass to the callback function when it is called.
52
JavaScript
In this example, the counter will be printed every second and incremented by 1 each time.
[Link] Considerations
1. Minimum Delay:
Browsers often have a minimum delay of around 4ms for setInterval(), even if you specify a smaller
value. This is done to prevent excessive CPU usage.
If the interval delay is very small (like 1 or 2ms), you might not get the expected precision.
If the callback function takes longer to execute than the interval delay, the next execution will be
delayed, causing drift.
For example, if the function takes 1 second to execute but you set the interval to 1 second, the
function will actually execute every 2 seconds.
53
JavaScript
3. Timer Accuracy:
setInterval() is not always 100% accurate. It depends on various factors like the system's
performance and whether the browser is busy doing other tasks.
Updating UI elements: You can use setInterval() to update certain elements on the page at regular
intervals, such as updating a clock or displaying live data.
setInterval(() => {
[Link]("clock").textContent = new Date().toLocaleTimeString();
}, 1000); // Updates the time every 1 second
Animation Loops: In animations, you can use setInterval() to move elements or change their properties at
regular intervals.
Polling data: You might use setInterval() to repeatedly check for new data from an API at regular
intervals.
setInterval(() => {
fetch("/api/data")
.then(response => [Link]())
.then(data => [Link](data));
}, 5000); // Polls for new data every 5 seconds
54
JavaScript
Persistent storage: Data stored in Local Storage remains even after the browser or tab is closed
and reopened.
Storage capacity: Typically, Local Storage allows around 5MB of data to be stored, but this can
vary by browser.
Key-Value pairs: Local Storage stores data as key-value pairs, both of which are strings.
No expiration: Data in Local Storage does not expire unless it is explicitly removed, unlike cookies,
which have expiration dates.
[Link]('username', 'Alice');
Example: Store a number (converted to string) [Link]('age', '25');
Example: Store an object (converted to string using [Link]())
const user = { name: 'Alice', age: 25 };
[Link]('user', [Link](user));
[Link] Data
To retrieve data, you use [Link](), which accepts the key and returns the value associated
with that key.
Syntax:
Example: Retrieve the stored usernamelet username = [Link]('username');
[Link](username); // Outputs: "Alice"
[Link] Data
You can remove specific items from Local Storage using [Link]().
Syntax:
[Link](key);
55
JavaScript
To remove all data stored in Local Storage, you can use [Link](). This will clear everything,
including all keys and values.
Syntax:
[Link]();
Example: Clear all data in Local Storage
[Link]();
Checking if Data Exists
To check if a key exists in Local Storage, you can use [Link](). If the item does not exist, it
will return null.
Example
let data = [Link]('nonexistentKey');
if (data === null) {
[Link]('Item not found.');
} else {
[Link]('Item found:', data);
}
[Link] Size: Most browsers limit Local Storage to around 5MB per domain.
[Link]-only Storage: Local Storage can only store strings. Non-string data (like arrays or objects) must be
serialized (using [Link]()) before storing and deserialized (using [Link]()) when retrieving.
[Link] Expiry Mechanism: Data in Local Storage does not have an expiration time, meaning you must
explicitly remove it when it's no longer needed
Security Considerations
Sensitive Data: Local Storage is accessible from JavaScript running on the same domain. This
makes it vulnerable to cross-site scripting (XSS) attacks. Avoid storing sensitive data like
passwords or tokens directly in Local Storage.
Limited security: Data stored in Local Storage is not encrypted, so any sensitive information stored
can be accessed by anyone who can view the browser’s storage (through Developer Tools).
Local Storage:
o Data persists even after the browser is closed.
o Data is available for the entire session and across tabs/windows for the same origin.
Session Storage:
o Data only persists for the duration of the page session (until the tab is closed).
o Data is isolated to the specific tab/window in which it was created.
56