0% found this document useful (0 votes)
3K views54 pages

Introduction to JavaScript Basics

Cse 201 agricultural Engineering

Uploaded by

Subham Karmakar
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)
3K views54 pages

Introduction to JavaScript Basics

Cse 201 agricultural Engineering

Uploaded by

Subham Karmakar
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
You are on page 1/ 54

JavaScript

Introduction
• JavaScript was introduced in 1995.
• Initially the language was used to add programs to web pages in the
Netscape Navigator Browser. Later adopted by all other major Web
browser.
• This language has made the web application capable of direct
interaction without a page reload for every action.
• JavaScript has almost nothing to do with the programming language
name Java. The similar name was inspired by marketing
consideration.
Features of JavaScript
• JavaScript is a full-fledges programming language that enables
dynamic interactivity on website on websites when applied to an
HTML document.
• All popular web browsers support JavaScript as they provide built-in
execution environments.
• It is a light-weighted and interpreted language.
• It is a case-sensitive language.
• It provides good control to the users over the web browser.
JavaScript code
• JavaScript code is inserted between <script> and </script> tag.
• This script tag can be placed in the <body>, or in the <head> section
of an HTML page, or in both.
JavaScript Example-2
<html>
<body>
<script>
document.write(“This is a JavaScript program inside body tag.”);
</script>
</body>
</html>
JavaScript Example-2
<html>
<head>
<script>
document.write(“This is a JavaScript program inside head tag.”);
</script>
</head>
<body>
</body>
</html>
JavaScript Comment
• The JavaScript comments are used to add information about the
code, warnings or suggestions to make the code easy to understand.
• The JavaScript comment is ignored by the JavaScript engine.
• Type of JavaScript Comments:
• Single-line Comment
• Multi-line Comment
Types of JavaScript Comments
Single line Comment Multi line Comment
• It is represented by double slashes (//). • It can be used to add single as well as
• It can be used before and after the multi line comments.
statement • It is represented by forward slash with
asterisk then asterisk with forward slash.

<script> <script>
//It is a single line comment /* It is a multi line comment
document.write(“Single line”); It will not be displayed */
</script> document.write(“Multi line”);
</script>
JavaScript Variables
• Variables are containers for storing data.
• There are some rules while declaring a JavaScript variable (also
known as identifiers).
• Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ )
sign.
• After first letter we can use digits (0 to 9), for example value1.
• JavaScript variables are case sensitive, for example x and X are different
variables.
JavaScript Variable Declaration and Initialization
• Declaration of a variable is used to specify the variable and type.
• Initialization is the process of assigning a value to the variable.
• Different ways of declaring any JavaScript Variable:
• var
• let
• const
• Even without declaring anything

var x; // Variable Declaration let x = 10; // Variable


x = 10; // Variable Initialization Declaration and Initialization x = 10;
in a Single line.
Few points about Variables
• Variables defined with let and const cannot be redeclared.
• Variables defined with const cannot be reassigned.
• Variables defined with let must be declared before use.
• var should be used only if any older browser is used.
• Variable defined inside a {} block with let and const cannot be
accessed from outside.
• JavaScript is a dynamic type language. As a result of that, there is no
need to specify the type of variable, because it is dynamically used by
JavaScript engine.
Datatypes
• Primitive data types are a set of basic data types from which all other
data types are constructed.
• JavaScript has seven primitive data types.
• String
• Number
• BigInt
• Boolean
• Undefined
• Symbol
• NULL
Primitive Datatypes
Datatype Description Example
String • A String is a sequence of characters used to represent text. let str1 = “Hello”;
• String are written with quotes, either single or double quotes. let str2 = ‘world’;
let str3 = ‘Hello World”;

Number • All JavaScript are stored as decimal numbers (double precision 64 bit floating //With decimals
point format (IEEE 754)). let num1 = 10.00;
//Without decimals
let num2 = 10;
BigInt • JavaScript BigInt is a new datatype that can be used to store integer values let x = BigInt("123456789012345678901234567890");
that are too big to be represented by a normal JavaScript number.

