[go: up one dir, main page]

0% found this document useful (0 votes)
115 views17 pages

Javascript Module-1

JavaScript is a client-side scripting language used to make web pages more interactive and dynamic. It can change HTML content and attributes, styles, and show/hide elements. JavaScript functions and events allow code to run when events like button clicks occur. JavaScript can display data by writing to HTML elements, using document.write(), alerts, or the browser console.

Uploaded by

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

Javascript Module-1

JavaScript is a client-side scripting language used to make web pages more interactive and dynamic. It can change HTML content and attributes, styles, and show/hide elements. JavaScript functions and events allow code to run when events like button clicks occur. JavaScript can display data by writing to HTML elements, using document.write(), alerts, or the browser console.

Uploaded by

Mudit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

JAVASCRIPT

JavaScript is a client-side, object-based scripting language that is used to handle and validate


client-side data. JavaScript is also used for making the user interface of the web pages more
dynamic making it responsive to events like the movement of the mouse, mouse click on a
certain HTML element, a button click, etc, using which we can improve the user experience.

 JavaScript is the world's most popular Web programming language. JavaScript was initially created to
“make web pages alive”. The programs in this language are called scripts. They can be written right in a web
page’s HTML and run automatically as the page loads.
 Scripts are provided and executed as plain text. They don’t need special preparation or compilation to run.
 Today, JavaScript can execute not only in the browser, but also on the server, or actually on any device that
has a special program called the JavaScript engine. The browser has an embedded engine sometimes
called a “JavaScript virtual machine”. Different engines have different “codenames”. For example: V8 – in
Chrome, Opera and Edge, SpiderMonkey – in Firefox , …There are other codenames like “Chakra” for IE,
“JavaScriptCore”, “Nitro” and “SquirrelFish” for Safari, etc.

 JavaScript is one of the 3 languages all web developers must learn:


1. HTML to define the content of web pages
2. CSS to specify the layout of web pages
3. JavaScript to program the behavior of web pages

Why is it called JavaScript?
 When JavaScript was created, it initially had another name: “LiveScript”. But Java was very popular at that
time, so it was decided that positioning a new language as a “younger brother” of Java would help.
 But as it evolved, JavaScript became a fully independent language with its own specification called
ECMAScript, and now it has no relation to Java at all.

What makes JavaScript unique?


There are at some great things about JavaScript:
 Full integration with HTML/CSS.
 Simple things are done simply.
 Supported by all major browsers and enabled by default.
 JavaScript is the only browser technology that combines these three things.
 That’s what makes JavaScript unique. That’s why it’s the most widespread tool for creating browser
interfaces.
 That said, JavaScript can be used to create servers, mobile applications, etc.

Code editors
 A code editor is the place where programmers spend most of their time. There are two main types of code
editors: IDEs and lightweight editors. Many people use one tool of each type.

 IDE : The term IDE (Integrated Development Environment) refers to a powerful editor with many features
that usually operates on a “whole project.” As the name suggests, it’s not just an editor, but a full-scale
“development environment.” An IDE loads the project (which can be many files), allows navigation between
files, provides autocompletion based on the whole project (not just the open file), and integrates with a
version management system (like git), a testing environment, and other “project-level” stuff. If you haven’t
selected an IDE yet, consider the following options:
Visual Studio Code (cross-platform, free).
WebStorm (cross-platform, paid).
For Windows, there’s also “Visual Studio”, not to be confused with “Visual Studio Code”. “Visual Studio” is a
paid and mighty Windows-only editor, well-suited for the .NET platform. It’s also good at JavaScript. There’s
also a free version Visual Studio Community. Many IDEs are paid, but have a trial period. Their cost is usually
negligible compared to a qualified developer’s salary, so just choose the best one for you.

 Lightweight editors : “Lightweight editors” are not as powerful as IDEs, but they’re fast, elegant and
