[Go to site: main page, start]

0% found this document useful (0 votes)
4 views12 pages

JavaScript Functions and Scope Explained

Uploaded by

tazvitya Mapfumo
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views12 pages

JavaScript Functions and Scope Explained

Uploaded by

tazvitya Mapfumo
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

IT350 Web and Internet Programming

Fall 2007
SlideSet #9: JavaScript Functions

(from Chapter 10 of the text)


Function Definitions
• Syntax and terminology:
function function-name( parameter-list )
{
declarations and statements
}
• Example
/* Return an integer no larger than ‘max’ */
function getIntegerWithMax(max) {
var value;
do {
value = [Link](
"Please enter an integer no larger than "+max);
} while (value > max);
return value;
}
Function Invocation

• Built-in functions

• User-defined functions

Arguments are passed ______________, so original


values in caller are ________________
Scope – Where is a variable visible in the program?
function dog(g) {
h = 3;
var sum = g+h;
[Link]("<br/> Sum is: "+sum);
}

g = 7;
h = 5;

[Link]("<br/> g: "+g+" h: "+h);


dog(g);
[Link]("<br/> g: "+g+" h: "+h);
[Link]("<br/> sum: "+sum);

Output?
JavaScript Scope Rules

• Variables declared inside a function:


– Explicitly (with var)
– Implicitly (just used)
– Parameters
(Look at FIRST USE inside a function to decide which applies)

• Variables declared outside a function:


– Explicitly
– Implicitly
Exercise #1 – Write a function that takes two
arguments and returns the minimum of the two
Exercise #2 – What’s the output?
function fun1 (x) {
x = x + 3;
y = y + 4;
[Link]("<br/> FUN1: "+x+ "," +y);
}

function fun2 () {
var y;
x = x + 10;
y = y + 20;
[Link]("<br/> FUN2: "+x+ "," +y);
}

x = 1;
y = 2;

[Link]("<br/> MAIN #1: "+x+ "," +y);


fun1(x);
[Link]("<br/> MAIN #2: "+x+ "," +y);
fun1(y);
[Link]("<br/> MAIN #3: "+x+ "," +y);
fun2();
[Link]("<br/> MAIN #4: "+x+ "," +y);
Exercise #3 – Write a function indentPrint(N, str1, str2) that
outputs the following:
a.) ‘N’ dashes, followed by the string ‘str1’, then <br/>
b.) ‘N’ dashes, followed by the string ‘str2’, then <br/>
Use [Link]() for output. You can assume N is an integer.
Exercise #4
1. What point(s) are strange about the following code?
2. Will each cause a syntax error, logic error, or neither?
3. Fix the average function so that it correctly calculates both requested
averages.
4. (a stretch) Do #3 without changing the function header.

function average(x, y, z) {
return (x + y + z) / 3;
}

[Link]("<br/> avg2:" +average(3, 9));


[Link]("<br/> avg1:" +average(10, 20, 30, 40));
Connecting JavaScript and XHTML

• Where to place the JavaScript


– In the .html file

– In a separate file
<script type = “text/javascript” src = “[Link]” />

• How to invoke the script?


– Place non-function code in the <head>
– <body >

– <input type = "button" value = “Roll"


/>
JavaScript Secrets

• Invalid numbers are NaN


– Test with isNaN(value)
• 5 types for variables:
– number (including NaN)
– string
– boolean
– “undefined” – may cause error or lead to NaN
– null
• Gotchas
– color = red;
– if (x = 7) …
– Uninitialized variables
– Forgetting “break” in switch
JavaScript Tips

• Quoting
[Link]("<a href=\"[Link]\">cat</a>");
vs.
[Link]("<a href='[Link]'>cat</a>");

• Multiple arguments to [Link]()


[Link]("<h1>"+heading+"</h1>");

[Link]("<h1>",heading,"</h1>");

(doesn’t work with my_writeln() )

Common questions

Powered by AI

In JavaScript, NaN (Not-a-Number) is a special value resulting from operations like dividing zero by zero or parsing invalid numbers. NaN causes operations to propagate this value, often leading to unintended results. Programmers can handle such cases by employing 'isNaN(value)' to test if a calculation yields NaN and take appropriate action, such as logging an error or applying alternative logic to handle faulty computations .

Defining 'color = red;' without prior declarations or quotation marks leads to several issues. 'red' is interpreted as an undefined variable unless it's defined elsewhere in the code. This use would not define a valid string or reference, resulting in an error or bug due to the variable 'color' being implicitly global if 'use strict' is not employed. This practice is considered bad due to potential unforeseen errors or conflicts .

Failing to use 'break' statements in JavaScript's 'switch' structure results in 'fall through', where execution proceeds unchecked through subsequent cases until a 'break' or the end is reached. This likely causes unintended behavior or logic errors where multiple cases might execute instead of just the matched one .

Using single quotes versus double quotes in strings within 'document.write()' can affect HTML output by potentially causing syntax errors or unexpected behavior, especially when embedding HTML attributes. Correctly escaping or consistently using one type ensures correct parsing, such as '<a href="cat.html">' being equivalent to '<a href='cat.html'>', without issues of nesting conflicting quotes .

Placing JavaScript functions inside a HTML document's head section allows them to be pre-loaded and ready for use as soon as the page loads. Conversely, using separate JavaScript files can improve modularity and manageability of code, facilitating updates and reuse without altering HTML. However, separate files require correct linking using the 'src' attribute and must be accounted for in network load considerations .

The function 'fun2()' contains the declaration 'var y;' which initializes 'y' to 'undefined' due to JavaScript's variable hoisting. Hence, 'y = y + 20;' results in NaN since undefined plus a number yields NaN. The 'x = x + 10;' affects 'x' as it updates the global 'x' variable by 10 due to the lack of 'var', 'let', or 'const', since 'x' is assumed to be a global variable .

Calling the function 'average(x, y, z)' with more or fewer arguments than specified in its definition leads to logic errors because missing arguments are considered 'undefined', and extra arguments are ignored. To handle varying argument counts without modifying the header, logic must be added inside the function to handle 'arguments.length' and dynamically compute the average based on the number of arguments provided. For instance, summing only 'arguments' array elements and dividing by its 'length' would solve this issue .

Designing a function to print styled messages involves defining parameters for the message, repetition count, and CSS styling attributes as a string or object. The function should robustly check for valid parameter values, employ loops for repetition, and safely integrate CSS styles with potential default values to prevent formatting errors. For instance, 'function styledMessage(msg, count = 1, style = "") { for (let i = 0; i < count; i++) { document.write(`<div style='${style}'>${msg}</div>`); } }'. Considerations include security risks (CSS injection), handling defaults, and HTML escape sequences .

In JavaScript, variables declared inside a function have function scope and are only accessible within that function. They can be declared explicitly with 'var' or implicitly by just using them. Parameters are also considered as having function scope. In contrast, variables declared outside of a function have global scope and are accessible throughout the program unless shadowed by local variables of the same name .

When arguments are passed by value in JavaScript, the original variables in the caller function remain unchanged. Instead, copies of the values are passed to the function, which means any modifications inside the function do not affect the original variables .

You might also like