Boolean • Boolean can only have two values: true or false. let x = 5;
let y = 5;
(x == y) // Returns true
Undefined • undefined is a primitive value automatically assigned to variables that have let x;
just been declared. var y;
Symbol • Symbols are unique and it can be used as keys for objects. let a = symbol(‘sample’);

Null • Null declares a variable with an empty value and undefined defines a document.write(null == undefined) //true
variable with no value. document.write(null == undefined) //false
Datatypes cont.
• A composite or derived or compound data type is any data type
which can constructed using primitive data types and other
composite data types.
• Followings are the composite datatype in JavaScript:
• Object – An object contains different types of values.
• Array – It represents a collection of similar element in JavaScript.
• RegExp – It represents regular expression in JavaScript
JavaScript Operators
• There are following types of operators in JavaScript:
• Arithmetic Operators
• Comparison (Relational) Operators
• Bitwise Operators
• Logical Operators
• Assignment Operators
JavaScript Arithmetic Operator
Operator Description Example
+ Addition 10+20 = 30
- Subtraction 20-10 = 10
* Multiplication 10*20 = 200
** Exponentiation 10**2 = 100
/ Division 10/2 = 5
% Modulus 10%2 = 0
++ Increment Var a = 10
a++; // a is now 11
-- Decrement Var a = 10
a--; // a is now 9
JavaScript Comparison Operator
Operator Description Example
== Is equal to var x = 10;
x == ‘10’ // true
=== Identical (equal and of same type) var x = 10;
x === ‘10’ // false
!= Not equal to var x = 10;
x != ’10’ // false
!== Not identical var x = 10;
x !== ‘10’ // true
> Greater than 20 > 20 // false
>= Greater than or equal to 20 >= 20 // true
< Less than 20 < 20 // false
<= Less than or equal to 20 <= 20 // true
? Conditional operator Conditional Exp ? Exp If True : Exp If False
JavaScript Bitwise Operators

Operator Name Description


& AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is 1.
^ XOR Sets each bit to 1 if only one of two bits is 1.
~ NOT Inverts all the bits.
<< Zero fill left shift Shifts left by pushing zeros in from the right and let the
leftmost bits fall off.
>> Signed right shift Shifts right by pushing copies of the leftmost bit in from the
left, and let the rightmost bits fall off.
>>> Zero fill right shift Shifts right by pushing zeros in from the left, and let the
rightmost bits fall off.
JavaScript Bitwise Operations Example

Operation Result Result


5&1 1 0101 & 0001 0001
5|1 5 0101 | 0001 0101
~5 10 ~ 0101 1010
5 << 1 10 0101 << 1 1010
5^1 4 0101 ^ 0001 0100
5 >> 1 2 0101 >> 1 0010
5 >>> 1 2 0101 >>> 1 0010
JavaScript Logical Operators
Operator Describe Example
&& Logical AND (10 == 20 && 20 == 33) // False
|| Logical OR (10 == 20 || 20 == 33) // False
! Logical NOT !(10 == 20) // True
Logical Assignment Operators
Operator Example Similar to
= x=y x=y
+= x += y x=x+y
-= x -= y x=x-y
*= x *= y x=x*y
/= x /= y x=x/y
%= x %= y x=x%y
**= x **= y x = x ** y
Block
• In code, we often need to group a
series of statements together, var amount = 33.33;
which we often call a block.
• In JavaScript, a block is defined by
wrapping one or more statements // a general block
inside curly-brace pair { … }. {
• Typically, these blocks are attached amount = amount * 2;
to some other control statement, document.write(amount);
such as if statement or loop.
}
Conditional Statement
• Conditional statements are used to perform different actions based
on different conditions.
• JavaScript if-else statements are used to execute conditional
statements.
• There are three forms if statements.
• if statement
• else statement
• else if statement
If Statement
• A block of JavaScript code to be executed • Example:
if the expression or the condition is true. If a number is greater than zero. Then print
• Syntax: positive.

if (condition) let x = 100;