simple. They are mainly used to open and edit a file instantly. The main difference between a “lightweight
editor” and an “IDE” is that an IDE works on a project-level, so it loads much more data on start, analyzes the
project structure if needed and so on. A lightweight editor is much faster if we need only one file. In practice,
lightweight editors may have a lot of plugins including directory-level syntax analyzers and autocompletes, so
there’s no strict border between a lightweight editor and an IDE.
There are many options, for instance:
Sublime Text (cross-platform, shareware).
Notepad++ (Windows, free).
Vim and Emacs are also cool if you know how to use them.

What JavaScript can do.


1. JavaScript Can Change HTML Content 2. JavaScript Can Change HTML Attribute
<html> Values
<body> <html>
<h2>What Can JavaScript Do?</h2> <body>
<p id="demo">JavaScript can change HTML <h2>What Can JavaScript Do?</h2>
content.</p> <p>JavaScript can change HTML attribute values.</p>
<button type="button" onclick = <p>In this case JavaScript changes the value of the src
'document.getElementById("demo").innerHTML = (source) attribute of an image.</p>
"Hello JavaScript!"'>Click Me!</button> <button onclick =
"document.getElementById('myImage').src='pic_bulbon.
</body> gif'"> Turn on the light </button>
</html> <img id="myImage" src="pic_bulboff.gif"
style="width:100px">
<button onclick =
"document.getElementById('myImage').src='pic_bulboff.
gif'">Turn off the light</button>
</body>
</html>
3. JavaScript Can Change HTML Styles 4. JavaScript Can Hide HTML Elements
(CSS) <html>
<html> <body>
<body> <h2>What Can JavaScript Do?</h2>
<h2>What Can JavaScript Do?</h2><p <p id="demo">JavaScript can hide HTML elements.</p>
id="demo">JavaScript can change the style of an <button type="button" onclick =
HTML element.</p> "document.getElementById('demo').style.display='none'"
<button type="button" onclick = > Click Me! </button>
"document.getElementById('demo').style.fontSize='35p </body></html>
x'">Click Me!</button>
</body>
</html>
5. JavaScript Can Show HTML Elements 6. JavaScript Functions and Events
<html> <html>
<body> <head>
<h2>What Can JavaScript Do?</h2> <script>
<p>JavaScript can show hidden HTML elements.</p> function myFunction() {
<p id="demo" style="display:none">Hello JavaScript! document.getElementById("demo").innerHTML =
</p> "Paragraph changed.";
<button type="button" onclick = }
"document.getElementById('demo').style.display='bloc </script>
k'">Click Me!</button> </head>
<body>
</body> <h2>Demo JavaScript in Head</h2>
</html> <p id="demo">A Paragraph.</p>
<button type="button" onclick="myFunction()">Try
it</button>
</body>
</html>

JavaScript Output
JavaScript Display Possibilities - JavaScript can "display" data in different ways:

 Writing into an HTML element, using innerHTML.

 Writing into the HTML output using document.write().

 Writing into an alert box, using window.alert().

 Writing into the browser console, using console.log().

 Using innerHTML : To access an HTML element, JavaScript  Using document.write() - For testing purposes, it is
can use the document.getElementById(id) method. convenient to use document.write():
The id attribute defines the HTML element. The innerHTML property defines <html>
the HTML content: <body>
<html> <h2>My First Web Page</h2>
<body> <p>My first paragraph.</p>
<h2>My First Web Page</h2> <p>Never call document.write after the document has finished loading
<p>My First Paragraph.</p> It will overwrite the whole document.</p>
<p id="demo"></p> <script>
<script> document.write(5 + 6);
document.getElementById("demo").innerHTML = 5 + 6; </script>
</script> </body>
</body> </html>
</html>

Example2: Using document.write() after an HTML


#Example2: document is loaded, will delete all existing HTML:
<html>
<html>
<body>
<body>
<h2>JavaScript Statements</h2>
<h2>My First Web Page</h2>
<p>JavaScript code blocks are written between { and }</p>
<p>My first paragraph.</p>
<button type="button" onclick="myFunction()">Click Me!</button>
<button type="button" onclick="document.write(5 + 6)">Try it</button>
<p id="demo1"></p>
</body>
<p id="demo2"></p>
</html>
<script>
function myFunction() {
document.getElementById("demo1").innerHTML = "Hello Dolly!";
document.getElementById("demo2").innerHTML = "How are you?";
}
</script>
</body>
</html>
 Using window.alert() - use an alert box to display data:  Using console.log() - For debugging purposes, you
