[Go to site: main page, start]

0% found this document useful (0 votes)
10 views29 pages

JavaScript Basics: Syntax and Functions

This document provides an overview of JavaScript, including its history, structure, and key components such as variables, functions, operators, conditional statements, and loops. It explains how to add JavaScript to web pages, declare variables, define functions, and utilize various operators and control structures through examples. Additionally, it covers arrays and their properties, emphasizing JavaScript's dynamic nature and versatility as a scripting language.

Uploaded by

06anushri
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views29 pages

JavaScript Basics: Syntax and Functions

This document provides an overview of JavaScript, including its history, structure, and key components such as variables, functions, operators, conditional statements, and loops. It explains how to add JavaScript to web pages, declare variables, define functions, and utilize various operators and control structures through examples. Additionally, it covers arrays and their properties, emphasizing JavaScript's dynamic nature and versatility as a scripting language.

Uploaded by

06anushri
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Unit – IV

JavaScript
4.1 Introduction
 JavaScript was developed by Brendan Eich in 1995. The language was initially called
LiveScript and was later renamed JavaScript.
 The official name of the standard language is ECMAScript (European Computer
Manufacturers Association).
 JavaScript can be divided into three parts: the core, client side, and server side
 The core is the heart of the language, including its operators, expressions,
statements, and subprograms.
 Client-side JavaScript is a collection of objects that support the control of a
browser and interactions with users.
 Server-side JavaScript is a collection of objects that make the language useful on a
Web server. Server-side JavaScript is used far less frequently than client-side
JavaScript.
 JavaScript is a Scripting language . It is a light-weighted and interpreted language and
it is a case- sensitive language.

4.2 How to Add a Script to Your Pages


 JavaScript can either be embedded in a page or placed in an external script file (rather
like CSS).
 You add scripts to your page inside the <script> element. The type attribute on the
opening <script> tag indicates what scripting language will be found inside the element,
so for JavaScript you use the value text/JavaScript .
Syntax :
<script type=”text/javascript”>
[Link](“content”);
</script>

In the above syntax ,


 The script tag specifies that we are using JavaScript.
 The text/javascript is the content type that provides information to the browser
about
the data.
 The [Link]() function is used to display dynamic content through
JavaScript.
 The write() method to add a new line of text into the web page (and the web page
is represented using the document object).

 The <noscript> tag in HTML is used to display the text for those browsers which does
not support script tag or the browsers disable the script by the user.
Syntax : <noscript> content</noscript>
1
Program 1 :Displaying a Line of Text in a Web Page (Embedded in HTML)
<html>
<head>
<title> JavaScript Example </title>
</head>
<body>
<script>
[Link]("Welcome to JavaScript Programming")
</script>
</body>
</html>

Program 2 : Displaying a Line of Text in a Web Page (External JavaScript)

An external JavaScript file must be saved by .js extension. It is recommended to embed all
JavaScript files into a single file. It increases the speed of the webpage.

[Link]
[Link]("Welcome to JavaScript Programming")
[Link]

<html>
<head>
<title> JavaScript Example </title>
</head>
<body>
<script src=”[Link]”>
</script>
</body>
</html>

4.3 Variable
 A variable is used to store some information. JavaScript includes variables which hold the
data value and it can be changed anytime.
 JavaScript uses reserved keyword var (or) let to declare a variable. A variable must have
a unique name. You can assign a value to a variable using equal to (=) operator when you
declare it or before using it.
2
Syntax:
var variablename; // Variable Declaration

var variablename=value; //Variable Declaration & Initialization

Example:
var a = 1; // variable “a” stores numeric value
var c = ”Bhavans”; //variable “c” stores string value
var b; // declared variable without assigning a value
If no value is given to variable, then its value is undefined .

Example Program on Variable

<html>
<head>
<title>variable</title>
</head>
<body>
<script>
var a=20;
[Link]("a value is "+a+"<br>");
var b=40.2;
[Link]("b value is "+b+"<br>");
var st="Hello Bhavans";
[Link]("<br> string value is "+st);
[Link]("<br> Boolean value is "+(60>5));
var z;
[Link]("<br> z value is "+z);
</script>
</body>
</html>

4.4 Functions
 JavaScript provides functions similar to most of the scripting and programming
languages.
 In JavaScript, a function allows you to define a block of code, give it a name and then
execute it as many times as you want.
 A JavaScript function can be defined using function keyword.
