0% found this document useful (0 votes)
6 views36 pages

C DAC Javascript DAY1

The document provides an introduction to JavaScript, highlighting its importance as a core web development language alongside HTML and CSS. It covers the language's features, advantages, limitations, and how to integrate JavaScript into HTML, along with various programming concepts such as variables, data types, operators, conditional statements, and loops. Additionally, it includes examples of code and explanations of JavaScript syntax and functionality.

Uploaded by

vivekya9504
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)
6 views36 pages

C DAC Javascript DAY1

The document provides an introduction to JavaScript, highlighting its importance as a core web development language alongside HTML and CSS. It covers the language's features, advantages, limitations, and how to integrate JavaScript into HTML, along with various programming concepts such as variables, data types, operators, conditional statements, and loops. Additionally, it includes examples of code and explanations of JavaScript syntax and functionality.

Uploaded by

vivekya9504
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/ 36

Introduction to JavaScript

Short Term Training © C-DAC Patna


Why Should You Learn JavaScript?
• JavaScript is one of the three essential languages that every web developer absolutely
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
• JavaScript is a lightweight, interpreted programming language with object-oriented
capabilities that allows you to build interactivity into otherwise static HTML pages.
• With JavaScript, users can build modern web applications to interact directly without
reloading the page every time.
• Data Validation

Short Term Training © C-DAC Patna


About JavaScript
• JavaScript is a Open Source Scripting Language developed by Brendan Eich at NetScape
Corporation in May 1995.
• JavaScript is Platform Independent Scripting Language.
• JavaScript is the Case Sensitive Language.
• JavaScript was initially Object Base Language now object oriented.
• JavaScript is the Event-Driven Programming Language.
• JavaScript is mainly used for client side validations.
• No relation to JAVA Programming Language.

Short Term Training © C-DAC Patna


Advantages and Disadvantages
Advantages of JavaScript:
1. Less server interactions
2. Immediate feedback to the users
3. Increased Interactivity
Limitations with JavaScript:
1. Its not a full fledged programming language
2. Does not allow the reading and writing of files
3. Not used for network applications
4. Multithreading and multiprocessing is not available

Short Term Training © C-DAC Patna


Putting JavaScript into HTML Page
• The <script> Tag - In HTML, JavaScript code is inserted
between <script> and </script> tags.
• <script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>
• Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both.
• External JS -
• Scripts can also be placed in external files
• JavaScript files have the file extension .js.
• To use an external script, put the name of the script file in the src (source) attribute of a <script> tag:
• <script src="myScript.js"></script>
• To add several script files to one page - use several script tags

Short Term Training © C-DAC Patna


Example Code

Short Term Training © C-DAC Patna


JS Output
• JavaScript can "display" data in different ways:
• Writing into the HTML output using document.write().
• Writing into an alert box, using window.alert().
• Writing into the browser console, using console.log().
• Writing into an HTML element, using innerHTML. (DOM manipulation method)
• For testing purposes, it is convenient to use document.write()
• Try window.print() ??
• prompt() - A JavaScript prompt is a dialog box that asks the user to input some text,
typically providing a way to capture user input in a web application.
• prompt(“Enter your name”)

Short Term Training © C-DAC Patna


Example code -
First Code as always – Print “Hello World! ”

Short Term Training © C-DAC Patna


JavaScript Variables
• Variables are Containers for Storing Data
• JavaScript Variables can be declared in 4 ways:
• Automatically - They are automatically declared when first used
• Using var - Only use var if you MUST support old browsers.
• Using let - Only use let if you can't use const
• Using const - These are constant values and cannot be changed.
• It is considered good programming practice to always declare variables before use.
• A variable declared without a value will have the value undefined.
• let variable_test; //value will be undefined
• You cannot re-declare a variable declared with let or const.
• Variables defined with const cannot be Reassigned.
• const variables must be assigned a value when they are declared.

Short Term Training © C-DAC Patna


JavaScript Identifiers / Names
• All JavaScript variables must be identified with unique names.
• These unique names are called identifiers.
• Identifiers are used to name variables and keywords, and functions.
• A JavaScript name must begin with:
• A letter (A-Z or a-z)
• A dollar sign ($)
• Or an underscore (_)
• Subsequent characters may be letters, digits, underscores, or dollar signs.
• All JavaScript identifiers are case sensitive.
• JavaScript programmers tend to use camel case that starts with a lowercase letter:
• firstName
• lastName

Short Term Training © C-DAC Patna


Reserved Words

Short Term Training © C-DAC Patna


