RECITATION WEEK 8 JavaScript Functions P N

RECITATION WEEK 8
JavaScript Functions
PREPARED BY
NEELANG NAVAL
CS-170 SECTION 23,24
Optional Presentation Title
JAVASCRIPT
•
Can be inserted into HTML page
•
Can be executed by all modern browsers
A good Webpage:
•
HTML – for Content
•
CSS – for Stylizing
•
JavaScript – for Interactivity
Defining JavaScript -
<script >
//All code of javascript
</script>
Unit Name
Optional Presentation Title
Few things
•
Unlike HTML, JavaScript is case sensitive.
•
Close statement with a semi-colon ;
•
Text is always between quotes
•
•
Numbers and variables are displayed without quotes
Prompting something to user
“”
alert("Hello, world.”);
• Using variable to prompt and save info
varfirstName = prompt("What is your name");
• Example : var firstName = prompt("What is your name");
document.write("Hello " + firstName + "!");
Unit Name
Optional Presentation Title
Java Script Functions
• SYNTAX:
function function-name (arguments)
{
code;
}
Why do we need Functions? 
- Reusability of code
- Keeps the code short
- Maintains Proper structure
Sounds Cool…Lets try it! 
Unit Name
Optional Presentation Title
Some Examples
<script>
var total;
total();
//declaring variable
//Function Call
function total()
//empty brackets () means there are no arguments
{
var x=5;
//Declaring variable and assigning value to x
var y=10;
total=x+y;
alert(“Total sum is ” + total);
}
</script>
Unit Name
Optional Presentation Title
Functions Calls:
• Whenver a function is called, it will go to the function definition
and it will execute the code.
• Example:
<button onclick="greeter('Student','CS170')">Greetings</button>
• Whenver a user clicks the button, it will go where the “greeter”
function is define and execute it.
• Arguments will be in single quotes unless they are
variables!
Unit Name
Optional Presentation Title
var name=prompt(“Enter your name”);
var course=prompt(“Enter your course”);
var user=confirm(“Are you a student?”);
if(user == true)
{
greeter(name, course);
// Function Call
}
function greeter(name , course)
//Function Definition
{
document.write("Welcome" + name + "to" + course);
}
Unit Name
Optional Presentation Title
Scope of Variables
• The scope of a name defines how “far” from its declaration it
can be used.
• Variables declared in a function can be used only within that
function (local variables).
• Those declared outside functions can be used throughout the
program (global variables).
• Locals come into existence when a function begins, and when
it ends, they vanish.
•Unit Global
variables are around all the time.
Name
Optional Presentation Title
Scope of Variables
Unit Name
Optional Presentation Title
Built-In Functions
• Math.max(arguments)
• Returns a maximum value passed in the arguments.
Example:
var value = Math.max(10, 20, -1, 100);
• Fontcolor()
• Var str=”Hello!”;
• str.fontcolor(”red”);
• Date()
• document.write('<p>' + (Date( ).toString( )) + '</p>');
Unit Name