3
//defining a function
function function_name( args )
{
// code to be executed
}

//calling a function
function_name(args);

Example Program on Functions


<html>
<head>
<title>Functions in JS</title>
<script>
function display()
{
[Link]("Functions in javascript");
}
display();
</script>
</head>
</html>

The Return Statement


Return statement is used to return a value or a result. This statement is used to specify the
value that is returned when a function is called.

<html>
<head>
<title>Return Statement</title>
<script>
function calculateArea(width,height)
{
area=width*height;
return area;
}
[Link]("area of Rectangle "+calculateArea(10,20));
</script>
</head>
</html>

4
4.5 Operators
An operator performs some operation on single or multiple operands (data value) and
produces a result.

For example 1 + 2, where + sign is an operator and 1 is left operand and 2 is right operand.
+ operator adds two numeric values and produces a result which is 3 in this case.

JavaScript includes following categories of operators.


1. Arithmetic Operators
2. Assignment Operators
3. Comparison Operators
4. Logical Operators
5. String Operators
6. Conditional Operator
4.5.1 Arithmetic Operators
Arithmetic operators perform arithmetic operations upon operands

<html>
<head>
<title>Arithmetic Operator</title>
</head>
<body>
<script>
var a=12,b=3
[Link]("Addition of a & b : "+(a+b))
[Link]("<br>Subtraction of a & b : "+(a-b))
[Link]("<br>Multiplication of a & b : "+(a*b))
[Link]("<br>Division of a & b : "+(a/b))
[Link]("<br>Modulo of a & b : "+(a%b))
</script>
</body>
</html>

5
4.5.2 Assignment Operators
The assignment operators are the operators used to assign the right-hand side value to
the left-hand side variable.

<html>
<head>
<title>Assignment Operator</title>
</head>
<body>
<script>
var a=12,b=3
[Link]("a+=b : "+(a+=b))
[Link]("<br>a-=b : "+(a-=b))
[Link]("<br>a*=b : "+(a*=b))
[Link]("<br>a/=b : "+(a/=b))
[Link]("<br>a%=b : "+(a%=b))
</script>
</body>
</html>

4.5.3 Comparison Operators


comparison operators compare two operands and then return either true or false based on
whether the comparison is true or not.

6
<html>
<head>
<title>Comparison Operator</title>
</head>
<body>
<script>
var x=12,y=3
[Link]("x==y : "+(x==y))
[Link]("<br>x!=y : "+(x!=y))
[Link]("<br>x>y : "+ (x>y))
[Link]("<br>x>=y : "+(x>=y))
[Link]("<br>x<=y : "+(x<=y))
[Link]("<br>x &lt y : "+ (x<y))
</script>
</body>
</html>

4.5.4 Logical Operators


Logical or Boolean operators return one of two values: true or false . They are particularly
helpful when you want to evaluate more than one expression at a time.

<html>
<head>
<title>Logical Operator</title>
</head>
<body>
<script>
var x=12,y=3, z=10
[Link]("Logical and : "+(x>y && x>z))
[Link]("<br> Logical OR : "+(x>y || x>z))
[Link]("<br> Logical Not : "+ !(x>y))
</script>
</body>
</html>

7
4.5.5 String Operator (Using + with Strings)
The process of adding two strings together is known as concatenation. You can also add text to
strings using the + operator.

<html>
<head>
<title>String Operators</title>
</head>
<body>
<script>
var a="Hello";
var b="world",c;
c=a+b;
[Link]("String Concatenation : "+c);
</script>
</body>
</html>

4.5.6 Conditional Operator / Ternary Operator


A ternary operator evaluates a condition and executes a block of code based on the
condition.

Syntax :
condition ? expression1 : expression2

<html>
<head>
<title>Conditional Operators</title>
</head>
<body>
<script>
var age=20
var result = (age>18) ?'Elgible':'Not elgibe';
[Link](result+" to Vote");
</script>
</body>
</html>

8
4.6 Conditional Statements
Conditional statements allow you to take different actions depending upon different
statements. There are three types of conditional statements
4.6.1 if Statement
if statements allow code to be executed when the condition is true.

Syntax:
if (condition)
{
code to be executed if condition is true
}
Example Program on if Statement

<html>
<head>
<title>if statement</title>
</head>
<body>
<script>
var age=18;
if(age>=18)
{
[Link]("Eligible to vote");
}
</script>
</body>
</html>