JavaScript Scope
• Scope determines the accessibility (visibility) of variables.
• JavaScript variables have 3 types of scope:
• Block scope
• Function scope
• Global scope
• ES6 introduced two important new JavaScript keywords: let and const
• These two keywords provide Block Scope in JavaScript.
• Variables declared inside a { } block cannot be accessed from outside the block:
• {
let x = 2;
} // x can NOT be used here
• Variables defined inside a function are not accessible (visible) from outside the function.
• function myFunction() {
let foodName = “burger"; // Function Scope
}
• Variables declared Globally (outside any function) have Global Scope.
• let foodName = “burger";
// code here can use foodName

function myFunction() {
// code here can also use foodName
}

Short Term Training © C-DAC Patna


JavaScript Statements
• A computer program is a list of "instructions" to be "executed" by a computer.
• In a programming language, these programming instructions are called statements.
• JavaScript statements are composed of: Values, Operators, Expressions, Keywords, and Comments.
• document.getElementById("demo").innerHTML = "Hello Sunita.";
• Statements are executed, one by one, in the same order as they are written.
• Semicolons separate the JavaScript statements.
• let a, b, c; // Declare 3 variable
• If a JavaScript statement does not fit on one line, the best place to break it is after an operator.
• JS expression is a combination of values, variables, and operators, which computes to a value.
• 5 * 10
• x * 10 // where x is an variable

Short Term Training © C-DAC Patna


JS Comments
• Code after double slashes // or between /* and */ is treated as a comment.
• Comments are ignored, and will not be executed.

Example code –
// This is a single-line comment
/*
This is a
multi-line comment
*/
console.log("Check the comments in the code!");

Short Term Training © C-DAC Patna


Data Types in JavaScript

• JavaScript has dynamic types. This means that the same variable can be used to hold different data types.
• Undefined - Represents a variable that has been declared but not assigned a value.
• Null - Represents an intentional absence of any object value.
• Symbol - Represents a unique identifier (introduced in ECMAScript 6)

Short Term Training © C-DAC Patna


Example Code -
• // Numbers:
let length = 25;
let weight = 7.5;

// Strings:
let color = “Red";
let lastName = ‘Sanjay’;

// Booleans:
let x = true;
let y = false;

// Object:
const person = {firstName:“Aayush", lastName:“Sinha"};