{ if (x > 0)
// block of code to be executed {
} document.write(“Positive”);
}
The else statement
• else statement specifies a block of code • Example:
to be executed if the condition or If a number is greater than equal to zero.
expression is false. Then print positive. Otherwise print
• Syntax negative.
if (condition)
{ let x = 100;
// block of code to be executed if (x >= 0)
} {
else document.write(“Positive”);
{ }
// block of code to be executed else
} {
document.write(“Negative”);
}
The else-if Statement
• The else-if statement specifies a new condition if the first condition is false.
• Syntax:
if (condition1)
{
// block of code to be executed if condition1 is true.
}
else if (condition2)
{
// block of code to be executed if condition1 is false and condition2 is true.
}
else
{
// block of code to be executed if condition1 and consition2 both are false.
}
The else-if statement example
If a number is less than equal to zero, then print negative. If less than
100, then print print positive and less than 100, otherwise print
positive and greater than 100.
JavaScript Switch Statement
• The switch statement is used to • Syntax:
perform different actions based on
different conditions.
switch (expression)
• It is just like else-if statement. But it is
more convenient as it can be used with {
numbers, characters etc. case x:
• The switch statement evaluates an // code block
expression, matching the expression's
value against a series of case clause. case y:
Then executes statements after the // code block
first case clause with a matching value,
until a break statement is default:
encountered. //
code block
}
JavaScript Switch Statement cont.
• The break keyword stop the execution inside the switch block. However, it
is not necessary to break the last case in a switch block. The block breaks
(end) there anyway.
• If anyone omit the break statement, the next case will be executed even if
the evaluation does not match the case.
• The default keyword specifies the code to run if no case matches.
• The default case does not have to be the last case in a switch block.
• If multiple cases matches a case value, the first case will be selected.
• The switch case uses strict comparison (===).
JavaScript switch statement example 1
let x = 3; case 2:
switch(x) {
{
document.write(“two”);
break;
case 0: }
{ case 3:
document.write(“zero”); {
break; document.write(“three”);
} break;
}
case 1: default:
{ {
document.write(“one”); document.write(“Wrong Number”);
break; }
}
}
JavaScript switch statement example 2
let x = 'Bananas'; default:
switch(x) {
{ document.write("Wrong choices");
case 'Oranges': }
{
document.write("Oranges are orange");
break;
}
case 'Bananas':
{
document.write("Bananas are yellow");
break;
}
Ternary Operator
• Ternary operator can be used • Finding the larger number out of
alternatively in place of if-else two variables?
statement.
• Ternary operator is used to make var a = 10;
the code more concise.
var b = 20;
• Syntax:
condition ? expressionIfTrue :
expressionIfFalse; (a > b) ? (document.write(“a is
greater.”)) : (document.write(“b is
greater”));
Flowchart
● A flowchart is a type of diagram that
represents a workflow or process. Symbol Purpose
● A flowchart can also be defined as a
diagrammatic representation of an Flowline
algorithm.
Terminal (start /
stop)

Statements

Condition

Input / Output
JavaScript Loops
• Loops is used to execute a block of code a number of times.
• Mainly there exists three types of loop:
• While loop
• Do-While loop
• For loop
While loop
• The JavaScript while statement creates a loop that executes a block of
statements as long as a condition evaluates to true.
• The while statement evaluates the expression before each iteration of
the loop.
• If the expression evaluates to true, the while statement executes the
block of statements. Otherwise, the while loop exists.
• Because the while loop evaluates the expression before each
iteration, it is known as a pretest loop.
• If the expression evaluates to false before the loop enters, the while
loop will never execute.
Syntax and Flowchart for While loop
• Syntax

while (expression)
{
// statement
}
Example of While loop
• Print all the number from 1 to 10. • Output:
1
let count = 1; 2
while( count <= 10) 3
{ 4
document.write(count); 5
count = count + 1; 6
} 7
8
9
10
Do-While loop
• The do-while loop statement creates a loop that executes a block of
statements until a condition evaluates to false.
• Unlike the while loop, the do-while loop always executes the block of
statements at least once before evaluating the expression.
• Because the do-while loop evaluates expression after each iteration,
it’s often referred to as a post-test loop.
Syntax and Flowchart for Do-While loop
• Syntax

do
{
// statement
}while(expression);
Example of Do-While loop
• Print all the number from 1 to 10. • Output:
1
let count = 1; 2
do 3
{ 4
document.write(count); 5
count = count + 1; 6
} while (count <= 10); 7
8
9
10
For loop
• The for loop statements creates a loop with three expressions. These are:
• Initializer
The for statement executes the initializer only once the loop starts. It initializes a
loop variable in the initializer.
• Condition
The condition is a Boolean expression that determines whether the for should
execute the next iteration.
The for statement evaluates the condition before each iteration. If the condition
is true (or is not present), it executes the next iteration. Otherwise, it’ll end the loop.
• Iterator
The for statement executes the iterator after each iteration.
Syntax and Flowchart of For loop
• Syntax

for (initializer; condition; iterator)


{
// statements
}
Example of Do-While loop
• Print all the number from 1 to 10. • Output:
1
let count; 2
3
for(count = 1; count <= 10; count++) 4
{ 5
document.write(count); 6
} 7
8
9
10
Break Statement
• The break statement prematurely • Example:
terminates a loop such as for, for(i=0; i<10; i++)
do…while, while loop, switch etc.
{
if (i == 5)
{
break;
}
}
Continue Statement
• The continue statement • Find all the even number from 1 to 10
terminates the execution of the
statement in the current iteration
for(i=1; i<=10; i++)
of a loop such as for, while,
do…while loop and immediately {
continues the next iteration. if (i%2 != 0)
{
continue;
}
document.write(“Even no:”, i);
}
JavaScript Functions
• A JavaScript function is a block of code designed to perform a
particular task.
• A JavaScript function is executed when “something” invokes it invokes
it or call it.
• A JavaScript function can be called several time to reuse the code.
JavaScript Function Syntax
• A JavaScript function is defined with
the function keyword, followed by a function functionName(parameter))
name, followed by parentheses.
{
• The parentheses contains zero, one
or multiple arguments or parameter. // code to be executed
• The function name must be a valid
identifier. }
Few more points:
• The code inside the function will execute • Example
when some statement invokes (calls) the
function. var x;
• Function often compute a return value. function newFunc(a, b)
The return value id “returned” back to the {
“caller”. return a*b;
• If the function was invoked from a }
statement, JavaScript will “return” to x = newFunc(10, 20);
execute the code after the invoking
document.write(x);
statement.
• In JavaScript, a function can be called
before function declaration.
Local Variables
• Variables declared within a • Example:
JavaScript function, become local
to the function.
• Local variables can only be // code here can NOT use carName
accessed from within the function.
Function myFunc()
{
let carName = “Volvo”;
// code here CAN use carName
}

