0% found this document useful (0 votes)
2 views

JavaScript Lecture

JavaScript is a scripting language developed by Netscape in 1995, primarily used to enhance web pages with interactive features. It has various data types, operators, and methods for manipulating data, as well as control statements and functions for structuring code. The language has evolved through several versions, becoming standardized as ECMAScript, and includes modern features like classes and modules for better code organization.

Uploaded by

temisoreidowu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

JavaScript Lecture

JavaScript is a scripting language developed by Netscape in 1995, primarily used to enhance web pages with interactive features. It has various data types, operators, and methods for manipulating data, as well as control statements and functions for structuring code. The language has evolved through several versions, becoming standardized as ECMAScript, and includes modern features like classes and modules for better code organization.

Uploaded by

temisoreidowu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

Introduction to

JavaScript
What is JavaScript?
JavaScript is a scripting language designed for
Web pages by Netscape. It is a programming
language that is used to enhance HTML pages
and make a website responsive
Why Use JavaScript?

JavaScript enhances Web pages with dynamic and


interactive features.
What Can JavaScript Do?

• Adding interactive behavior to web pages


• JavaScript enables shopping carts, form validation,
calculations, special graphic and text effects, image
swapping, image mapping, clocks, and more.
• Building web servers and developing server
applications
History of JavaScript

• JavaScript was invented by Brendan Eich in 1995.


• It was developed for Netscape 2, and became
the ECMA-262 standard in 1997.
History of JavaScript

• After Netscape handed JavaScript over to ECMA,


the Mozilla foundation continued to develop
JavaScript for the Firefox browser. Mozilla's latest
version was 1.8.5. (Identical to ES5).
• Internet Explorer (IE4) was the first browser to
support ECMA-262 Edition 1 (ES1).
JavaScript Versions
• JavaScript was invented by Brendan Eich in 1995, and became an ECMA standard in 1997.
• ECMAScript is the official name of the language.
• ECMAScript versions have been abbreviated to ES1, ES2, ES3, ES5, and ES6.
• Since 2016, versions are named by year (ECMAScript 2016, 2017, 2018, 2019, 2020).
JavaScript Syntax

JavaScript syntax is the set of rules, how JavaScript programs are


constructed. JavaScript uses a C-style syntax, with statements
separated by semicolons and code blocks enclosed in curly braces.
JavaScript
Comments
JavaScript comments are ignored by JS and are not executable.
They are used to explain JavaScript code, and to make it more
readable.
Forms of Commenting
// is used for Single line comment
/*…*/ is used for Multi-line comment
JavaScript Reserved
Words
abstract boolean break byte case catch char class continue const
debugger default delete do double else enum export extends false
final finally float for function goto if implements import in instanceof
int interface long native new null package private protected public
return short static super switch synchronized this throw throws
true try typeof var void while with
JavaScript
Output
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
JavaScript Data Types
Data Types: JavaScript has several data types, including numbers,
strings, bigint, booleans, objects and arrays. It also has a special
type called "undefined" that represents a value that has not been
assigned.
Number
JavaScript Data Types
• for numbers of any kind: integer or floating-point, integers are limited by +(253 – 1).

String

• for strings. A string may have zero or more characters, there’s no separate single-character type.

Boolean

• For true/false .

Null

• for unknown values – a standalone type that has a single value null .

Undefined

• for unassigned values – a standalone type that has a single value .

Objects

• objects are used to store keyed collections of various data and more complex entities.

Bigint

• for integer numbers of arbitrary length and is created by appending n to the end of an integer
JavaScript Data Type Conversion

JavaScript has built-in methods for converting between data types.


JavaScript Data Type Conversion

method description example


toNumber() Converting a value Var x = “3.14”;
to a number
document.getElementById("demo").inne
rHTML = x.toNumber();

Results in 3.14

toString() Converting a value Var x = 123;


to a string
document.getElementById("demo").inne
rHTML = x.toString();

Results in “123”
JavaScript Variables

Variables in JavaScript are containers used to store and manipulate


data. They are declared using the "var", "let", or "const" keyword.
JavaScript Operators
operators examples example
Arithmetic +, - , * x = 3, y = 5
JavaScript has various operators which can be usedz =X +for
y assigning
values, comparing values, performing mathematical and arithmetic
operations and more.==,!=,>
Comparison There are different types of JavaScript
document.write(5==5)
operators: Arithmetic Operators, Assignment Operators,
Assignment Comparison Operators
=, +=, -= and Logical Operators etc.
x =3, y=10
x += y: x= x + y
Logical &&, ||, ! document.write((5>4)||(5+4))
operators types descriptions example
Arithmetic +, - , * Arithmetic Operators are used to x = 3, y = 5
perform arithmetic on numbers z =X + y

