JavaScript Day 2
JavaScript Day 2
//some code
//action to do
Output
JavaScript Functions
A function is an organized block of reusable code (a set of statements)
that handles and performs actions generated by user events.
▪ Functions categorized into
• built-in functions improve your program's efficiency and readability.
• user defined functions , created by developer to make your programs
scalable.
▪ Function executes when it is called.
• from another function
• from a user event, called by an event or
• from a separate <script> block.
Global functions
Function Description
eval() Evaluates a string and executes it as if it was script
code
isFinite() Determines whether a value is a finite, legal number
isNaN() Determines whether a value is an illegal number
Number() Converts an object's value to a number
parseFloat() Parses a string and returns a floating-point number
parseInt() Parses a string and returns an integer
String() Converts an object's value to a string
Every JavaScript
Function function is actually a
Function object.
User-defined functions
Function blocks begin with the keyword function followed by the function
name and () then {} its building block declaration.
Syntax:
function functionName (argument1, argument2, ...)
{
//statement(s) here
//return statement;
}
return can be used anywhere in the function to stop the function’s work.
Its better placed at the end.
Defining function
function myFunction(x,l)
Functions {
var y = x+l;
return y;
}
Calling function
var z =
myFunction(5,6)
User-defined functions
▪ Function can be called before its declaration block.
▪ Local Scope
▪ A variable inside a function and stops existing when the function ends.
Understanding Scopes
Global
function
var1
var3 function
var2 var4 var5 var6
Variable Scope
▪ It is where var is available in code
▪ All properties and methods are in the public global scope
▪ They are properties of the global object “window”
Number
Boolean
Array
Date
Math
RegExp
Error
Function
Object
Constructor
Object
Properties Properties
Functions Functions
String Wrapp
Strings are useful for
er holding data that can
be represented in
text form.
String Object
▪ Enables us to work with and manipulate strings of text.
OR
er
object wrapper for a
boolean value.
Boolean Object
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false).
■ Everything in the language is either “truthy” or “falsy”
■ The rules for truthiness:
0 , ”” , NaN , null , and undefined 🡺 falsy
Everything else 🡺 truthy
■ You can convert any value to it’s boolean equivalent by applying “!!” preceding the value
■ Example:
!!”” 🡺 false
!!123 🡺true
■ To create Boolean Object
var b = new Boolean(); 🡺 false // typeof is Object
B = false 🡺 false // typeof “boolean”
Boolean Object
🡺All the following lines of code create Boolean objects withan initial value of false:
var myBoolean=new Boolean()
var myBoolean=new Boolean(0)
var myBoolean=new Boolean(null)
var myBoolean=new Boolean(undefined)
var myBoolean=new Boolean("")
var myBoolean=new Boolean(false)
var myBoolean=new Boolean(NaN)
Boolean Object
🡺And all the following lines of code create Boolean objectswith an initial value of true:
mathematical
constants and
functions.
Math Object
▪ Allows you to perform common mathematical tasks.
Constants value
Math.PI 3.141592653589793
Math.E 2.718281828459045
Math.LN2 0.6931471805599453
Math Object
▪ Methods
Methods
Math.abs() Returns the absolute unsigned value
Math.ceil() Return rounded number up to nearest interger
Math.cos() Returns cosine of number
Math.floor() Returns number down to nearest integer
Math.pow() Returns the number raised to a power
Math.random() Returns a number between 0 and 1.0
Math.sqrt() Returns square root of number
Math.round() Returns number rounded to closest integer
Array object is a
global object that is
used in the
construction of
Array
arrays.
Array Object
▪ Array is a special type of object
▪ It has length property:
▪ gives the length of the array It is one more than the highest index in the array
▪ Declaring an array
▪ var myarr=[]; //declaring an array literal
▪ var myarr=[1 , 2 , ‘three’ , ’four’ , false];
▪ var myarr= new Array() //using array constructor.
▪ var myarr=new Array(2) //an array with 2 undefined elements
▪ var myarr=new Array(1,2,’r’,true); //an array with 4 elements
Array Methods
var arr = new Array(“A”,”B”,”C”);
var arr2 = new Array(“1”,”2”,”0”)
Method Description Example
pop() Removes and returns the last element of an array. arr.pop()
//C, and the length becomes 2
push() Adds elements to the end of an array. arr.push(“D”)
//4 (Length of the array)
//and arr[3]=“D”
shift() Removes and returns the first element of an array. arr.shift() // A
//arr[0] =“B” & arr[1]=“C”
unshift() Adds elements to the beginning of an array. arr.unshift(“D”)); //4
//arr[0]=“D”
toString() Returns a string representation of the array. arr2.toString()//1,2,0
Array Methods
Method Description Example
concat() Concatenates elements from one array to another arr.concat(arr2)
array. //A,B,C,1,2,0
join() Joins the elements of an array by a separator to arr.join()//A,B,C
form a string. arr.join(“*”)//A*B*C
Syntax:
<script>
var assocArray = new Array( );
assocArray[“Ahmed"] = “Excellent";
assocArray[“Tareq"] = “pass";
</script>
1. Create array that contain some tips about JavaScript (Array of 10 strings, each string is
tip about JS), and show random tip for the user each time he opens the page.
2. Make a function that takes Student faculty as a parameter, checks:
a. If the entered faculty: FCI, show message: “You’re eligible to Programing tracks”.
b. If the entered faculty: Engineering, show message: “You’re eligible to Network and
Embedded tracks”.
c. If the entered faculty: Commerce, show message: “You’re eligible to ERP and Social
media tracks”.
d. For any other faculty, show message: “You’re eligible to SW fundamentals track”.
3. [Redo] On contact page prompt user to enter his name, make sure that name is string,
and let the user enter his birth year and make sure that it is a number, and it is less than
2020, and then calculate his age. For each prompt if user input valid show him next
prompt, if not valid show him the same prompt again until user enters it correctly (use
loops). And after validating user input, write all user input on the page in that format:
Name: ahmed
Birth year: 1981
Age: 30
4. [Bouns] Write a function that takes 2 parameters: start and end number and print odd
numbers between the given 2 numbers.