SlideShare a Scribd company logo
1 of 52
JavaScript
Functions, Arrays
Megha V
Assistant Professor
Dept of IT,
Kannur University
14-10-2022 meghav@kannuruniv.ac.in 1
JavaScript Statements
let x, y, z; // Statement 1
x = 5; // Statement 2
y = 6; // Statement 3
z = x + y; // Statement 4
14-10-2022 meghav@kannuruniv.ac.in 2
JavaScript Programs
• A computer program is a list of "instructions" to be
"executed" by a computer.
• In a programming language, these programming
instructions are called statements.
• A JavaScript program is a list of
programming statements.
• In HTML, JavaScript programs are executed by the web
browser.
14-10-2022 meghav@kannuruniv.ac.in 3
JavaScript Statements
• JavaScript statements are composed of:
• Values, Operators, Expressions, Keywords, and
Comments.
• This statement tells the browser to write "Hello Dolly."
inside an HTML element with id="demo":
document.getElementById("demo").innerHTML = "Hello
Dolly.";
14-10-2022 meghav@kannuruniv.ac.in 4
• Most JavaScript programs contain many JavaScript statements.
• The statements are executed, one by one, in the same order as
they are written.
• JavaScript programs (and JavaScript statements) are often called
JavaScript code.
JavaScript Statements
14-10-2022 meghav@kannuruniv.ac.in 5
Semicolons ;
• Semicolons separate JavaScript statements.
• Add a semicolon at the end of each executable
statement:
• Examples
let a, b, c; // Declare 3 variables
a = 5; // Assign the value 5 to a
b = 6; // Assign the value 6 to b
c = a + b; // Assign the sum of a and b to c
14-10-2022 meghav@kannuruniv.ac.in 6
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Statements</h2>
<p>JavaScript statements are separated by semicolons.</p>
<p id="demo1"></p>
<script>
let a, b, c;
a = 5;
b = 6;
c = a + b;
document.getElementById("demo1").innerHTML = c;
</script>
</body>
</html>
JavaScript Statements
JavaScript statements are separated by semicolons.
11
14-10-2022 meghav@kannuruniv.ac.in 7
• When separated by semicolons, multiple statements on
one line are allowed:
a = 5; b = 6; c = a + b;
JavaScript White Space
• JavaScript ignores multiple spaces. You can add white
space to your script to make it more readable.
• The following lines are equivalent:
let person = "Hege";
let person="Hege";
• A good practice is to put spaces around operators ( = +
- * / ):
let x = y + z;
14-10-2022 meghav@kannuruniv.ac.in 8
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 (calls it).
14-10-2022 meghav@kannuruniv.ac.in 9
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Functions</h2>
<p>This example calls a function which performs a calculation, and returns the result:</p>
<p id="demo"></p>
<script>
function myFunction(p1, p2) {
return p1 * p2;
}
document.getElementById("demo").innerHTML = myFunction(4, 3);
</script>
</body>
</html>
JavaScript Functions
This example calls a function which performs a calculation, and
returns the result:
12
14-10-2022 meghav@kannuruniv.ac.in 10
JavaScript Function Syntax
• A JavaScript function is defined with the function keyword, followed
by a name, followed by parentheses ().
• Function names can contain letters, digits, underscores, and dollar
signs (same rules as variables).
• The parentheses may include parameter names separated by
commas:
• (parameter1, parameter2, ...)
14-10-2022 meghav@kannuruniv.ac.in 11
The code to be executed, by the function, is placed inside curly
brackets: {}
function name(parameter1, parameter2, parameter3) {
// code to be executed
}
JavaScript Function Syntax
14-10-2022 meghav@kannuruniv.ac.in 12
• Function parameters are listed inside the parentheses
() in the function definition.
• Function arguments are the values received by the
function when it is invoked.
• Inside the function, the arguments (the parameters)
behave as local variables.
• A Function is much the same as a Procedure or a
Subroutine, in other programming languages.
14-10-2022 meghav@kannuruniv.ac.in 13
Function Invocation
• The code inside the function will execute when
"something" invokes (calls) the function:
• When an event occurs (when a user clicks a button)
• When it is invoked (called) from JavaScript code
• Automatically (self invoked)
• You will learn a lot more about function invocation later
in this tutorial.
14-10-2022 meghav@kannuruniv.ac.in 14
Function Return
• When JavaScript reaches a return statement, the function will stop
executing.
• If the function was invoked from a statement, JavaScript will "return"
to execute the code after the invoking statement.
• Functions often compute a return value. The return value is
"returned" back to the "caller":
14-10-2022 meghav@kannuruniv.ac.in 15
Example
Calculate the product of two numbers, and return the result:
let x=myFunction(4,3);//Function is called, return value will end up in x
function myFunction(a, b) {
return a * b; //Function returns the product of a and b
}
The result in x will be:
12
14-10-2022 meghav@kannuruniv.ac.in 16
The () Operator Invokes the Function
• Using the example above, toCelsius refers to the function object, and
toCelsius() refers to the function result.
• Accessing a function without () will return the function object instead
of the function result.
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
document.getElementById("demo").innerHTML =
toCelsius;
14-10-2022 meghav@kannuruniv.ac.in 17
Functions Used as Variable Values
• Functions can be used the same way as you use variables, in all types
of formulas, assignments, and calculations.
14-10-2022 meghav@kannuruniv.ac.in 18
JavaScript Objects
• Real Life Objects, Properties, and Methods
• In real life, a car is an object.
• A car has properties like weight and color,
and methods like start and stop:
14-10-2022 meghav@kannuruniv.ac.in 19
Object Properties Methods
Car
car.name = Fiat
car.model = 500
car.weight = 850kg
car.color = white
car.start()
car.drive()
car.brake()
car.stop()
All cars have the same properties, but the property values differ from car to car.
All cars have the same methods, but the methods are performed at different
times.
14-10-2022 meghav@kannuruniv.ac.in 20
JavaScript Objects
• You have already learned that JavaScript variables are
containers for data values.
• This code assigns a simple value (Fiat) to
a variable named car:
let car = "Fiat";
• Objects are variables too. But objects can contain many
values.
• This code assigns many values (Fiat, 500, white) to
a variable named car:
• const car = {type:"Fiat", model:"500", color:"white"};
14-10-2022 meghav@kannuruniv.ac.in 21
JavaScript Objects
• The values are written as name:value pairs (name and
value separated by a colon)
• Object Definition
• You define (and create) a JavaScript object with an
object literal:
• const person = {firstName:"John", lastName:"Doe",
age:50, eyeColor:"blue"};
14-10-2022 meghav@kannuruniv.ac.in 22
JavaScript Objects
• Spaces and line breaks are not important.
• An object definition can span multiple lines:
• Example
• const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
14-10-2022 meghav@kannuruniv.ac.in 23
Object Properties
• The name:values pairs in JavaScript objects are
called properties:
Property Property Value
firstName John
lastName Doe
age 50
eyeColor blue
14-10-2022 meghav@kannuruniv.ac.in 24
Accessing Object Properties
• You can access object properties in two ways:
objectName.propertyName
Or
objectName["propertyName"]
Example1
person.lastName;
Example2
person["lastName"];
14-10-2022 meghav@kannuruniv.ac.in 25
Object Methods
• Objects can also have methods.
• Methods are actions that can be performed on objects.
• Methods are stored in properties as function
definitions.
• Property Property Value
firstName John
lastName Doe
age 50
eyeColor blue
fullName function() {return this.firstName + " " + this.lastName;}
14-10-2022 meghav@kannuruniv.ac.in 26
Object Methods
• A method is a function stored as a property.
const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
14-10-2022 meghav@kannuruniv.ac.in 27
In the example above, this refers to the person object.
I.E. this.firstName means the firstName property of this.
I.E. this.firstName means the firstName property of person.
• In JavaScript, the this keyword refers to an object.
• Which object depends on how this is being invoked (used or called).
• The this keyword refers to different objects depending on how it is used:
14-10-2022 meghav@kannuruniv.ac.in 28
The this Keyword
• In a function definition, this refers to the "owner" of the function.
• In the example above, this is the person object that "owns" the
fullName function.
• In other words, this.firstName means the firstName property of this
object.
14-10-2022 meghav@kannuruniv.ac.in 29
Accessing Object Methods
• You access an object method with the following syntax:
objectName.methodName()
14-10-2022 meghav@kannuruniv.ac.in 30
JavaScript Arrays
• An array is a special variable, which can hold more than one
value:
const cars = ["Saab", "Volvo", "BMW"];
Eg:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrays</h2>
<p id="demo"></p>
<script>
const cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
</script>
</body>
</html>
14-10-2022 meghav@kannuruniv.ac.in 31
Why Use Arrays?
• If you have a list of items (a list of car names, for
example), storing the cars in single variables could look
like this:
let car1 = "Saab";
let car2 = "Volvo";
let car3 = "BMW";
• An array can hold many values under a single name,
and you can access the values by referring to an index
number.
14-10-2022 meghav@kannuruniv.ac.in 32
Creating an Array
• Using an array literal is the easiest way to create a
JavaScript Array.
• Syntax:
const array_name = [item1, item2, ...];
• It is a common practice to declare arrays with
the const keyword.
• Example
• const cars = ["Saab", "Volvo", "BMW"];
14-10-2022 meghav@kannuruniv.ac.in 33
Creating an Array
• Spaces and line breaks are not important. A declaration can
span multiple lines:
const cars = [
"Saab",
"Volvo",
"BMW"
];
• Example
const cars = [];
cars[0]= "Saab";
cars[1]= "Volvo";
cars[2]= "BMW";
14-10-2022 meghav@kannuruniv.ac.in 34
Using the JavaScript Keyword new
• The following example also creates an Array, and
assigns values to it:
• Example
const cars = new Array("Saab", "Volvo", "BMW");
• The two examples above do exactly the same.
• There is no need to use new Array().
• For simplicity, readability and execution speed, use the array literal
method.
14-10-2022 meghav@kannuruniv.ac.in 35
Accessing Array Elements
• You access an array element by referring to the index
number:
const cars = ["Saab", "Volvo", "BMW"];
let car = cars[0];
14-10-2022 meghav@kannuruniv.ac.in 36
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrays</h2>
<p>JavaScript array elements are accessed using numeric indexes
(starting from 0).</p>
<p id="demo"></p>
<script>
const cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars[0];
</script>
</body>
</html>
JavaScript Arrays
JavaScript array elements are accessed using numeric indexes
(starting from 0).
Saab
14-10-2022 meghav@kannuruniv.ac.in 37
• Note: Array indexes start with 0.
• [0] is the first element. [1] is the second element.
Changing an Array Element
• This statement changes the value of the first element in cars:
cars[0] = "Opel";
Example
const cars = ["Saab", "Volvo", "BMW"];
cars[0] = "Opel";
14-10-2022 meghav@kannuruniv.ac.in 38
Access the Full Array
• With JavaScript, the full array can be accessed by
referring to the array name:
• Example
• const cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
14-10-2022 meghav@kannuruniv.ac.in 39
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrays</h2>
<p id="demo"></p>
<script>
const cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
</script>
</body>
</html>
JavaScript Arrays
Saab,Volvo,BMW
14-10-2022 meghav@kannuruniv.ac.in 40
Arrays are Objects
• Arrays are a special type of objects. The typeof operator in JavaScript
returns "object" for arrays.
• But, JavaScript arrays are best described as arrays.
• Arrays use numbers to access its "elements". In this example,
person[0] returns John:
• Array:
const person = ["John", "Doe", 46];
• Objects use names to access its "members". In this example,
person.firstName returns John:
14-10-2022 meghav@kannuruniv.ac.in 41
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrays</h2>
<p>Arrays use numbers to access its elements.</p>
<p id="demo"></p>
<script>
const person = ["John", "Doe", 46];
document.getElementById("demo").innerHTML = person[0];
</script>
</body>
</html>
JavaScript Arrays
Arrays use numbers to access its elements.
John
14-10-2022 meghav@kannuruniv.ac.in 42
• Object:
const person = {firstName:"John", lastName:"Doe",
age:46};
14-10-2022 meghav@kannuruniv.ac.in 43
​<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Objects</h2>
<p>JavaScript uses names to access object properties.</p>
<p id="demo"></p>
<script>
const person = {firstName:"John", lastName:"Doe", age:46};
document.getElementById("demo").innerHTML = person.firstName;
</script>
</body>
</html>
JavaScript Objects
JavaScript uses names to access object properties.
John
14-10-2022 meghav@kannuruniv.ac.in 44
Array Elements Can Be Objects
• JavaScript variables can be objects. Arrays are special
kinds of objects.
• Because of this, you can have variables of different
types in the same Array.
• You can have objects in an Array. You can have
functions in an Array. You can have arrays in an Array:
myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myCars;
14-10-2022 meghav@kannuruniv.ac.in 45
Array Properties and Methods
• The real strength of JavaScript arrays are the built-in
array properties and methods:
cars.length // Returns the number of elements
cars.sort() // Sorts the array
14-10-2022 meghav@kannuruniv.ac.in 46
The length Property
• The length property of an array returns the length of an array (the
number of array elements).
• Example
const fruits =
["Banana", "Orange", "Apple", "Mango"];
let length = fruits.length;
JavaScript Arrays
The length property returns the length of an array.
4
The length property is always one more than the highest array index.
14-10-2022 meghav@kannuruniv.ac.in 47
Accessing the First Array Element
• Example
const fruits =
["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits[0];
14-10-2022 meghav@kannuruniv.ac.in 48
Looping Array Elements
• Looping Array Elements
• Example
const fruits =
["Banana", "Orange", "Apple", "Mango"];
let fLen = fruits.length;
let text = "<ul>";
for (let i = 0; i < fLen; i++) {
text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";
14-10-2022 meghav@kannuruniv.ac.in 49
• You can also use the Array.forEach() function:
const fruits =
["Banana", "Orange", "Apple", "Mango"];
let text = "<ul>";
fruits.forEach(myFunction);
text += "</ul>";
function myFunction(value) {
text += "<li>" + value + "</li>";
}
14-10-2022 meghav@kannuruniv.ac.in 50
Adding Array Elements
• The easiest way to add a new element to an array is using the push()
method:
• Example
const fruits = ["Banana", "Orange", "Apple"];
fruits.push("Lemon"); // Adds a new element (Lemon)
to fruits
New element can also be added to an array using the length property:
const fruits = ["Banana", "Orange", "Apple"];
fruits[fruits.length] = "Lemon"; // Adds "Lemon" to
fruits
14-10-2022 meghav@kannuruniv.ac.in 51
REFERENCES
1. Jeffrey C. Jackson, Web Technologies: A Computer Science Perspective, Prentice Hall
2. David Flanagan, JavaScript: The Definitive Guide, 6th Edn. O'Reilly Media.2011
3. Bob Breedlove, et al, Web Programming Unleashed, Sams Net Publishing, 1stEdn
4. Steven Holzner, PHP: The Complete Reference, McGraw Hill Professional, 2008
5. Steve Suehring, Tim Converse, Joyce Park, PHP6 and MY SQL Bible, John Wiley & Sons,2009
6. Pedro Teixeira, Instant Node.js Starter, Packt Publishing Ltd., 2013
7. Anthony T. HoldenerIII, Ajax: The Definitive Guide, O’Reilly Media, 2008
8. Nirav Mehta, Choosing an Open Source CMS: Beginner's Guide Packt Publishing Ltd, 2009
9. James Snell, Programming Web Services with SOAP, O'Reilly 2002
10. Jacob Lett , Bootstrap Reference Guide, Bootstrap Creative 2018
11. Maximilian Schwarzmüller, Progressive Web Apps (PWA) - The Complete Guide, Packt Publishing
2018
12. Mahesh Panhale, Beginning Hybrid Mobile Application Development, Apress 2016
14-10-2022 meghav@kannuruniv.ac.in 52

More Related Content

Similar to JavaScript- Functions and arrays.pptx

Brief Introduction on JavaScript - Internship Presentation - Week4
Brief Introduction on JavaScript - Internship Presentation - Week4Brief Introduction on JavaScript - Internship Presentation - Week4
Brief Introduction on JavaScript - Internship Presentation - Week4Devang Garach
 
JavaScript Interview Questions Part - 1.pdf
JavaScript Interview Questions Part - 1.pdfJavaScript Interview Questions Part - 1.pdf
JavaScript Interview Questions Part - 1.pdfkatarichallenge
 
Week 8
Week 8Week 8
Week 8A VD
 
Javascript sivasoft
Javascript sivasoftJavascript sivasoft
Javascript sivasoftch samaram
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...Fabio Franzini
 
Web Host_G4.pptx
Web Host_G4.pptxWeb Host_G4.pptx
Web Host_G4.pptxRNithish1
 
The curious Life of JavaScript - Talk at SI-SE 2015
The curious Life of JavaScript - Talk at SI-SE 2015The curious Life of JavaScript - Talk at SI-SE 2015
The curious Life of JavaScript - Talk at SI-SE 2015jbandi
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiRan Mizrahi
 
Javascriptinobject orientedway-090512225827-phpapp02
Javascriptinobject orientedway-090512225827-phpapp02Javascriptinobject orientedway-090512225827-phpapp02
Javascriptinobject orientedway-090512225827-phpapp02Sopheak Sem
 
Functions and Objects in JavaScript
Functions and Objects in JavaScript Functions and Objects in JavaScript
Functions and Objects in JavaScript Dhananjay Kumar
 
Fii Practic Frontend - BeeNear - laborator3
Fii Practic Frontend - BeeNear - laborator3Fii Practic Frontend - BeeNear - laborator3
Fii Practic Frontend - BeeNear - laborator3BeeNear
 
HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPT
HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPTHSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPT
HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPTAAFREEN SHAIKH
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyDavid Padbury
 

Similar to JavaScript- Functions and arrays.pptx (20)

Java script
Java scriptJava script
Java script
 
Brief Introduction on JavaScript - Internship Presentation - Week4
Brief Introduction on JavaScript - Internship Presentation - Week4Brief Introduction on JavaScript - Internship Presentation - Week4
Brief Introduction on JavaScript - Internship Presentation - Week4
 
JavaScript Interview Questions Part - 1.pdf
JavaScript Interview Questions Part - 1.pdfJavaScript Interview Questions Part - 1.pdf
JavaScript Interview Questions Part - 1.pdf
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Week 8
Week 8Week 8
Week 8
 
Javascript sivasoft
Javascript sivasoftJavascript sivasoft
Javascript sivasoft
 
JavaScript_III.pptx
JavaScript_III.pptxJavaScript_III.pptx
JavaScript_III.pptx
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
 
Web Host_G4.pptx
Web Host_G4.pptxWeb Host_G4.pptx
Web Host_G4.pptx
 
wp-UNIT_III.pptx
wp-UNIT_III.pptxwp-UNIT_III.pptx
wp-UNIT_III.pptx
 
[2015/2016] JavaScript
[2015/2016] JavaScript[2015/2016] JavaScript
[2015/2016] JavaScript
 
Lecture 6: Client Side Programming 2
Lecture 6: Client Side Programming 2Lecture 6: Client Side Programming 2
Lecture 6: Client Side Programming 2
 
The curious Life of JavaScript - Talk at SI-SE 2015
The curious Life of JavaScript - Talk at SI-SE 2015The curious Life of JavaScript - Talk at SI-SE 2015
The curious Life of JavaScript - Talk at SI-SE 2015
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
 
Javascriptinobject orientedway-090512225827-phpapp02
Javascriptinobject orientedway-090512225827-phpapp02Javascriptinobject orientedway-090512225827-phpapp02
Javascriptinobject orientedway-090512225827-phpapp02
 
Java script
Java scriptJava script
Java script
 
Functions and Objects in JavaScript
Functions and Objects in JavaScript Functions and Objects in JavaScript
Functions and Objects in JavaScript
 
Fii Practic Frontend - BeeNear - laborator3
Fii Practic Frontend - BeeNear - laborator3Fii Practic Frontend - BeeNear - laborator3
Fii Practic Frontend - BeeNear - laborator3
 
HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPT
HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPTHSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPT
HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPT
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
 

More from Megha V

Soft Computing Techniques_Part 1.pptx
Soft Computing Techniques_Part 1.pptxSoft Computing Techniques_Part 1.pptx
Soft Computing Techniques_Part 1.pptxMegha V
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScriptMegha V
 
Python Exception Handling
Python Exception HandlingPython Exception Handling
Python Exception HandlingMegha V
 
Python- Regular expression
Python- Regular expressionPython- Regular expression
Python- Regular expressionMegha V
 
File handling in Python
File handling in PythonFile handling in Python
File handling in PythonMegha V
 
Python programming -Tuple and Set Data type
Python programming -Tuple and Set Data typePython programming -Tuple and Set Data type
Python programming -Tuple and Set Data typeMegha V
 
Python programming –part 7
Python programming –part 7Python programming –part 7
Python programming –part 7Megha V
 
Python programming Part -6
Python programming Part -6Python programming Part -6
Python programming Part -6Megha V
 
Python programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operationsPython programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operationsMegha V
 
Python programming- Part IV(Functions)
Python programming- Part IV(Functions)Python programming- Part IV(Functions)
Python programming- Part IV(Functions)Megha V
 
Python programming –part 3
Python programming –part 3Python programming –part 3
Python programming –part 3Megha V
 
Parts of python programming language
Parts of python programming languageParts of python programming language
Parts of python programming languageMegha V
 
Python programming
Python programmingPython programming
Python programmingMegha V
 
Strassen's matrix multiplication
Strassen's matrix multiplicationStrassen's matrix multiplication
Strassen's matrix multiplicationMegha V
 
Solving recurrences
Solving recurrencesSolving recurrences
Solving recurrencesMegha V
 
Algorithm Analysis
Algorithm AnalysisAlgorithm Analysis
Algorithm AnalysisMegha V
 
Algorithm analysis and design
Algorithm analysis and designAlgorithm analysis and design
Algorithm analysis and designMegha V
 
Genetic algorithm
Genetic algorithmGenetic algorithm
Genetic algorithmMegha V
 
UGC NET Paper 1 ICT Memory and data
UGC NET Paper 1 ICT Memory and data  UGC NET Paper 1 ICT Memory and data
UGC NET Paper 1 ICT Memory and data Megha V
 
Seminar presentation on OpenGL
Seminar presentation on OpenGLSeminar presentation on OpenGL
Seminar presentation on OpenGLMegha V
 

More from Megha V (20)

Soft Computing Techniques_Part 1.pptx
Soft Computing Techniques_Part 1.pptxSoft Computing Techniques_Part 1.pptx
Soft Computing Techniques_Part 1.pptx
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Python Exception Handling
Python Exception HandlingPython Exception Handling
Python Exception Handling
 
Python- Regular expression
Python- Regular expressionPython- Regular expression
Python- Regular expression
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
Python programming -Tuple and Set Data type
Python programming -Tuple and Set Data typePython programming -Tuple and Set Data type
Python programming -Tuple and Set Data type
 
Python programming –part 7
Python programming –part 7Python programming –part 7
Python programming –part 7
 
Python programming Part -6
Python programming Part -6Python programming Part -6
Python programming Part -6
 
Python programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operationsPython programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operations
 
Python programming- Part IV(Functions)
Python programming- Part IV(Functions)Python programming- Part IV(Functions)
Python programming- Part IV(Functions)
 
Python programming –part 3
Python programming –part 3Python programming –part 3
Python programming –part 3
 
Parts of python programming language
Parts of python programming languageParts of python programming language
Parts of python programming language
 
Python programming
Python programmingPython programming
Python programming
 
Strassen's matrix multiplication
Strassen's matrix multiplicationStrassen's matrix multiplication
Strassen's matrix multiplication
 
Solving recurrences
Solving recurrencesSolving recurrences
Solving recurrences
 
Algorithm Analysis
Algorithm AnalysisAlgorithm Analysis
Algorithm Analysis
 
Algorithm analysis and design
Algorithm analysis and designAlgorithm analysis and design
Algorithm analysis and design
 
Genetic algorithm
Genetic algorithmGenetic algorithm
Genetic algorithm
 
UGC NET Paper 1 ICT Memory and data
UGC NET Paper 1 ICT Memory and data  UGC NET Paper 1 ICT Memory and data
UGC NET Paper 1 ICT Memory and data
 
Seminar presentation on OpenGL
Seminar presentation on OpenGLSeminar presentation on OpenGL
Seminar presentation on OpenGL
 

Recently uploaded

Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfjimielynbastida
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Neo4j
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsAndrey Dotsenko
 

Recently uploaded (20)

Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdf
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 

JavaScript- Functions and arrays.pptx

  • 1. JavaScript Functions, Arrays Megha V Assistant Professor Dept of IT, Kannur University 14-10-2022 meghav@kannuruniv.ac.in 1
  • 2. JavaScript Statements let x, y, z; // Statement 1 x = 5; // Statement 2 y = 6; // Statement 3 z = x + y; // Statement 4 14-10-2022 meghav@kannuruniv.ac.in 2
  • 3. JavaScript Programs • A computer program is a list of "instructions" to be "executed" by a computer. • In a programming language, these programming instructions are called statements. • A JavaScript program is a list of programming statements. • In HTML, JavaScript programs are executed by the web browser. 14-10-2022 meghav@kannuruniv.ac.in 3
  • 4. JavaScript Statements • JavaScript statements are composed of: • Values, Operators, Expressions, Keywords, and Comments. • This statement tells the browser to write "Hello Dolly." inside an HTML element with id="demo": document.getElementById("demo").innerHTML = "Hello Dolly."; 14-10-2022 meghav@kannuruniv.ac.in 4
  • 5. • Most JavaScript programs contain many JavaScript statements. • The statements are executed, one by one, in the same order as they are written. • JavaScript programs (and JavaScript statements) are often called JavaScript code. JavaScript Statements 14-10-2022 meghav@kannuruniv.ac.in 5
  • 6. Semicolons ; • Semicolons separate JavaScript statements. • Add a semicolon at the end of each executable statement: • Examples let a, b, c; // Declare 3 variables a = 5; // Assign the value 5 to a b = 6; // Assign the value 6 to b c = a + b; // Assign the sum of a and b to c 14-10-2022 meghav@kannuruniv.ac.in 6
  • 7. <!DOCTYPE html> <html> <body> <h2>JavaScript Statements</h2> <p>JavaScript statements are separated by semicolons.</p> <p id="demo1"></p> <script> let a, b, c; a = 5; b = 6; c = a + b; document.getElementById("demo1").innerHTML = c; </script> </body> </html> JavaScript Statements JavaScript statements are separated by semicolons. 11 14-10-2022 meghav@kannuruniv.ac.in 7
  • 8. • When separated by semicolons, multiple statements on one line are allowed: a = 5; b = 6; c = a + b; JavaScript White Space • JavaScript ignores multiple spaces. You can add white space to your script to make it more readable. • The following lines are equivalent: let person = "Hege"; let person="Hege"; • A good practice is to put spaces around operators ( = + - * / ): let x = y + z; 14-10-2022 meghav@kannuruniv.ac.in 8
  • 9. 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 (calls it). 14-10-2022 meghav@kannuruniv.ac.in 9
  • 10. <!DOCTYPE html> <html> <body> <h2>JavaScript Functions</h2> <p>This example calls a function which performs a calculation, and returns the result:</p> <p id="demo"></p> <script> function myFunction(p1, p2) { return p1 * p2; } document.getElementById("demo").innerHTML = myFunction(4, 3); </script> </body> </html> JavaScript Functions This example calls a function which performs a calculation, and returns the result: 12 14-10-2022 meghav@kannuruniv.ac.in 10
  • 11. JavaScript Function Syntax • A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses (). • Function names can contain letters, digits, underscores, and dollar signs (same rules as variables). • The parentheses may include parameter names separated by commas: • (parameter1, parameter2, ...) 14-10-2022 meghav@kannuruniv.ac.in 11
  • 12. The code to be executed, by the function, is placed inside curly brackets: {} function name(parameter1, parameter2, parameter3) { // code to be executed } JavaScript Function Syntax 14-10-2022 meghav@kannuruniv.ac.in 12
  • 13. • Function parameters are listed inside the parentheses () in the function definition. • Function arguments are the values received by the function when it is invoked. • Inside the function, the arguments (the parameters) behave as local variables. • A Function is much the same as a Procedure or a Subroutine, in other programming languages. 14-10-2022 meghav@kannuruniv.ac.in 13
  • 14. Function Invocation • The code inside the function will execute when "something" invokes (calls) the function: • When an event occurs (when a user clicks a button) • When it is invoked (called) from JavaScript code • Automatically (self invoked) • You will learn a lot more about function invocation later in this tutorial. 14-10-2022 meghav@kannuruniv.ac.in 14
  • 15. Function Return • When JavaScript reaches a return statement, the function will stop executing. • If the function was invoked from a statement, JavaScript will "return" to execute the code after the invoking statement. • Functions often compute a return value. The return value is "returned" back to the "caller": 14-10-2022 meghav@kannuruniv.ac.in 15
  • 16. Example Calculate the product of two numbers, and return the result: let x=myFunction(4,3);//Function is called, return value will end up in x function myFunction(a, b) { return a * b; //Function returns the product of a and b } The result in x will be: 12 14-10-2022 meghav@kannuruniv.ac.in 16
  • 17. The () Operator Invokes the Function • Using the example above, toCelsius refers to the function object, and toCelsius() refers to the function result. • Accessing a function without () will return the function object instead of the function result. function toCelsius(fahrenheit) { return (5/9) * (fahrenheit-32); } document.getElementById("demo").innerHTML = toCelsius; 14-10-2022 meghav@kannuruniv.ac.in 17
  • 18. Functions Used as Variable Values • Functions can be used the same way as you use variables, in all types of formulas, assignments, and calculations. 14-10-2022 meghav@kannuruniv.ac.in 18
  • 19. JavaScript Objects • Real Life Objects, Properties, and Methods • In real life, a car is an object. • A car has properties like weight and color, and methods like start and stop: 14-10-2022 meghav@kannuruniv.ac.in 19
  • 20. Object Properties Methods Car car.name = Fiat car.model = 500 car.weight = 850kg car.color = white car.start() car.drive() car.brake() car.stop() All cars have the same properties, but the property values differ from car to car. All cars have the same methods, but the methods are performed at different times. 14-10-2022 meghav@kannuruniv.ac.in 20
  • 21. JavaScript Objects • You have already learned that JavaScript variables are containers for data values. • This code assigns a simple value (Fiat) to a variable named car: let car = "Fiat"; • Objects are variables too. But objects can contain many values. • This code assigns many values (Fiat, 500, white) to a variable named car: • const car = {type:"Fiat", model:"500", color:"white"}; 14-10-2022 meghav@kannuruniv.ac.in 21
  • 22. JavaScript Objects • The values are written as name:value pairs (name and value separated by a colon) • Object Definition • You define (and create) a JavaScript object with an object literal: • const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}; 14-10-2022 meghav@kannuruniv.ac.in 22
  • 23. JavaScript Objects • Spaces and line breaks are not important. • An object definition can span multiple lines: • Example • const person = { firstName: "John", lastName: "Doe", age: 50, eyeColor: "blue" }; 14-10-2022 meghav@kannuruniv.ac.in 23
  • 24. Object Properties • The name:values pairs in JavaScript objects are called properties: Property Property Value firstName John lastName Doe age 50 eyeColor blue 14-10-2022 meghav@kannuruniv.ac.in 24
  • 25. Accessing Object Properties • You can access object properties in two ways: objectName.propertyName Or objectName["propertyName"] Example1 person.lastName; Example2 person["lastName"]; 14-10-2022 meghav@kannuruniv.ac.in 25
  • 26. Object Methods • Objects can also have methods. • Methods are actions that can be performed on objects. • Methods are stored in properties as function definitions. • Property Property Value firstName John lastName Doe age 50 eyeColor blue fullName function() {return this.firstName + " " + this.lastName;} 14-10-2022 meghav@kannuruniv.ac.in 26
  • 27. Object Methods • A method is a function stored as a property. const person = { firstName: "John", lastName : "Doe", id : 5566, fullName : function() { return this.firstName + " " + this.lastName; } }; 14-10-2022 meghav@kannuruniv.ac.in 27
  • 28. In the example above, this refers to the person object. I.E. this.firstName means the firstName property of this. I.E. this.firstName means the firstName property of person. • In JavaScript, the this keyword refers to an object. • Which object depends on how this is being invoked (used or called). • The this keyword refers to different objects depending on how it is used: 14-10-2022 meghav@kannuruniv.ac.in 28
  • 29. The this Keyword • In a function definition, this refers to the "owner" of the function. • In the example above, this is the person object that "owns" the fullName function. • In other words, this.firstName means the firstName property of this object. 14-10-2022 meghav@kannuruniv.ac.in 29
  • 30. Accessing Object Methods • You access an object method with the following syntax: objectName.methodName() 14-10-2022 meghav@kannuruniv.ac.in 30
  • 31. JavaScript Arrays • An array is a special variable, which can hold more than one value: const cars = ["Saab", "Volvo", "BMW"]; Eg: <!DOCTYPE html> <html> <body> <h2>JavaScript Arrays</h2> <p id="demo"></p> <script> const cars = ["Saab", "Volvo", "BMW"]; document.getElementById("demo").innerHTML = cars; </script> </body> </html> 14-10-2022 meghav@kannuruniv.ac.in 31
  • 32. Why Use Arrays? • If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this: let car1 = "Saab"; let car2 = "Volvo"; let car3 = "BMW"; • An array can hold many values under a single name, and you can access the values by referring to an index number. 14-10-2022 meghav@kannuruniv.ac.in 32
  • 33. Creating an Array • Using an array literal is the easiest way to create a JavaScript Array. • Syntax: const array_name = [item1, item2, ...]; • It is a common practice to declare arrays with the const keyword. • Example • const cars = ["Saab", "Volvo", "BMW"]; 14-10-2022 meghav@kannuruniv.ac.in 33
  • 34. Creating an Array • Spaces and line breaks are not important. A declaration can span multiple lines: const cars = [ "Saab", "Volvo", "BMW" ]; • Example const cars = []; cars[0]= "Saab"; cars[1]= "Volvo"; cars[2]= "BMW"; 14-10-2022 meghav@kannuruniv.ac.in 34
  • 35. Using the JavaScript Keyword new • The following example also creates an Array, and assigns values to it: • Example const cars = new Array("Saab", "Volvo", "BMW"); • The two examples above do exactly the same. • There is no need to use new Array(). • For simplicity, readability and execution speed, use the array literal method. 14-10-2022 meghav@kannuruniv.ac.in 35
  • 36. Accessing Array Elements • You access an array element by referring to the index number: const cars = ["Saab", "Volvo", "BMW"]; let car = cars[0]; 14-10-2022 meghav@kannuruniv.ac.in 36
  • 37. <!DOCTYPE html> <html> <body> <h2>JavaScript Arrays</h2> <p>JavaScript array elements are accessed using numeric indexes (starting from 0).</p> <p id="demo"></p> <script> const cars = ["Saab", "Volvo", "BMW"]; document.getElementById("demo").innerHTML = cars[0]; </script> </body> </html> JavaScript Arrays JavaScript array elements are accessed using numeric indexes (starting from 0). Saab 14-10-2022 meghav@kannuruniv.ac.in 37
  • 38. • Note: Array indexes start with 0. • [0] is the first element. [1] is the second element. Changing an Array Element • This statement changes the value of the first element in cars: cars[0] = "Opel"; Example const cars = ["Saab", "Volvo", "BMW"]; cars[0] = "Opel"; 14-10-2022 meghav@kannuruniv.ac.in 38
  • 39. Access the Full Array • With JavaScript, the full array can be accessed by referring to the array name: • Example • const cars = ["Saab", "Volvo", "BMW"]; document.getElementById("demo").innerHTML = cars; 14-10-2022 meghav@kannuruniv.ac.in 39
  • 40. <!DOCTYPE html> <html> <body> <h2>JavaScript Arrays</h2> <p id="demo"></p> <script> const cars = ["Saab", "Volvo", "BMW"]; document.getElementById("demo").innerHTML = cars; </script> </body> </html> JavaScript Arrays Saab,Volvo,BMW 14-10-2022 meghav@kannuruniv.ac.in 40
  • 41. Arrays are Objects • Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays. • But, JavaScript arrays are best described as arrays. • Arrays use numbers to access its "elements". In this example, person[0] returns John: • Array: const person = ["John", "Doe", 46]; • Objects use names to access its "members". In this example, person.firstName returns John: 14-10-2022 meghav@kannuruniv.ac.in 41
  • 42. <!DOCTYPE html> <html> <body> <h2>JavaScript Arrays</h2> <p>Arrays use numbers to access its elements.</p> <p id="demo"></p> <script> const person = ["John", "Doe", 46]; document.getElementById("demo").innerHTML = person[0]; </script> </body> </html> JavaScript Arrays Arrays use numbers to access its elements. John 14-10-2022 meghav@kannuruniv.ac.in 42
  • 43. • Object: const person = {firstName:"John", lastName:"Doe", age:46}; 14-10-2022 meghav@kannuruniv.ac.in 43
  • 44. ​<!DOCTYPE html> <html> <body> <h2>JavaScript Objects</h2> <p>JavaScript uses names to access object properties.</p> <p id="demo"></p> <script> const person = {firstName:"John", lastName:"Doe", age:46}; document.getElementById("demo").innerHTML = person.firstName; </script> </body> </html> JavaScript Objects JavaScript uses names to access object properties. John 14-10-2022 meghav@kannuruniv.ac.in 44
  • 45. Array Elements Can Be Objects • JavaScript variables can be objects. Arrays are special kinds of objects. • Because of this, you can have variables of different types in the same Array. • You can have objects in an Array. You can have functions in an Array. You can have arrays in an Array: myArray[0] = Date.now; myArray[1] = myFunction; myArray[2] = myCars; 14-10-2022 meghav@kannuruniv.ac.in 45
  • 46. Array Properties and Methods • The real strength of JavaScript arrays are the built-in array properties and methods: cars.length // Returns the number of elements cars.sort() // Sorts the array 14-10-2022 meghav@kannuruniv.ac.in 46
  • 47. The length Property • The length property of an array returns the length of an array (the number of array elements). • Example const fruits = ["Banana", "Orange", "Apple", "Mango"]; let length = fruits.length; JavaScript Arrays The length property returns the length of an array. 4 The length property is always one more than the highest array index. 14-10-2022 meghav@kannuruniv.ac.in 47
  • 48. Accessing the First Array Element • Example const fruits = ["Banana", "Orange", "Apple", "Mango"]; let fruit = fruits[0]; 14-10-2022 meghav@kannuruniv.ac.in 48
  • 49. Looping Array Elements • Looping Array Elements • Example const fruits = ["Banana", "Orange", "Apple", "Mango"]; let fLen = fruits.length; let text = "<ul>"; for (let i = 0; i < fLen; i++) { text += "<li>" + fruits[i] + "</li>"; } text += "</ul>"; 14-10-2022 meghav@kannuruniv.ac.in 49
  • 50. • You can also use the Array.forEach() function: const fruits = ["Banana", "Orange", "Apple", "Mango"]; let text = "<ul>"; fruits.forEach(myFunction); text += "</ul>"; function myFunction(value) { text += "<li>" + value + "</li>"; } 14-10-2022 meghav@kannuruniv.ac.in 50
  • 51. Adding Array Elements • The easiest way to add a new element to an array is using the push() method: • Example const fruits = ["Banana", "Orange", "Apple"]; fruits.push("Lemon"); // Adds a new element (Lemon) to fruits New element can also be added to an array using the length property: const fruits = ["Banana", "Orange", "Apple"]; fruits[fruits.length] = "Lemon"; // Adds "Lemon" to fruits 14-10-2022 meghav@kannuruniv.ac.in 51
  • 52. REFERENCES 1. Jeffrey C. Jackson, Web Technologies: A Computer Science Perspective, Prentice Hall 2. David Flanagan, JavaScript: The Definitive Guide, 6th Edn. O'Reilly Media.2011 3. Bob Breedlove, et al, Web Programming Unleashed, Sams Net Publishing, 1stEdn 4. Steven Holzner, PHP: The Complete Reference, McGraw Hill Professional, 2008 5. Steve Suehring, Tim Converse, Joyce Park, PHP6 and MY SQL Bible, John Wiley & Sons,2009 6. Pedro Teixeira, Instant Node.js Starter, Packt Publishing Ltd., 2013 7. Anthony T. HoldenerIII, Ajax: The Definitive Guide, O’Reilly Media, 2008 8. Nirav Mehta, Choosing an Open Source CMS: Beginner's Guide Packt Publishing Ltd, 2009 9. James Snell, Programming Web Services with SOAP, O'Reilly 2002 10. Jacob Lett , Bootstrap Reference Guide, Bootstrap Creative 2018 11. Maximilian Schwarzmüller, Progressive Web Apps (PWA) - The Complete Guide, Packt Publishing 2018 12. Mahesh Panhale, Beginning Hybrid Mobile Application Development, Apress 2016 14-10-2022 meghav@kannuruniv.ac.in 52