Comparison ==,!=,> Comparison operators are used in document.write(5==5)


logical statements to determine
equality or difference between
variables or values.

Assignment =, +=, -= Assignment operators assign values x =3, y=10


to JavaScript variables. x += y: x= x + y

Logical &&, ||, ! Logical operators are used to document.write((5>4)||(5+4))


determine the logic between
variables or values.
JavaScript Statements

JavaScript statements are instructions that tell the browser to


perform a specific task. JavaScript statements are composed of:
Values, Operators, Expressions, Keywords, and Comments.
Control Statements
Statements that are used to control the flow of execution in a
script or flow of program based on certain conditions are known as
control statements.
Control Statements
statement description syntax
If statement It is used to specify a block if (condition) {
of code to be executed, if a // block of code to be
specified condition is true executed if the condition is
true
}
Else statement It is used to specify a block if (condition) {
of code to be executed, if // block of code to be
the same condition is false executed if the condition is
true
} else {
// block of code to be
executed if the condition is
false
}
statement description syntax
Else-if statement It is used to specify a new if (condition1) {
condition if the first condition is // block of code to be executed if
false. condition1 is true
} else if (condition2) {
// block of code to be executed if
the condition1 is false and
condition2 is true
} else {
// block of code to be executed if
the condition1 is false and
condition2 is false
}