<!DOCTYPE html> call the console.log() method in the browser to disp
<html>
data.
<body>
<html>
<h2>My First Web Page</h2>
<body>
<p>My first paragraph.</p>
<h2>Activate Debugging</h2>
<script>
<p>F12 on your keyboard will activate debugging.</p>
window.alert(5 + 6);
<p>Then select "Console" in the debugger menu.</p>
</script>
<p>Then click Run again.</p>
</body> <script>
</html> console.log(5 + 6);
</script>
</body>
</html>
#Example2: You can skip the window keyword.
In JavaScript, the window object is the global scope object. This means that
variables, properties, and methods by default belong to the window object.
This also means that specifying the window keyword is optional:

<html>
<body>
<h2>My First Web Page</h2>
<p>My first paragraph.</p>
<script>
alert(5 + 6);
</script>
</body>
</html>
 JavaScript Print  JavaScript Statements - JavaScript statements are composed
JavaScript does not have any print object or print methods. Values, Operators, Expressions, Keywords, and Comments.
You cannot access output devices from JavaScript. <!DOCTYPE html>
The only exception is that you can call the window.print() method in the <html>
browser to print the content of the current window. <body>
<html> <h2>JavaScript Statements</h2>
<body> <p>JavaScript statements are separated by semicolons.</p>
<h2>The window.print() Method</h2> <p id="demo1"></p>
<p>Click the button to print the current page.</p> <script>
<button onclick="window.print()">Print this page</button> let a, b, c;
</body> a = 5;
</html> b = 6;
c = a + b;
document.getElementById("demo1").innerHTML = c;
</script>

</body>
</html>

First JavaScript Code - Hello, world! -


<html>
<body>
<script language = "javascript" type = "text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
</body>
</html>

Comments in JavaScript
 JavaScript supports both C-style and C++-style comments, Thus −
 Any text between a // and the end of a line is treated as a comment and is ignored by JavaScript.
 Any text between the characters /* and */ is treated as a comment. This may span multiple lines.
 JavaScript also recognizes the HTML comment opening sequence <!--. JavaScript treats this as a single-
line comment, just as it does the // comment.
 The HTML comment closing sequence --> is not recognized by JavaScript so it should be written as //-->.

Example - Single Line Comments - Single line comments start with //.


<html>
<body>
<h1 id="myH"></h1>
<p id="myP"></p>
<script>
// Change heading:
document.getElementById("myH").innerHTML = "JavaScript Comments";
// Change paragraph:
document.getElementById("myP").innerHTML = "My first paragraph.";
</script>
</body>
</html>

#Example: Multi-line Comments - Multi-line comments start with /* and end


with */.
<html>
<body>

<h1 id="myH"></h1>
<p id="myP"></p>
<script>
/*
The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
*/
document.getElementById("myH").innerHTML = "JavaScript Comments";
document.getElementById("myP").innerHTML = "My first paragraph.";
</script>
</body>
</html>

JavaScript - Placement in HTML File


There is a flexibility given to include JavaScript code anywhere in an HTML document. However the most preferred
ways to include JavaScript in an HTML file are as follows −
 Script in <head>...</head> section.
 Script in <body>...</body> section.
 Script in <body>...</body> and <head>...</head> sections.
 Script in an external file and then include in <head>...</head> section.