4.6.2 if..else Statement


if statements allow code to be executed when the condition is true, else statements
allow to executed when condition is false.

Syntax:
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is false
}

9
Example Program on if..else Statement

<html>
<head>
<title>if..else statement</title>
</head>
<body>
<script>
var age=15;
if(age>=18)
{
[Link]("Eligible to vote");
}
else
{
[Link]("Not eligible to vote");
}
</script>
</body>
</html>

4.6.3 nested if Statement


Writing an if statement inside another if-statement is called nested if statement.

Syntax:
if(condition_1)
{
if(condition_2)
{
inner if-block of statements;
...
}
...
}

Example Program on nested if Statement

<html>
<head>
<title>Nested if </title>
</head>
<body>
<script>
var x=10,y=20
if(x>5)
if(y>5)
[Link]("x and y are > 5 ")

10
else
[Link]("x is <= 5")
</script>
</body>
</html>

4.6.4 switch Statement


The switch is a conditional statement like if statement. Switch is useful when you want
to execute one of the multiple code blocks based on the return value of a specified
expression.

Syntax:
switch (expression)
{
case option1:
// statement (s)
case option2:
// statement (s)
...
default:
// statement (s)
}

Example Program on switch Statement


<html>
<head>
<title>Switch Case</title>
</head>
<body>
<script>
var a=2;
switch(a)
{
case 1: [Link]("Case 1 Executed");
break;
case 2: [Link]("Case 2 Executed");
break;
case 3: [Link]("Case 3 Executed");
break;
default:[Link]("default case Executed");
}
</script>
</body>
</html>

11
4.7 Looping / Iterative / Repetition Statements
Looping statements are used to execute the same block of code a specified number of
times.
4.7.1 while Statement
In a while loop, a code block is executed if a condition is true and for as long as that
condition remains true
Syntax:
while (condition)
{
// Statements;
}

Example Program on while Statement

<html>
<head>
<title>while Loop</title>
</head>
<body>
<script>
var i=1;
while(i<=5)
{
[Link]("Hello<br>");
i++;
}
</script>
</body>
</html>

4.7.2 do- while Statement


The do-while loop is similar to while loop the only difference is it evaluates condition expression
after the execution of code block. So do-while loop will execute the code block at least once.
Syntax:
do
{
// Statements;
} while (condition)

12
Example Program on do..while Statement

<html>
<head>
<title>while Loop</title>
</head>
<body>
<script>
var i=1;
do
{
[Link]("<br>i="+i);
i++;
}
while(i<=5)
</script>
</body>
</html>

4.7.3 for Statement


for loop to execute code repeatedly

Syntax:
for(initializer; condition; iteration)
{
// Code to be executed
}

Example Program on for Statement

<html>
<head>
<title>for Loop</title>
</head>
<body>
<script>
var i
for(i=0;i<10;i++)
{
[Link]("<br>i="+i);
}
</script>
</body>
</html>

13
4.8 Arrays
An array is a special type of variable, which can store multiple values using special
syntax. Every value is associated with numeric index starting with 0. JavaScript arrays have
dynamic lengths.
4.8.1 Declaring and Allocating Arrays :-
An array in JavaScript can be defined and initialized in two ways, Array literal
and Array constructor syntax.
Array Literal
Array literal syntax is simple. It takes a list of values separated by a comma and
enclosed in square brackets.
Syntax:
Syntax: var <array-name> = [element0,element1,element2,..elementN];
Example :
var stringArray = ["one", "two", "three"];
var numericArray = [1, 2, 3, 4];
var decimalArray = [1.1, 1.2, 1.3];
var booleanArray = [true, false, false, true];
var mixedArray = [1, "two", "three", 4];

Note :- JavaScript array can store multiple element of different data types. It is not
required to store value of same data type in an array.
Array Constructor
We can initialize an array with Array constructor syntax using new keyword.
The Array constructor has following three forms.
Syntax:
var arrayName = new Array();
var arrayName = new Array(Number length);
var arrayName = new Array(element1, element2,... elementN);

4.8.2 Array Properties

Array includes "length" property which returns number of elements in the array.
Use for loop to access all the elements of an array using length property.
Example Program on Array Literal
<html>
<head>
<title>JavaScript Arrays</title>
</head>
<body>
<script>
var arr=[10,20,30,40,50];
14
for (var i=0;i<[Link];i++)
{
[Link](arr[i] + "<br>");
}
</script>
</body>
</html>