// code here can NOT use carName


How to write JavaScript in an External File
• Create external JavaScript file with the extension .js.
• After creating, add it to the HTML file in the script tag. The src
attribute is used to include that external JavaScript file.
• If there are more than one external JavaScript file, then add it in the
same web page to increase performance of the page.
Example
<!DOCTYPE html>
<html> • Javascript file
<head> meta charset=“utf-8” </head>
<body> function newFunc()
<form> {
<input type="button” value="Result" document.write("Hello Everyone");
onclick=”newFunc()"/>
}
</form>
<script src="new.js">
</script>
</body>
</html>
Alert() method
• The alert() method displays an • Example:
alert box with a message and an
OK button.
alert(“This is a JavaScript alert”);
• Syntax:
alert(message)
• This message is optional.
• The message contains the text to
be displayed in the alert box.
Confirm() method
• The confirm() method displays a • Example
dialog box with a message, an
OK button, and a Cancel button.
let str = “Hello Everyone”;
• The confirm() method returns if (confirm(str) == true)
true if the user clicked “Ok”, {
otherwise false.
document.write(“you have clicked OK”);
• Syntax: }
confirm(message) else
{
document.write(“you have clicked cancel”);
}
Prompt() method
• The prompt() method displays a dialog • Example
box that prompts the user input. var x = 10;
• The prompt() method returns the input var y = prompt(“Enter the value:”, 10);
value if the user clicks “OK”, otherwise it var z = Number(y);
returns NULL. if (x == z)
• Syntax: {
prompt(text, defaultText) document.write(“Ok”);
}
• The text is optional. The text is displayed
in the text box. else
{
• The defaultText is also optional. This is the
default input. document.write(“Not Ok”);
}

You might also like