In the following section, we will see how we can place JavaScript in an HTML file in different ways.
JavaScript in JavaScript in JavaScript in JavaScript in
<head>...</hea <body>...</body> section <body> and External File
d> section If you need a script to run as the page loads <head> there are cases where
If you want to have a script so that the script generates content in the you are reusing
page, then the script goes in the <body> Sections identical JavaScript
run on some event, such You can put your
as when a user clicks portion of the document. In this case, you code on multiple pages
would not have any function defined using JavaScript code in of a site.
somewhere, then you will <head> and <body>
place that script in the JavaScript. Take a look at the following code. You are not restricted to
section altogether as be maintaining identical
head as follows − follows − 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.
<html> <html> <html> <html>
<head> <body> <head> <head>
<script type = <h2>What Can JavaScript Do?</h2> <script type = <script type =
"text/javascript "> <p id="demo">JavaScript can change "text/javascript"> "text/javascript" src =
<!-- HTML content.</p> <!-- "filename.js"
function <button type="button" onclick = function ></script>
sayHello() { 'document.getElementById("demo").inner sayHello() { </head>
alert("Hello HTML = "Hello JavaScript!"'>Click alert("Hello
World") Me!</button> World") <body>
} } .......
//--> </body> //--> </body>
</script> </html> </script> </html>
</head> </head>

<html> To use JavaScript from