4.9 DOM Methods


 The Document Object Model (DOM) is the data representation of the objects that
comprise the structure and content of a document on the web.
 The following methods are used to get an element or a set of elements based on
their type, properties, property values, or their position on the screen relative to the
viewport.

4.9.1 getElementById

The getElementById is a basic method of DOM manipulation. It allows us to select and


access a specific HTML element by its unique identifier (id).
The innerHTML property is used to get or set the HTML content inside an element , It can
insert text, HTML tags, or both inside an element.

Syntax :
[Link](elementID)

Example Program:

<html>
<head>
<title>getElementById Example</title>
</head>
<body>
<h2 id="id1">Hello DOM</h2>
<script>
[Link]("id1").innerHTML = "Welcome";
</script>
</body>
</html>

15
4.9.2 getElementsByClassName

The getElementsByClassName method, we use to retrieve a collection of elements based


on their class name. It's useful for applying changes to multiple elements that share a
common class.
Syntax :
[Link](classname)
Example Program:
<html>
<head>
<title>getElementByClass Example</title>
</head>
<body>
<p class="c1">Santhosh</p>
<p class="c1">Bhavans</p>
<script>
var items = [Link]("c1");
items[0].[Link] = "blue";
items[1].[Link] = "green";
</script>
</body>
</html>

4.9.3 getElementsByTagName

With getElementsByTagName, we can select elements based on their tag name. This
method is handy when dealing with a group of elements of the same type.
Syntax :
[Link](tagname)
Example Program:
<html>
<head>
<title>getElementByTag Example</title>
</head>
<body>
<p>Santhosh</p>
<p>Bhavans</p>
<script>
var items = [Link]("p");
items[0].[Link] = "bold";

16
items[1].[Link] = "green";
</script>
</body>
</html>

4.9.4 querySelector

The querySelector() method is used to select the first element in the document that
matches a given CSS selector.
Syntax :
[Link](selectors);
Example Program:

<html>
<head>
<title>querySelector Example</title>
</head>
<body>
<p class="c1">First Note</p>
<p class="c1">Second Note</p>
<script>
[Link](".c1").innerHTML = "Updated First Note";
</script>
</body>
</html>

4.9.5 querySelectorAll

The querySelectorAll() method returns all elements in the document that match the
given CSS selector(s).
Syntax :

[Link](selectors);

Example Program:
<html>
<head>
<title>querySelectorAll Example</title>
</head>
<body>
<p class="c1">Bhavans</p>
17
<p class="c1">College</p>
<script>
var items = [Link](".c1");
items[0].[Link] = "yellow";
items[1].[Link] = "lightgreen";
</script>
</body>
</html>

4. 10 String
 A string is a series of characters treated as a single unit. A string may include letters,
digits and various special characters, such as +, -, *, /, and $.
 The JavaScript String object is a global object that is used to store strings.

String Properties

Property Description

length Returns the length of a string.

String Methods

The following table lists the standard methods of the String object.

Method Description
charAt() Returns the character at the specified index.

charCodeAt() Returns the Unicode of the character at the specified index.

concat() Joins two or more strings, and returns a new string.

endsWith() Checks whether a string ends with a specified substring.

fromCharCode() Converts Unicode values to characters.

includes() Checks whether a string contains the specified substring.

Returns the index of the first occurrence of the specified


indexOf()
value in a string.

18
Returns the index of the last occurrence of the specified
lastIndexOf()
value in a string.

localeCompare() Compares two strings in the current locale.

Matches a string against a regular expression, and returns


match()
an array of all matches.

Returns a new string which contains the specified number


repeat()
of copies of the original string.

Replaces the occurrences of a string or pattern inside a


replace() string with another string, and return a new string without
modifying the original string.

Searches a string against a regular expression, and returns


search()
the index of the first match.

slice() Extracts a portion of a string and returns it as a new string.

split() Splits a string into an array of substrings.

startsWith() Checks whether a string begins with a specified substring.

Extracts the part of a string between the start index and a


substr()
number of characters after it.

Extracts the part of a string between the start and end


substring()
indexes.

toLocaleLowerCase Converts a string to lowercase letters, according to host


() machine's current locale.

toLocaleUpperCas Converts a string to uppercase letters, according to host


e() machine's current locale.

toLowerCase() Converts a string to lowercase letters.