Switch Statement used to perform different actions switch(expression) {


based on different conditions. case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
JavaScript Functions
Functions are reusable blocks of code that can be called to perform
a specific task. They are defined using the "function" keyword and
can take parameters and return a value.
Its syntax is: the function is defined with the function keyword,
followed by a name, followed by parenthesis()
JavaScript Functions
Example of Function Code

Function to compute the product of p1 function myFunction(p1, p2) {


and p2 return p1 * p2;
}
Function to convert Fahrenheit to Celsius: function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
document.getElementById("demo").inne
rHTML = toCelsius(77);
Strings and Methods

JavaScript strings are for storing and manipulating text. JavaScript


has a built-in "String" object that has various methods for
manipulating strings.
Strings and Methods
method description example
String Length The length property returns the let text =
length of a string: "ABCDEFGHIJKLMNOPQRSTUVWX
YZ";

document.getElementById("demo
").innerHTML = text.length;
</script>

Results in 26

String Slice slice() extracts a part of a string let text = "Apple, Banana, Kiwi";
and returns the extracted part in a
new string. let part = text.slice(7,13);

document.getElementById("demo
").innerHTML = part;

Results in Banana
Formatting String
Strings also has the template literals (backtick) which uses ${} to
include the variable value within the string.
JavaScript has built-in methods for formatting strings. "toFixed()“
which is used to format a number using fixed-point notation. It can
be used to format a number with a specific number of digits to the
right of the decimal.
• "toPrecision()“ which is used is used to format a number to a
specific precision or length.
Formatting String
method description syntax
Lower case string method As the name implies, you const lowercased =
use string.toLowerCase()
the toLowerCase() string
method to convert strings
to their lowercase version.

Upper case string method Similar to the first const uppercased =


method, toUpperCase is a string.toUpperCase()
string method you use to
convert strings to their
uppercase version.
Formatting String

method description syntax


Replace string method You use the replace string const modified =
method to replace a string.replace(searchValue,
section of a string with a replaceValue)
substring. This way, you
will format the string so
you can modify it.
Number and its methods

JavaScript has a built-in "Number" object that has various methods


for manipulating numbers, such as "toFixed()", "toPrecision()",
"toExponential()", "isNaN()" and "isFinite()".
Number and its methods
method description syntax
Number toFixed The toFixed() method number.toFixed(x)
converts a number to a
string.
This method rounds the
string to a specified
number of decimals.

Number toPrecision The toPrecision() method number.toPrecision(x)


formats a number to a
specified length.
A decimal point and nulls
are added (if needed), to
create the specified
length.
Number and its methods
method description syntax
Number toExponential The toExponential() number.toExponential(x)
method converts a
number into an
exponential notation.
Number isFinite The Number.isFinite() met Number.isFinite(value)
hod returns true if a
number is a finite number.
Infinite (not finite)
numbers are Infinity, -
Infinity, or NaN
Otherwise it returns false.
Arrays and its methods

JavaScript has a built-in "Array" object that can be used to store a


collection of data. It has various methods for manipulating arrays,
such as "push()", "pop()", "slice()“ etc.
Arrays and its methods
method description syntax
Array push The push() method adds array.push(item1, item2,
new items to the end of an ..., itemX)
array.
Array pop The pop() method array.pop()
removes (pops) the last
element of an array.
Array sort The sort() sorts the array.sort(compareFunctio
elements of an array. n)

Array slice The slice() method returns array.slice(start, end)


selected elements in an
array, as a new array.
JS Date & Date
Methods
JavaScript has a built-in "Date" object that can be used to work
with dates and times. It has methods for getting and setting
different parts of the date, such as "getFullYear()", "getMonth()",
and "getDate()". It also has built-in methods for formatting dates,
such as "toUTCString()".
JS Date & Date
Methods
method description syntax
getDate() Returns the day of the Date.getDate()
month (from 1-31)

getMonth() Returns the month (from 0- Date.getMonth()


11)

getFullYear() Returns the year Date.getFullYear()

toUTCString() Returns a date object as a Date.toUTCString()


string, according to UTC.
Mapping datatypes
A Map holds key-value pairs where the keys can be any datatype. A
Map remembers the original insertion order of the keys. JavaScript
has several built-in methods for mapping data types, such as
"map()" and “get()“.
Mapping datatypes
method description syntax
new Map() Creates a new Map object const values = new Map([
[“x”, y],
]);
get() Gets the value for a key in a values.get(“x");
Map
Map.has() Returns true if a key exists in a values.has(“x");
Map
JS Iterables
Iterable objects are objects that can be iterated iver with for..of.
Technically, iterables must implement the Symbol.iterator.
method description example
Iterating Over a String You can use a for..of loop to const name = “NewHoriz";
iterate over the elements of a
string let text = ""
for (const x of name) {
text += x + "<br>";
}

document.getElementById("d
emo").innerHTML = text;
Iterating Over an Array You can use a for..of loop to const letters = ["a","b","c"];
iterate over the elements of
an Array: let text = "";
for (const x of letters) {
text += x + "<br>";
}

document.getElementById("d
emo").innerHTML = text;
JS Hoisting
JavaScript uses a concept called hoisting, where variable and
function declarations are moved to the top of their scope during
execution. This can cause issues with variable assignment and
function invocation if not understood.
JS Arrow Function
JavaScript introduced arrow functions in ECMAScript 6, which is a
shorthand for defining anonymous functions. They have a shorter
syntax and use the "=>" operator to separate the function
arguments and body.
function example
With Arrow Function let hello = "";

hello = () => {
return "Hello World!";
}

Arrow Functions Returning Value by Default let hello = "";

hello = () => "Hello World!";


Arrow Function With Parameters let hello = "";

hello = (val) => "Hello " + val;

document.getElementById("demo").innerHTML =
hello("Universe!");
Arrow Function Without Parentheses: let hello = "";

hello = val => "Hello " + val;

document.getElementById("demo").innerHTML =
hello("Universe!");
Introduction to JS Class
JavaScript introduced classes in ECMAScript 6, which is a blueprint
for creating objects. Classes can have properties and methods and
can be used to create objects with similar behavior.
Use the keyword class to create a class and always add a method
named constructor():
Introduction to JS Class
method syntax
JavaScript Class class ClassName {
constructor() { ... }
}

Class Methods class ClassName {


constructor() { ... }
method_1() { ... }
method_2() { ... }
method_3() { ... }
}
Introduction to JavaScript Modules
JavaScript introduced modules in ECMAScript 6, which allows for
better code organization and separation of concerns. Modules are
defined in one file and can be imported and exported between
different files. There are two types of exports: Named
Exports and Default Exports.
JSON
JSON (JavaScript Object Notation) is a lightweight data-interchange
format that is easy for humans to read and write and easy for
machines to parse and generate. It is a standard format for data
interchange and is commonly used in web development.
JS Objects
JavaScript has a built-in "Object" object that can be used to store
and manipulate data in a structured way. Objects can have
properties and methods and can be created using object literals,
constructor functions, or classes.
JS HTML DOM

JavaScript can manipulate the HTML Document Object Model


(DOM) to change the content, layout, and style of a web page. The
DOM is a tree-like structure that represents the elements of a web
page and can be accessed and manipulated using JavaScript.
Introduction to API
An API (Application Programming Interface) is a set of rules and
protocols for building and interacting with software applications.
JavaScript can use various APIs to interact with the browser, the
server, and other applications.
Form API
JavaScript has built-in methods for working with forms which are
used to access and manipulate form elements.
Form API
property description
checkValidity() Returns true if an input element contains
valid data.
setCustomValidity() Sets the validationMessage property of
an input element.

Validity property description


customError Set to true, if a custom validity message is
set.
tooLong Set to true, if an element's value exceeds
its maxLength attribute.
typeMismatch Set to true, if an element's value is invalid
per its type attribute.

You might also like