0% found this document useful (0 votes)
3K views

JavaScript Day 2

The document provides information about JavaScript functions including: 1) Functions are blocks of reusable code that handle actions and are categorized as built-in or user-defined. 2) Functions execute when called from another function, event, or script. 3) The document describes several built-in global functions and explains that functions are Function objects.

Uploaded by

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

JavaScript Day 2

The document provides information about JavaScript functions including: 1) Functions are blocks of reusable code that handle actions and are categorized as built-in or user-defined. 2) Functions execute when called from another function, event, or script. 3) The document describes several built-in global functions and explains that functions are Function objects.

Uploaded by

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

Input

//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.

▪ Functions are not required to return a value


▪ Functions will return undefined implicitly if it is to set explicitly

▪ When calling function it is not obligatory to specify all its arguments


▪ The function has access to all of its passed parameters via arguments collection

▪ We can specify default value using || operator or ES6 default function


parameters
Variable
Scope Life Time
JavaScript Variables Lifetime
▪ Global Scope
▪ A variable declared outside a function and is accessible in any part of your
program

▪ 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”

▪ There was no Block Scope before ES6, only function scope


▪ Variables declared
▪ Inside a function are local variable
▪ outside any function are global variable
▪ i.e. available to any other code in the current document
Object Categories
Built-in objects
Object
Math
Host Objects
String Author Objects
BOM
Boolean All other objects
DOM
Array
Date
Number
String

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.

▪ String Objects have:


▪ Property
▪ length : gives the length of the String.

▪ Methods that fall into three categories:


▪ Manipulate the contents of the String
▪ Manipulate the appearance of the String

▪ To create a String Object


▪ var text = “hello”;

▪var str = new String(‘hello’);


String Object Methods
Method Name Description Example
charAt(n ) Return the character at a given myStr.charAt(0)
position //L
indexOf( substr,[start]) Searches for first occurrence for a
myStr.indexOf("at") //12
substring.
lastIndexOf( substr,[start]) Searches for last occurrence for a
myStr.lastIndexOf("a")
substring.
//16
toUpperCase( ) Returns with all characters
converted to uppercase.
substring(from, to) method returns the part of the myStr.substring(1, 7)
string between the start and end //et's s
indexes, or to the end of the string. myStr.substring(2)
//t's see what happens!
Trim( ) removes whitespace from both
ends of a string
String Object Methods
Method Example Returned value

replace(string) Searches for a match between a myStr.replace(/e/,”?”)


substring (or regular expression) and //L?t's see what happens!
a string, and replaces the matched
substring with a new substring myStr.replace(/e/g,”?”)
//L?t's s?? what happ?ns!

concat(string) Joins two or more strings, and myStr.concat(“ now”)


returns a copy of the joined strings //Let's see what happens! now
slice(start , end) Extracts a substring of a string. myStr.slice(0, 5)
What’s the difference then ? //Let’s
split(delimiter, limit) Return array of strings, from splitting myStr.split(“ ”)
string into substrings at the boundaries //Let's,see,what,happens!;
specified by delimiter, constrained by myStr.split(“ ”,2)
limit number of elements. //Let's,see;
NumberWrapp Number object is a
wrapper object
er allowing you to work
with numerical
values.
Number Object
To create a Number Object

🡺 var n = new Number(101);

OR

🡺 n = new Number(); // if not assigned a value initially n =0

🡺 n=10; // value changed to n=10

Number has a set of Constant values & object methods.


Boolean Wrapp Boolean object is an

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:

var myBoolean=new Boolean(true)

var myBoolean=new Boolean(1)

var myBoolean=new Boolean("false“)

var myBoolean=new Boolean(“anyThing")


Math is a built-in
object that has
properties and
methods for
Math

mathematical
constants and
functions.
Math Object
▪ Allows you to perform common mathematical tasks.

▪ The Math object is a static object.

▪ Math is a little different from other built-in objects because it cannot be


used as a constructor to create objects.

▪ Its just a collection of functions and constants


Math Object
▪ Constant Properties:

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

reverse() Reverses the order of the elements in an array. arr.reverse()


//C,B,A
slice([begin[, end]]) Creates a new array from elements of an existing arr.slice(1) // B,C
array. arr.slice(2) //C
sort() Sorts an array alphabetically or numerically. arr2.sort() //1,10,2

Splice(start[, Removes and/or replaces elements of an array. arr.slice(1) // B,C


deleteCount[, item1[, arr.slice(2) //C
item2[, ...]]]])
Array Object
Associative Arrays: The Arrays That Aren't
• Associative arrays provide let you specify key-value pairs.
• Associative array is just like an ordinary array, except that instead of the indices
being numbers, they’re strings, which can be a lot easier to remember and reference:
• Although the keys for an associative array have to be strings, the values can be of any
data type, including other arrays or associative arrays.

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.

You might also like