<body> <body> an external file source,
<input type = <head> <script type =
</head> you need to write all
"button" onclick = "text/javascript"> your JavaScript source
"sayHello()" value = "Say <!-- code in a simple text file
Hello" /> <body>
<script type = "text/javascript"> with the extension ".js"
</body> document.write("He and then include that
</html> <!-- llo World")
document.write("Hello World") file as shown above.
//--> For example, you can
//--> </script>
</script> keep the following
content
<input type =
<p>This is web page body </p> "button" onclick = in filename.js fil
</body> "sayHello()" value = e and then you can
</html> "Say Hello" /> use sayHello funct
</body> ion in your HTML file
</html> after including the
filename.js file.

function sayHello()
{
alert("Hello World")
}

JavaScript Variables
4 Ways to Declare a JavaScript Variable:
• Using var
• Using let
• Using const
• Using nothing

In this example, x, y, and z, are In this example, x, y, and z, are In this example, x, y, and z
variables, declared with variables, declared with When to Use JavaScript const? undeclared variables:
the var keyword: the let keyword:

<!DOCTYPE html> <html> <html> <html>


<html> <body> <body> <body>
<body> <h2>JavaScript Variables</h2> <h1>JavaScript Variables</h1> <h1>JavaScript Variables</h
<h1>JavaScript Variables</h1> <p>In this example, x, y, and z are <p>In this example, price1, price2, <p>In this example, x, y, and
<p>In this example, x, y, and z are variables.</p> and total are variables.</p> undeclared variables.</p>
variables.</p> <p id="demo"></p> <p id="demo"></p> <p id="demo"></p>
<p id="demo"></p> <script> <script> <script>
<script> let x = 5; const price1 = 5; x = 5;
var x = 5; let y = 6; const price2 = 6; y = 6;
var y = 6; let z = x + y; let total = price1 + price2; z = x + y;
var z = x + y; document.getElementById("demo").in document.getElementById("demo").in document.getElementById("d
document.getElementById("demo").in nerHTML = "The value of z is: " + z; nerHTML = "The total is: " + total; nerHTML = "The value of z i
nerHTML = "The value of z is: " + z; </script> </script> </script>
</script> </body> </body> </body>
</body> </html> </html> </html>
</html>

What are Variables?


Variables are containers for storing data (storing data values). - In this example, x, y, and z, are variables, declared
with the var keyword

JavaScript Variable Scope? -


The scope of a variable is the region of your program in which it is defined. JavaScript variables have only two
scopes.
 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.
<html> <html> <html> <html>
<body onload = <body> <head> <body>
checkscope();> <script> <title>Variables!!!</title> <h1>Demo: JavaScript Global and
<script type = var <script Local Variables </h1>
"text/javascript"> data=200;//gloabal type="text/javascript"> <p id="p1"></p>
<!-- variable var one = 22; <p id="p2"></p>
var myVar = function a(){ var two = 3; <p id="p3"></p>
"global"; // Declare document.writeln(dat var add = one + two;
a global variable a); var minus = one - two; <script>
function } var multiply = one * two; let greet = "Hello " // global variable
checkscope( ) { function b(){ var divide = one/two;
var myVar = document.writeln(dat
"local"; // Declare a a); document.write("First No: = function myfunction(){
local variable } " + one + "<br />Second No: let msg = "JavaScript!"; //local variable
a();//calling = " + two + " <br />");
document.write(myV JavaScript function document.getElementById("p1").innerH
ar); b(); document.write(one + " + " TML = greet + msg;
} </script> + two + " = " + add + }
//--> </body> "<br/>");
</script> </html>
myfunction();
</body> document.write(one + " - " +
</html> two + " = " + minus +
"<br/>"); document.getElementById("p2").innerH
TML = greet;
document.write(one + " * " + document.getElementById("p3").innerH
two + " = " + multiply + TML = msg; //error:can't access local
"<br/>"); variable
</script>
document.write(one + " / " + </body>
two + " = " + divide +
"<br/>");
</script>
</head>
<body>
</body>
</html>

JavaScript Arithmetic Operators


Arithmetic operators are used to perform arithmetic operations on the operands. The
following operators are known as JavaScript arithmetic operators.
Operator Description Example
+ Addition 10+20 = 30
- Subtraction 20-10 = 10
* Multiplication 10*20 = 200
/ Division 20/10 = 2
% Modulus (Remainder) 20%10 = 0
++ Increment var a=10; a++; Now a = 11
-- Decrement var a=10; a--; Now a = 9
Example
The following code shows how to use arithmetic operators in JavaScript.
<html>
<body>

<script type = "text/javascript">


<!--
var a = 33;
var b = 10;
var c = "Test";
var linebreak = "<br />";

document.write("a + b = ");
result = a + b;
document.write(result);
document.write(linebreak);

document.write("a - b = ");
result = a - b;
document.write(result);
document.write(linebreak);

document.write("a / b = ");
result = a / b;
document.write(result);
document.write(linebreak);

document.write("a % b = ");
result = a % b;
document.write(result);
document.write(linebreak);

document.write("a + b + c = ");
result = a + b + c;
document.write(result);
document.write(linebreak);

a = ++a;
document.write("++a = ");
result = ++a;
document.write(result);
document.write(linebreak);

b = --b;
document.write("--b = ");
result = --b;
document.write(result);
document.write(linebreak);
//-->
</script>

Set the variables to different values and then try...


</body>
</html>
Output
a + b = 43
a - b = 23
a / b = 3.3
a%b=3
a + b + c = 43Test
++a = 35
--b = 8
Set the variables to different values and then try...

JavaScript Comparison Operators


The JavaScript comparison operator compares the two operands. The comparison
operators are as follows:
Operator Description Example
== Is equal to 10==20 = false
=== Identical (equal and of same type) 10==20 = false
!= Not equal to 10!=20 = true
!== Not Identical 20!==20 = false
> Greater than 20>10 = true
>= Greater than or equal to 20>=10 = true
< Less than 20<10 = false
<= Less than or equal to 20<=10 = false

Example
The following code shows how to use comparison operators in JavaScript.

<html>
<body>
<script type = "text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";

document.write("(a == b) => ");


result = (a == b);
document.write(result);
document.write(linebreak);

document.write("(a < b) => ");


result = (a < b);
document.write(result);
document.write(linebreak);

document.write("(a > b) => ");


result = (a > b);
document.write(result);
document.write(linebreak);

document.write("(a != b) => ");


result = (a != b);
document.write(result);
document.write(linebreak);

document.write("(a >= b) => ");


result = (a >= b);
document.write(result);
document.write(linebreak);

document.write("(a <= b) => ");


result = (a <= b);
document.write(result);
document.write(linebreak);
//-->
</script>
Set the variables to different values and different operators and then try...
</body>
</html>
Output
(a == b) => false
(a < b) => true
(a > b) => false
(a != b) => true
(a >= b) => false
a <= b) => true
Set the variables to different values and different operators and then try...

JavaScript Bitwise Operators


The bitwise operators perform bitwise operations on operands. The bitwise operators
are as follows:
Operator Description Example
& Bitwise AND (10==20 & 20==33) = false
| Bitwise OR (10==20 | 20==33) = false
^ Bitwise XOR (10==20 ^ 20==33) = false
~ Bitwise NOT (~10) = -10
<< Bitwise Left Shift (10<<2) = 40
>> Bitwise Right Shift (10>>2) = 2
>>> Bitwise Right Shift with Zero (10>>>2) = 2
Example
Try the following code to implement Bitwise operator in JavaScript.
<html>
<body>
<script type = "text/javascript">
<!--
var a = 2; // Bit presentation 10
var b = 3; // Bit presentation 11
var linebreak = "<br />";
document.write("(a & b) => ");
result = (a & b);
document.write(result);
document.write(linebreak);

document.write("(a | b) => ");


result = (a | b);
document.write(result);
document.write(linebreak);

document.write("(a ^ b) => ");


result = (a ^ b);
document.write(result);
document.write(linebreak);

document.write("(~b) => ");


result = (~b);
document.write(result);
document.write(linebreak);

document.write("(a << b) => ");


result = (a << b);
document.write(result);
document.write(linebreak);

document.write("(a >> b) => ");


result = (a >> b);
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
Output
(a & b) => 2
(a | b) => 3
(a ^ b) => 1
(~b) => -4
(a << b) => 16
(a >> b) => 0
Set the variables to different values and different operators and then try...

JavaScript Logical Operators


The following operators are known as JavaScript logical operators.
Operator Description Example
&& Logical AND (10==20 && 20==33) = false
|| Logical OR (10==20 || 20==33) = false
! Logical Not !(10==20) = true
Example
Try the following code to learn how to implement Logical Operators in JavaScript.
<html>
<body>
<script type = "text/javascript">
<!--
var a = true;
var b = false;
var linebreak = "<br />";

document.write("(a && b) => ");


result = (a && b);
document.write(result);
document.write(linebreak);

document.write("(a || b) => ");


result = (a || b);
document.write(result);
document.write(linebreak);

document.write("!(a && b) => ");


result = (!(a && b));
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
Output
(a && b) => false
(a || b) => true
!(a && b) => true
Set the variables to different values and different operators and then try...

JavaScript Assignment Operators


The following operators are known as JavaScript assignment operators.
Operator Description Example
= Assign 10+10 = 20
+= Add and assign var a=10; a+=20; Now a = 30
-= Subtract and assign var a=20; a-=10; Now a = 10
*= Multiply and assign var a=10; a*=20; Now a = 200
/= Divide and assign var a=10; a/=2; Now a = 5
%= Modulus and assign var a=10; a%=2; Now a = 0
Example
Try the following code to implement assignment operator in JavaScript.
<html>
<body>
<script type = "text/javascript">
<!--
var a = 33;
var b = 10;
var linebreak = "<br />";

document.write("Value of a => (a = b) => ");


result = (a = b);
document.write(result);
document.write(linebreak);

document.write("Value of a => (a += b) => ");


result = (a += b);
document.write(result);
document.write(linebreak);

document.write("Value of a => (a -= b) => ");


result = (a -= b);
document.write(result);
document.write(linebreak);

document.write("Value of a => (a *= b) => ");


result = (a *= b);
document.write(result);
document.write(linebreak);

document.write("Value of a => (a /= b) => ");


result = (a /= b);
document.write(result);
document.write(linebreak);

document.write("Value of a => (a %= b) => ");


result = (a %= b);
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
Output
Value of a => (a = b) => 10
Value of a => (a += b) => 20
Value of a => (a -= b) => 10
Value of a => (a *= b) => 100
Value of a => (a /= b) => 10
Value of a => (a %= b) => 0
Set the variables to different values and different operators and then try...

JavaScript Special Operators


The following operators are known as JavaScript special operators.
Operator Description
(?:) Conditional Operator returns value based on the condition. It is like if-else.
, Comma Operator allows multiple expressions to be evaluated as single statement.
delete Delete Operator deletes a property from the object.
in In Operator checks if object has the given property
instanceof checks if the object is an instance of given type
new creates an instance (object)
typeof checks the type of object.
void it discards the expression's return value.
yield checks what is returned in a generator by the generator's iterator.

Example
Try the following code to understand how the Conditional Operator works in JavaScript.
<html>
<body>
<script type = "text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";

document.write ("((a > b) ? 100 : 200) => ");


result = (a > b) ? 100 : 200;
document.write(result);
document.write(linebreak);

document.write ("((a < b) ? 100 : 200) => ");


result = (a < b) ? 100 : 200;
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
Output
((a > b) ? 100 : 200) => 200
((a < b) ? 100 : 200) => 100
Set the variables to different values and different operators and then try..

JavaScript if, else, and else if


Flow Chart of if-else
The following flow chart shows how the if-else statement works.
JavaScript supports the following forms of if..else statement −
 if statement
 if...else statement
 if...else if... statement.

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
}