// Array object:
const cars = [“Alto", "Volvo", "BMW"];

// Date object:
const date = new Date("2022-03-25");

Short Term Training © C-DAC Patna


JavaScript Operators
• Javascript operators are used to perform different types of mathematical and logical computations.
• // Assign the value 5 to x
• let x = 5;
• Operators:
1.unary:
increment/decrement(++,--)
sign operator (+,-)
logical not (!)
complement operator (~)
special operator : typeof ,delete ,new
2.binary:
arithmetic (+,-,*,/,%,**)
relational(>,<,>=,<=,==,!=,===,!==)
logical (&&,||)
assignment(=,+=,-+,*=,/=, etc)
bitwise(&,|,^,>>,<<)
3.ternary:
conditional operator: ? :

Short Term Training © C-DAC Patna


Arithmetic Operators
• Arithmetic Operators are used to perform arithmetic on numbers
• The numbers (in an arithmetic operation) are called operands.
• The operation (to be performed between the two operands) is defined by an operator.

Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation (ES2016)
/ Division
% Modulus (Division Remainder)
++ Increment
-- Decrement

Short Term Training © C-DAC Patna


Operator Precedence
• Operator precedence describes the order in which operations are performed in an arithmetic
expression.
• let x = 100 + 50 * 3;
• Operations have the same precedence (like addition and subtraction or multiplication and
division), they are computed from left to right:
• let x = 100 / 50 * 3;

Short Term Training © C-DAC Patna


JavaScript Assignment Operators
Operator Example Same As

= 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

Short Term Training © C-DAC Patna


JavaScript Comparison Operators
Operator Description

== equal to
=== equal value and equal type
!= not equal
!== not equal value or not equal type
> greater than
< less than
>= greater than or equal to
<= less than or equal to
?: ternary operator

Short Term Training © C-DAC Patna


Logical Operator
Operator Description

&& Called Logical AND operator. If both the operands are non-zero, then
the condition becomes true.

|| Called Logical OR Operator. If any of the two operands are non zero
then then condition becomes true.

!
Called Logical NOT operator. Used to reverse the logical state of its
operand. If a condition is true, then the Logical NOT operator will
make it false.

Short Term Training © C-DAC Patna


Bitwise Operators
Operator Description Example Decimal

& AND 2&3 2

| OR 2|3 3

~ NOT ~3 -4
^ XOR 2^3 1

<< left shift 2 << 1 4

>> right shift 2 >> 1 1

>>> unsigned right shift 2>>> 1 1

Short Term Training © C-DAC Patna


Ternary Operator
• It takes three operands.
• syntax - condition ? expression1 : expression2
• Question – age > 18 adult , age < 18 = minor ?

Short Term Training © C-DAC Patna


JavaScript Type Operators
Operator Description

typeof Returns the type of a variable

instanceof The instanceof keyword checks whether an object is an


instance of a specific class or an interface.

The typeof Operator - You can use the JavaScript typeof operator to find the type of a JavaScript variable.
- typeof “Salman Khan"; //string
Example – let something = objectName instanceOf objectType

Short Term Training © C-DAC Patna


Conditional Statements
• Conditional statements are used to perform different actions based on different conditions.
• In JavaScript we have the following conditional statements:
- if, if-else, if…else if…,nested if
- Switch case

• The if statement is the fundamental control statement that allows JavaScript to make decisions and
execute statements conditionally.
• Syntax: if (expression){
Statement(s) to be executed if expression is true }

• The if...else statement is the next form of control statement that allows JavaScript to execute
statements in more controlled way.

• The if...else if... statement is the one level advance form of control statement that allows
JavaScript to make correct decision out of several conditions.

Short Term Training © C-DAC Patna


Example code -
<script type="text/javascript">
<!--
var book = "maths";
if( book == "history" ){
document.write("<b>History Book</b>");
}else if( book == "maths" ){
document.write("<b>Maths Book</b>");
}else if( book == "economics" ){
document.write("<b>Economics Book</b>");
}else{
document.write("<b>Unknown Book</b>");
}
//-->
</script>

Short Term Training © C-DAC Patna


Switch Case
• Multiple if...else if statements to perform a multiway check.
• 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 if statements.
• Syntax -
switch (expression)
{
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
...
case condition n: statement(s)
break;
default: statement(s)
}

Short Term Training © C-DAC Patna


Example code -

Short Term Training © C-DAC Patna


Looping Statements
• The for loop is the most compact form of looping and includes the following three important parts:
• The loop initialization
• The test condition
• The iteration statement where you can increase or decrease your counter.
• Syntax:
for (initialization; test condition; iteration statement){
Statement(s) to be executed if test condition is true
}
• for...in loop : This loop is used to loop through an object's properties.
- for (variablename in object){ // Each iteration returns a key
statement or block to execute
}
• The For Of Loop : The JavaScript for of statement loops through the values of an iterable object -
such as Arrays, Strings, Maps, NodeLists, and more…
- for (variable of iterable) {
// code block to be executed
}

Short Term Training © C-DAC Patna


Example code -
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
<!--
var aProperty;
document.write("Navigator Object Properties<br /> ");
for (aProperty in navigator) // for .. in Loop
{
document.write(aProperty);
document.write("<br />");
}
document.write("Exiting from the loop!");
//-->
</script>
<p>Set the variable to different object and then try...</p>
</body>
</html>

Short Term Training © C-DAC Patna


While Loop
• Loops can execute a block of code as long as a specified condition is true.
• while (condition) {
// code block to be executed
}
• If you forget to increase the variable used in the condition, the loop will never end.
This will crash your browser.
• do while loop : This loop will execute the code block once, before checking if the
condition is true, then it will repeat the loop as long as the condition is true.
• do {
// code block to be executed
}
while (condition);

Short Term Training © C-DAC Patna


Example code -
<!DOCYPE html>
<html>
<body>
<script type="text/javascript">
<!--
var count = 0;
document.write("Starting Loop");
while (count < 10){
document.write("Current Count : " + count + "<br/>");
count++;
}
document.write("Loop stopped!");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>

Short Term Training © C-DAC Patna


JavaScript Loop Control
• JavaScript provides you full control to handle your loops and switch
statement.
• JavaScript provides break and continue statements.
break :
• The break statement "jumps out" of a loop.
• The break statement is used to exit a loop early, breaking out of the enclosing curly
braces.
Continue :
• The continue statement "jumps over" one iteration in the loop.
• The continue statement tells the interpreter to immediately start the next iteration of
the loop and skip remaining code block.

Short Term Training © C-DAC Patna


Examples -
Q1. Sum of Odd Numbers Between 1 and 20: Write a JavaScript program that uses a for loop to calculate the sum
of all odd numbers between 1 and 20. Use the continue statement to skip even numbers.

Q2. Write a JavaScript program that uses a while loop to print numbers starting from 1 until it encounters the
number 5, then stops using the break statement.
Q3.
<script>
let num = 1;
while(num < 5) {
if(num == 2){
continue;
}
document.write(num);
num ++;
}
</script>

Short Term Training © C-DAC Patna


Thank You !

Short Term Training © C-DAC Patna

You might also like