toString() Returns a string representing the specified object.

toUpperCase() Converts a string to uppercase letters.

trim() Removes whitespace from both ends of a string.

valueOf() Returns the primitive value of a String object.

19
Example Program :
<html>
<head>
<title>String Objects</title>
</head>
<body>
<script>
var st="Bhavans Degree College";
[Link]("Length of the String is : "+[Link]);
[Link]("<br> charcater index is : "+[Link](0));
[Link]("<br> Ascii value of the index is : " +
[Link](2));
[Link]("<br> index of the character : " + [Link]("e"));
[Link]("<br> index of the character : " +
[Link]("e"));
[Link]("<br> lowercase : " + [Link]());
[Link]("<br> uppercase : " + [Link]());
[Link]("<br> font color: " + [Link]('red'));
[Link]("<br> font size: " + [Link](20));
</script>
</body>
</html>

4.11 JavaScript Closures (Local and Global Variable)


Scope in JavaScript defines accessibility of variables, objects and functions.
There are two types of scope in JavaScript.
1. Global scope
2. Local scope

Global Scope
Variables declared outside of any function become global variables. Global variables can be
accessed and modified from any function.
Local Scope
Variables declared inside any function with var or let keyword are called local variables. Local
variables cannot be accessed or modified outside the function declaration

20
<html>
<head>
<title>Scope & Global Variables </title>
<script>
var x=1;
function start()
{
var y=5;
[Link]("Local Variable y value :"+y);
A();
}
function A()
{
[Link]("<br>Global Variable x value :"+x);
}
</script>
</head>
<body ></body>
</html>
4.12 JSON
 In JavaScript, JSON (JavaScript Object Notation) is a lightweight data-interchange format
that's easy for humans to read and write and easy for machines to parse and generate.
 It’s commonly used to exchange data between a web server and a client, or to store data