<html> <html>
<body> <body>
<h2>JavaScript if</h2> <script>
<p>Display "Good day!" if the hour is less than var a=20;
18:00:</p> if(a%2==0){
<p id="demo">Good Evening!</p> document.write("a is even number");
<script> }
if (new Date().getHours() < 18) else{
{ document.getElementById("demo").innerHTML = document.write("a is odd number");
"Good day!"; }
} </script>
</script> </body>
</body> </html>
</html>

Create a JavaScript Calculator using If... Else...If statement and display using the
prompt dialog box.
<html>  
<body>  
<script>  
  
// program to create a simple calculator using the if...else...if in JavaScript.  
// take the operator from the user through prompt box in JavaScript.  
const operator = prompt('Enter operator to perform the calculation ( either +, -, * or / ): ');  
  
// accept the number from the user through prompt box  
const number1 = parseFloat(prompt ('Enter the first number: '));  
const number2 = parseFloat(prompt ('Enter the second number: '));  
  
let result; // declaration of the variable.  
  
// use if, elseif and else keyword to define the calculator condition in JavaScript.  
if (operator == '+') { // use + (addition) operator to add two numbers  
    result = number1 + number2;  
}  
else if (operator == '-') { // use -  (subtraction) operator to subtract two numbers  
    result = number1 - number2;  
}  
else if (operator == '*') { // use * (multiplication) operator to multiply two numbers  
    result = number1 * number2;  
}  
else {  
    result = number1 / number2; // use / (division) operator to divide two numbers  
}  
  
