Transcript var
JavaScript
Basics of JavaScript Programming Language
Advanced Web-based Systems | Misbhauddin
The Front-End Trifecta
Presentation
Styles the Tags
Provides Tags (Elements)
Structure
Functional
Modify the Tags
Advanced Web-based Systems | Misbhauddin
JavaScript
•
•
•
•
•
Client-Side Scripting Language
It tells the browser to go do the work
Makes Webpages more interactive
JavaScript is not the same as Java
But has various similarities with the programming language
Run Script (On Load / Action)
Request an HTML webpage
HTML Page (w/ Scripts)
Rules:
1.
2.
3.
JS cannot read/write files from/to the computer file system
JS cannot execute any other programs
JS cannot establish any connection to other computer, except to
download a new HTML page or to send mail
Advanced Web-based Systems | Misbhauddin
Output functions
• Popups or Alert Boxes
• alert(“message”)
• Write function
• document.write()
• Like the System.out.println() function in Java
• Console Output
• console.log()
• Mainly used for debugging
Advanced Web-based Systems | Misbhauddin
Variables
• Variables or Identifiers are named memory locations that hold
data to be used throughout the code
• JavaScript is a Dynamically Typed Language – No Data Type
• Statically Typed languages such as Java or C need data types on
declaration
keyword
value
var name = 23;
variable name
Rules:
1. Case-sensitive
2. Cannot start with a number
3. Can contain letter, numbers & underscore, dollar sign
Note: Must be declared before their use in the script
Advanced Web-based Systems | Misbhauddin
Types of Variables
•
•
•
•
Numbers: Integers, Decimal Numbers, Negative Numbers
Text / String: “Use quotations for values”
Boolean: true / false
No Value: null (Empty Variable) – Not same as a zero
typeof will return the type of the variable
console.log(typeof myVar);
Advanced Web-based Systems | Misbhauddin
Undefined and Null
• Both are falsie values
• Weak comparison both are equal (undefined == null) will be true
• Strong comparison both are not equal (undefined === null) will be
false
Advanced Web-based Systems | Misbhauddin
Strings
• Declared either using single quotes (‘test’) or double quotes
(“test”)
• If you use apostrophe (number’s) in your string, you should use
double quotes
var test = “Hello World”;
var test2 = ‘Hello’;
var test3 = “Brother’s car”;
//Apostrophe – double quotes necessary
Advanced Web-based Systems | Misbhauddin
Strings
• String declarations should be on the same line.
•
•
To add a new line to the output, use “\n”
To add a new tab to the output, use “\t”
• Two strings can be concatenated using “+” operator.
•
Multi-line string declarations possible by using “+” operator
var test = “Hello World” + “Welcome to Programming”;
var test2 = “Hello \n World”;
var test3 = “Hello \t World”;
var test4 = “Hello”+
“World”;
// Multi-line declaration
Advanced Web-based Systems | Misbhauddin
Strings Functions
• .length – Returns the length of the string
var test = “Hello World”;
document.write(test.length);
//Returns 11
• .indexOf(substring) – Will return the index of the substring passed
in the parameter. If not found, will return (-1). It is case sensitive.
var test = “Hello World”;
document.write(test.indexOf(‘World’));
document.write(test.indexOf(‘new’));
document.write(test.indexOf(‘world’));
//Returns 6
//Returns -1
//Returns -1 (Case sensitive)
• .charAt(index) – Returns the character found at the index passed
in the parameter. String indexes start from 0.
var test = “Hello World”;
document.write(test.charAt(4));
Advanced Web-based Systems | Misbhauddin
//Returns o
More Strings Functions
• .substr(a, b) – Returns the substring starting from a of length b
var test = “Hello World”;
document.write(test.substr(3, 2));
//Returns lo
• .toLowerCase() – converts the string to all lower case.
var test = “Hello World”;
document.write(test.toLowerCase());
//Returns hello world
• .toUpperCase() – converts the string to all upper case.
var test = “Hello World”;
document.write(test.toUpperCase());
Advanced Web-based Systems | Misbhauddin
//Returns HELLO WORLD
Strings Comparison
• Two comparison operators in JavaScript
• Double equal (==) or weak comparison
•
•
Check whether the two variables are equal
If one is string and the other is a number, forcefully converts them
both to the same type.
var a = “2”; var b = 2;
If(a==b)
//Returns true
• Triple equal (===) or strong comparison
• Compares both the values and their data types
var a = “2”; var b = 2;
If(a===b)
//Returns false
Advanced Web-based Systems | Misbhauddin
Numbers
• Accepts signed, unsigned and floating point numbers
• Internally, all numbers are stored as floating point numbers
• Large numbers are stored as exponents
•
For example, 105 is written as 10E5
• If a number starts with 0, it is interpreted as Octal number
• If a number starts with 0x, it is interpreted as Hexadecimal number
Advanced Web-based Systems | Misbhauddin
Data Type conversion
• Convert string to numbers
• Only if the string has numbers
• parseInt(“197”);
• parseFloat(“10.2”);
• parseInt can also convert a string starting with a number
•
parseInt(“23 people”);
//Return 23
• If a string starts with a alphabet
•
parseInt(“Not 23”);
// Returns NaN (Not a Number)
Advanced Web-based Systems | Misbhauddin
Operators
• “+”
• Addition when both are numbers
• Concatenation when any one is a string
• Others
• Minus(-), Multiply(*), Divide(/), Remainder(%)
• Increment(++), Decrement(--)
• Assignment (=)
• Comparison (==, ===)
Advanced Web-based Systems | Misbhauddin
Mathematical Functions
• Math.random()
•
•
Generates a random number from 0 to 1 (float)
To get a random number from 0 to 10
• Math.random()*10
• Math.round(x)
•
Round the number to the nearest whole number
• Math.floor(x)
•
Round the number to the lower limit [Math.floor(14.7) = 14]
• Math.ceil(x)
•
Round the number to the upper limit [Math.ceil(14.3) = 15]
Advanced Web-based Systems | Misbhauddin
More Mathematical Functions
• Math.pow(a,b)
•
•
Calculate ab
a is the base and b is the exponent
• Math.sqrt(x)
•
Calculates the square root x
• Math.min(x,y,a,b)
•
Returns the minimum number from the list of given numbers
• Math.max(x,y,a,b)
•
Returns the maximum number from the list of given numbers
Advanced Web-based Systems | Misbhauddin
Conditional Statements
SYNTAX
keyword
• If Statement
• execute some code only if a specific
condition is met.
• Else If Statement
• Various conditions that are checked
one after another until the script
finds a true condition
• Else Statement
• If none of the above conditions are
met, this block of code is executed.
if (something is the case)
{
more JavaScript commands
}
Comparison Operators
Larger than
>
Smaller than
<
Larger than or equal to
>=
Smaller than or equal to <=
Advanced Web-based Systems | Misbhauddin
Equal to
==
Not equal to
!=
Conditional Statements
• Switch Statement
• Select one of many blocks of code to be executed
SYNTAX
keywords
switch(test)
{
case 1: execute code block 1
break;
case 2: execute code block 2
break;
default: default code
}
Advanced Web-based Systems | Misbhauddin
Note:
Unlike Java,
switch in
JavaScript works
with strings
Boolean Combinators
• Combine Multiple conditions in the IF statement
AND (&&)
True when both elements are true
OR (||)
True when at least one of the elements is true
NOT (!)
Toggles a statement from true to false or from false to
true
Advanced Web-based Systems | Misbhauddin
Looping Statement
• Initial Value; Test Condition; Update Value
SYNTAX
keyword
for (initialize; condition; update)
{
more JavaScript commands
}
• For Statement
• execute some code repeatedly
• While Statement
• Convenient when you want to loop until
a condition changes
• Do Statement
• Useful when you always want to execute
the loop at least once
Initialize outside
Initialize outside
keyword
keyword
do
{
while (condition)
{
more JavaScript commands
update inside
}
more JavaScript commands
update inside
} while (condition);
Advanced Web-based Systems | Misbhauddin
Functions in JS
Advanced Web-based Systems | Misbhauddin
Function Declaration
• Mainly used for event-handling in Web Development
• Can also be called from other functions (Reuse)
SYNTAX
keyword
function name(param1, param2,…..)
{
}
var name = function (param1, param2,…..)
{
• You can use as many parameters as you like
• Can also return values (numbers, strings, Boolean)
• Use return statement
function name(parameters)
{
return b;
}
}
Advanced Web-based Systems | Misbhauddin
Anonymous Functions
• Functions with no name
•
•
Used mainly in calls and event handling
We don’t use them more than once in our code
var something = function() {
call(function(){
button.onclick = function(){
}
});
}
Advanced Web-based Systems | Misbhauddin
Arrays in JS
Advanced Web-based Systems | Misbhauddin
Arrays
• Can store numbers, strings, functions, Boolean, and Sub-arrays
SYNTAX
SYNTAX for Initializers
var array-name = new Array();
Elements
Built-in
keyword
var array-name = new Array(value1, value2,………..);
[0]…….[size-1]
Other Initialization Method
[0]
var array-name = new Array(size);
array-name[index] = “value”;
USAGE: array-name[index-value]
Note: Index value should be in-bounds otherwise “undefined” error
Advanced Web-based Systems | Misbhauddin
[1]
Index
Array Functions
• .length – Returns the length of the array
var test = [1, 2, 3, 4, 5];
document.write(test.length);
//Returns 5
• .toString() – Converts an array into a string. Used to display the
array.
var test = [1, 2, 3, 4, 5];
document.write(test.toString());
//Returns 1,2,3,4,5
• .push(x) – Adds the element x to the end of the array
var test = [1, 2, 3, 4, 5];
test.push(6);
document.write(test.toString());
//Returns 1,2,3,4,5,6
Advanced Web-based Systems | Misbhauddin
More Array Functions
• .pop() – Removes the last element in the array
var test = [1, 2, 3, 4, 5];
document.write(test.pop());
//Returns 5
• .unshift(x) – Add the element x to the beginning of the array
var test = [1, 2, 3, 4, 5];
test.unshift(0);
document.write(test.toString());
//Returns 0, 1,2,3,4,5
• .shift() – Removes the element from the beginning of the array
var test = [1, 2, 3, 4, 5];
document.write(test.shift());
Advanced Web-based Systems | Misbhauddin
//Returns 1
More Array Functions
• .sort() – Sorts the array. Default assumption is that the array is all
strings.
var test = [1, 2, 3, 4, 5, 10];
document.write(test.sort().toString());
//Returns 1, 10, 2, 3, 4, 5
• .reverse() – Reverses the array
var test = [1, 2, 3, 4, 5];
test.reverse();
document.write(test.toString());
//Returns 5, 4, 3, 2, 1
• a.concat(b) – Joins two array a and b into a new array
var z = [1,2,3].concat([4,5]);
document.write(z.toString());
//Returns 1,2,3,4,5
Advanced Web-based Systems | Misbhauddin
More Array Functions
• .slice(a,b) – extracts the array starting from index a until before
index b (excluding index b)
var test = [1, 2, 3, 4, 5, 10];
document.write(test.slice(2,4).toString());
//Returns 3, 4
• .join(x) – Converts the array into the string joining them using the
separator string x
var test = [1, 2, 3, 4, 5];
test.join(“/”);
document.write(test.toString());
//Returns 1/2/3/4/5
• delete a[x] – Delete the index x from the array a
var test = [1,2,3]
delete test[1];
document.write(test.toString());
Advanced Web-based Systems | Misbhauddin
//Returns 1, 3,
Objects in JS
Advanced Web-based Systems | Misbhauddin
Object-Oriented JS
JavaScript is Object-Oriented
Properties
They have a value
Methods
Object
'things that do
something
Example
var abc = “Hello World”;
abc.length;
document.write(“Hello World”);
method
property
Advanced Web-based Systems | Misbhauddin
Object Definition
Objects
•
•
Objects allow us to represent in code real world things and entities
Such as a person or bank account
SYNTAX
keyword
var object-name =
{
……….
}
Advanced Web-based Systems | Misbhauddin
Key-Value: Properties of an Object
Properties
•
•
Each piece of information we include in an object is known as a property.
Each property has a key, followed by : and then the value of that property
SYNTAX
Access value of a key
keyword
object-name[“key”];
or
object-name.key
var object-name =
{
key: value,
}
Note: Separate each property using a comma (,) and not a semicolon as in Java
Key names can have quotations. But if there is a space in the name (first name), quotation is necessary
Advanced Web-based Systems | Misbhauddin
Function Assignment to Objects
Methods
•
A method is just like a function associated with an object
SYNTAX
keyword
var object-name =
{
key: value,
function-name: function() {
----------}
}
Advanced Web-based Systems | Misbhauddin
Access the function
object-name.function-name();
“this” keyword
•
•
Refer to whichever object called that method
Gets the context of the method called
var mohammed =
{
name: “Mohammed”,
id: “2038986666”,
position: “Assistant Professor”,
upgrade: function() {
if(this.position === “Assistant Professor”)
this.position = “Associate Professor”;
}
}
Advanced Web-based Systems | Misbhauddin