in a structured format.
Syntax :
{
“key1” : “value1”,
“key2” : “value2”,
…. ,
“keyn” : “valuen”,
}
JSON Syntax rules :

 Data has to be in key/value pairs, separated by a colon ( : ).


 Data pairs have to be separated by a comma(,).
 In data pairs, the key needs to be a unique double-quoted string.
 The value can be any primitive data type but never a function.
 Objects are written inside curly brackets ( { ).
 Arrays are written inside square brackets ( [ ).

21
JSON Functions in JavaScript
In order to convert object to string and string to object, JSON provides two functions.

 [Link]() – Used to convert JavaScript objects to JSON strings. It is used


to serialize a JavaScript object into JSON string.
 [Link]() – As the name suggests, we use this to parse the data that is received
as JSON. It is used to de-serialize JSON String to JavaScript objects.

Example program to convert JavaScript Objects to JSON String (using


stringify() )

<html>
<head>
<title>JSON Example</title>
</head>
<body>
<script>
var obj = {
"name": "Bhavans" ,
"sem" : 1
}
var x=[Link](obj)
[Link](x);
</script>
</body>
</html>
Example program to convert JSON String to JavaScript Objects
(using Parse())
<html>
<head>
<title>JSON Example</title>
</head>
<body>
<script>
var json = '{"name":"Bhavans", "sem":1}';
var obj = [Link](json);
[Link]([Link]);
[Link]("<br>")
[Link]([Link]);

</script>
</body
</html>

22
4.13 Event Handling
 The change in the state of an object is known as an Event. Events are essentially the
actions that occur on a web app due to user interaction, such as clicking a button.
 Functions that handle events are called event handlers. event handler which is a piece
of code that will execute to respond to that event.
 An event handler is also known as an event listener. It listens to the event and responds
accordingly to the event fires.
There are two types of events that can be used to trigger scripts:
• Window events, which occur when something happens to a window. For
example, a page loads or unloads or focus is being moved to or away from a window
or frame .
• User events, which occur when the user interacts with elements in the page
using a mouse (or other pointing device) or a keyboard, such as placing the mouse
over an element, clicking on an element, or moving the mouse off an element
A list of some events supported by both Firefox and Internet Explorer is given with Descriptions.
Event Purpose
Document has finished loading (if used in a frameset, all frames
onload
have finished loading).
onunload Document is unloaded, or removed, from a window or frameset.
Button on mouse (or other pointing device) has been clicked over
onclick
the element.
Button on mouse (or other pointing device) has been double -
ondblclick
clicked over the element.
Button on mouse (or other pointing device) has been depressed
onmousedown
(but not released) over the element.
Button on mouse (or other pointing device) has been released over
onmouseup
the element.
Cursor on mouse (or other pointing device) has been moved onto
onmouseover
the element.
Cursor on mouse (or other pointing device) has been moved while
onmousemove
over the element.
Cursor on mouse (or other pointing device) has been moved off
onmouseout
the element.
Event Purpose

onkeypress A key is pressed and released.

onkeydown A key is held down.

onkeyup A key is released.

23
onfocus Element receives focus either by mouse (or other pointing device)

onblur Element loses focus.

onsubmit A form is submitted

onreset A form is reset.

onselect User selects some text in a text field.


A control loses input focus and its value has been changed since
onchange
gaining focus.

Example program on functions and onclick event


<html>
<body>
<h2>Onclick Event Example</h2>
<script>
function showMessage()
{
alert("Button was clicked!");
}
</script>
<button Me</button>
</body>
</html>

24
Example program on functions and ondblclick event
<html>
<body>
<h2>Ondblclick Event Example</h2>
<script>
function showMessage()
{
alert("Button was clicked Double!");
}
</script>
<button Me</button>
</body>
</html>

Example program on onkeydown, onkeyup, onkeypress → Keyboard events

<!DOCTYPE html>
<html>
<body>
<h2>Keyboard Events</h2>
<script>
function keyDownEvent()
{
alert("Key is pressed down");
}
function keyUpEvent()
{
alert("Key is released");
}
</script>
<input type="text" ></body>
</html>

25
Example program on onload event
<!DOCTYPE html>
<html>
<body > <h2>Onload Event</h2>
<script>
function welcome()
{
alert("Page Loaded Successfully!");
}
</script>
</body>
</html>

26
onmouseover and onmouseout
 The onmouseover event triggers when the mouse pointer moves over an element.
 The onmouseout event that triggers when the mouse pointer moves out of an element.
Example program
<!DOCTYPE html>
<html>
<body>
<h2>Mouse Events Example</h2>
<div id="box" style="width:150px; height:100px;
background:lightblue;"

> >

Hover over me

</div>
</body>
</html>
onmouseover Output

onmouseout Output

27
Example program on onfocus and onblur
<!DOCTYPE html>
<html>
<body>
<h2>Focus & Blur Events</h2>
<input type="text"
> > </body>
</html>

Example program on onsubmit and onreset


 The onsubmit event is an event that occurs when you try to submit a form.
 The onreset event occurs when the reset button in a form is clicked.

<html>
<head>
<title>onsubmit and onblur</title>
<script>
function resetfun()
{
alert("The form was reset");
}
function submitfun()
{
alert("The form was submitted");
}
</script>
</head>
<body>
<form action="" > > Firstname: <input type="text" name="fname"><br>
28
Lastname: <input type="text" name="lname"><br>
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form>
</body>
</html>

Unit-IV Questions
1. Explain about conditional statements and looping statements
2. Write a short note on JSON
3. Explain about keyboard and mouse events
4. Explain about JavaScript closures (local and global variables)
5. What is JavaScript? Operators in JavaScript
6. Explain about Array and DOM Methods
7. Write a short note on strings
8. How to declare a variable in JavaScript and explain about
functions

29

Common questions

Powered by AI

JSON (JavaScript Object Notation) is widely used in JavaScript for exchanging data between a web server and a client due to its lightweight, easy-to-read format. In JavaScript, the `JSON.stringify()` method converts JavaScript objects into JSON strings, which can then be sent over a network or stored. Conversely, `JSON.parse()` converts JSON strings back into JavaScript objects for manipulation. For example, given a JavaScript object `var obj = { "name": "Bhavans", "sem": 1 }`, `JSON.stringify(obj)` will convert it to `'{"name":"Bhavans", "sem":1}'`. To convert the string back, you can use `JSON.parse(jsonString)`, resulting in an object equivalent to the original .

Mouse and keyboard events in JavaScript are key to creating interactive user interfaces by responding to user actions. Mouse events include `onclick`, `ondblclick`, `onmouseover`, and `onmouseout`, among others, each allowing the page to react to different mouse interactions like clicks or cursor movements. Keyboard events such as `onkeydown`, `onkeyup`, and `onkeypress` detect interactions with the keyboard, triggering actions on text input or key navigation. These events enable dynamic and responsive behavior in web pages, enhancing user experience by making interfaces more engaging and intuitive. They empower developers to build apps that are reactive, providing feedback and responses aligned with user actions .

JavaScript supports arrays defined using the array literal and the `Array` constructor. Arrays can hold elements of different data types, providing flexibility. Array literals (`var arr = [1, 2, 3]`) are concise and preferred for their simplicity and readability. Using the `Array` constructor (`var arr = new Array(1, 2, 3)`) can lead to errors, such as confusing array length initialization (e.g., `new Array(3)` creates an array with three empty slots due to treating `3` as size, not elements). Array literals are recommended for better maintainability and clarity, allowing cleaner code without ambiguity in constructor usage, unless dynamic array sizing or specific behavior of `Array` constructor is intended .

JavaScript uses conditional statements like `if`, `if-else`, and `switch` to control the flow of the program based on different conditions. The `switch` statement provides a more readable and organized way to handle complex conditional logic when multiple discrete potential values are evaluated against the same variable or expression. Instead of writing multiple `if-else` statements, which can become cumbersome and hard to read, a `switch` statement allows for cleaner, more modular code by grouping related cases together and offering a `default` case to handle any unspecified values. It enhances code maintainability and readability in scenarios with multiple discrete value checks on the same variable .

Events and event handlers are essential in JavaScript for managing user interactions in web applications. Events represent actions or occurrences that happen in the system, such as user clicks, key presses, or mouse movements. Event handlers, or listeners, are functions designed to execute in response to certain events. For example, `onclick` is triggered when a user clicks on an element, `onkeydown` is triggered when a keypress is detected, and `onload` fires when a document is fully loaded. These handlers allow developers to create interactive and dynamic experiences; for instance, `onclick` may change the content on the page, while `onmousemove` could dynamically display coordinates of a cursor .

The primary difference between `while` and `do-while` loops in JavaScript lies in when the termination condition is evaluated. In a `while` loop, the condition is evaluated before the code block is executed, meaning if the condition is initially false, the block will not execute at all. Conversely, a `do-while` loop evaluates the condition after executing the block, ensuring that the code block runs at least once regardless of the initial condition. Use a `while` loop when you need to iterate based on a condition that may not be true at the start. Use `do-while` when you need the block to execute at least once, such as prompting the user for input that must be processed before the next iteration .

JavaScript functions are similar to functions in many other programming languages, allowing code to be defined and named so it can be executed multiple times. However, a distinctive feature of JavaScript is its first-class treatment of functions; they can be assigned to variables, passed as arguments, and returned from other functions. Functions are defined using the `function` keyword followed by a name and a list of parameters enclosed in parentheses. The body of the function is enclosed in curly braces. Example: `function function_name(args) { // code }`. Functions can be called using `function_name(args);`. JavaScript also supports anonymous functions and arrow functions, offering more flexibility in functional programming approaches .

The ternary operator (`condition ? expression1 : expression2`) offers a concise method for simple conditional assignments and expressions. It is beneficial for cases where a single expression needs to be returned based on a condition, allowing for inline assignments and reducing the amount of code compared to `if-else` statements. For example, setting a variable based on a condition can be done in a single line with the ternary operator: `var result = (age > 18) ? 'Eligible' : 'Not eligible';`. However, `if-else` statements are more suitable for complex conditions requiring multiple lines or statements within each condition block for improved readability and structure .

In JavaScript, variable scope determines where a variable can be accessed or modified. Variables declared outside of any function are in the global scope and can be accessed from anywhere in the code. Variables declared inside a function using `var` or `let` have local scope and can only be accessed within that function. JavaScript also supports block scope limited to the block in which they are defined when using `let` and `const`. Understanding scope is crucial to avoid unintended side-effects in large programs, as global variables can be modified from anywhere, potentially leading to bugs .

Logical operators in JavaScript are used to combine multiple conditions or invert logical states, returning true or false as Boolean operators. They include AND (`&&`), OR (`||`), and NOT (`!`). These operators allow for complex conditionals by evaluating multiple expressions at once. Logical operators can be used to short-circuit evaluations: with `&&`, if the first condition is false, JavaScript doesn't evaluate the second one. Similarly, with `||`, if the first condition is true, the second one is ignored. This short-circuit logic can optimize condition checks in terms of performance, especially in cases where evaluating a condition is resource-intensive .

You might also like