// display the result of the Calculator  
window.alert(" Result is" + result);  
</script>  
<body>  
</html>  

JavaScript Switch Statement
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.
switch (expression) {
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
case condition n: statement(s)
break;
default: statement(s)
}
1. The switch is a conditional statement like if statement.
2. A switch statement includes literal value or is expression based
3. A switch statement includes multiple cases that include code blocks to execute.
4. A break keyword is used to stop the execution of case block.
5. A switch case can be combined to execute same code block for multiple cases.
<html> <html> <html>
<body> <body> <body>
<h1>Demo: switch case</h1> <h1>Demo: combined switch
<h2>JavaScript switch</h2> cases</h1>
<script>
var a = 3; <p id="demo"></p> <script>
var a = 2;
switch (a) { <script>
case 1: let day; switch (a) {
alert('case 1 executed'); switch (new Date().getDay()) { case 1:
case 2: case 0: case 2:
alert("case 2 executed"); day = "Sunday"; case 3:
break; break; alert("case 1, 2, 3
case 3: case 1: executed");
alert("case 3 executed"); day = "Monday"; break;
break; break; case 4:
case 4: case 2: alert("case 4 executed");
alert("case 4 executed"); day = "Tuesday"; break;
break; break; default:
default: case 3: alert("default case
alert("default case executed"); day = "Wednesday"; executed");
} break; }
case 4: </script>
</script> day = "Thursday"; </body>
</body> break; </html>
</html> case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
document.getElementById("demo").innerHTML
= "Today is " + day;
</script>

</body>
</html>

You might also like