[Go to site: main page, start]

JavaScript Study Notes Overview

0% found this document useful (0 votes)
92 views9 pages
This document provides an overview and study notes on JavaScript. It covers using external JavaScript, variables, operators, control structures, functions, events, objects, properties, metho…

Uploaded by

Ts Dc
  • Overview
  • Event
  • JavaScript Object
  • Built-in Objects
  • JavaScript, Create Your Own Object
  • JavaScript Function as First-class object
  • JavaScript Development Tools

3/23/2021 JavaScript Study Notes

JavaScript Study Notes


fwang2@[Link]

Table of Contents:

1. Overview
1.1. Use external JavaScript
1.2. Variable and Operators
1.3. Controll Structure
1.4. Functions
1.5. Event
2. JavaScript Object
2.1. Properties
2.2. Methods
2.3. Object literal
2.4. Built-in Objects
3. JavaScript, Create Your Own Object
3.1. Create a direct instance of an object
3.2. Create object template
4. JavaScript Function as First-class object
4.1. Function as callbacks
4.2. Function context
4.3. Scope
4.4. Closure
4.5. Argument checking
4.6. Type checking
5. JavaScript Development Tools
5.1. Firebug (error console, debugger, DOM inspector)
5.2. Venkman (debugging)
5.3. JSUnit (unit testing)

1. Overview
1.1. Use external JavaScript

<html>
<head>
<script type="text/javascript" src="[Link]"> </script>
</head>
</html>

1.2. Variable and Operators

Comments are //

Code blocks { … }

Variables

[Link]/~fwang2/web/[Link] 1/9
3/23/2021 JavaScript Study Notes

x=5;
var x=5;

Arithmetic Operators:

+, -, *, /, % (modulus), ++, --

Assignment Operators:

=, +=, -=, *=, /=, %=

String addition

x = "5" + "5" // result is "55"


x = 5 + "5" // result is still "55"

Comparison operators

== // equal to
=== // exactly equal to (value and type)
!= // not equal to
> // greater
< // less
>= // greater than or equal to
<= // less than or equal to

Logical operators && // and || // or ! // not

Conditional operator

varname = (condition)? value1: value2

1.3. Controll Structure


if

if (condition) {
...
}

if else

if (condition) {
...
} else {
...
}

if … else if … else

[Link]/~fwang2/web/[Link] 2/9
3/23/2021 JavaScript Study Notes

if (condition)
{ ... }
else if (condition)
{ ... }
else
{ ... }

switch statement

switch(n)
{
case 1:
code block
break;
case 2:
code block
break;
default:
code default block
}

for loop

for (var=startvalue; var <= endvalue; var+var+increment)


{
code;
}

for … in loop

for (var in object) {


code;
}

while loop while (var < endvalue) { code; }

do … while loop

do {
code;
} while (var <= endval);

1.4. Functions
Function can be defined as:

function func_name(var1, var2, ... )


{
some code
}

The variables declared within a function is local to the function.

[Link]/~fwang2/web/[Link] 3/9
3/23/2021 JavaScript Study Notes

1.5. Event

Every element on a web page has certain events which can trigger a JavaScript. Examples such as:

onLoad and onUnload: triggered when user enters or leaves the page

onFocus, onBlur, and onChange: often used in combination with validation of form field.

<input type="text" size="30" id="email" >

onMouseOver and onMouseOut - often used to create animated button

2. JavaScript Object
Things to know:

A JavaScript object is an unordered collection of properties.

Properties consists of a name and a value

Objects can be declared as object literals

Top-level ‘variables’ are properties of window.

2.1. Properties

Properties are values associated with an object. For example of using length property of String object:

<script type="text/javascript">
var txt = "Hello world!";
[Link]([Link]);
</script>

2.2. Methods
Methods are actions that ban be performed on objects.

For example:

<script type="text/javascript">
var str="Hello worlds!";
[Link]([Link]();
</script>

2.3. Object literal

var ride = {
make: "Honda',
model: "Civic',
purchased: new Date(2008, 3, 12),
owner: {
name: "Feiyi Wang",
occupation: "Bum"

[Link]/~fwang2/web/[Link] 4/9
3/23/2021 JavaScript Study Notes

}
};

This notation, come to be known as JSON (JavaScript Object Notation) Also notice how nested objects
are declared.

2.4. Built-in Objects


String.

Date.

// return today's date


var d = new Date();

// turn time as milliseconds since 1970


[Link]([Link]());

// set full year


[Link](1992, 10, 3)

var weekday = new Array(7);


weekday[0] = "Sunday";
weekday[1] = "Monday";
...
weekday[6] = "Saturday";
[Link]("Today is" + weekday[[Link]()]);

Array

// create an array
var myCars = new Array();

// or
var myCars = new Array("Sabb", "Volvo", "BMW");

// or
var myCars = ["Sabb", "Volvo", "BMW");

// for loop
for (x in myCars)
{
[Link](myCars[x] + "<br />");
}

// merge array
var parents = ["mom", "dad"]
var children = ["mike", "jenny"]
var family = [Link](children);

// join array elements in to string


var fstr = [Link]();

// remove the last element of the array


[Link]() // jenney

[Link]/~fwang2/web/[Link] 5/9
3/23/2021 JavaScript Study Notes

// add to last
[Link]("jenny")

// add to beginning
[Link]("grandma");

Boolean

var myB = new Boolean();

If Boolean object has no initial value, or if it is 0, -0, null, ””, false, undefined, or NaN, the object is
set to False.

Otherwise, it is True.

Math

RegExp: for regular expression

navigator for browser detection.

// Broswer code name


[Link]

// Browser name:
[Link]

// Browser version
[Link]

// Cookie enabled
[Link]

3. JavaScript, Create Your Own Object


3.1. Create a direct instance of an object

// with 3 properties, you can just assign it.


p = new Object();
[Link] = "John"
[Link] = "Oliver"
[Link] = 50;

3.2. Create object template

function person(firstname, lastname, age)


{
[Link] = firstname;
[Link] = lastname;
[Link] = age;

[Link] = workhours;
}

[Link]/~fwang2/web/[Link] 6/9
3/23/2021 JavaScript Study Notes

Notice that:

An object tempalte is just plain function.

You can attach method workhours to it, by then you have to define it somewhere.

Once you have object template, you can create many instance of it now.

4. JavaScript Function as First-class object


A function can:

Assigned to variables

Assigned to a property of an object

Passed as an paramter

Returned as function result

Created using literals

Function is not a named entity: function keyword creates a Function instance and assigned it to a window
property if you delcare such at top-level. For example, the following two forms are the same:

function myFunc() {
alert('I am working');
}

<==>

myFunc = function() {
alert('I am working');
}

And the second form is also known as function literal, just as object literal we talked above.

4.1. Function as callbacks


Consider the following:

function hello() { alert('Hi there!'); }

setTimeout(hello, 5000)

or a more elegant version:

setTimeout( function() { alert('Hi there!'); }, 5000 )

In the later case, we express the functional literal directly in the parameter lsit, and no name is generated.

4.2. Function context

A function f acts as a method of object o when o serves as the function context of the invocation of f.

[Link]/~fwang2/web/[Link] 7/9
3/23/2021 JavaScript Study Notes

Example:

var o1 = { handle: 'o1' };


var o2 = { handle: 'o2' };
var o3 = { handle: 'o3' };

function whoAmI() {
return [Link];
}

[Link] = whoAmI;

alert(whoAmI()); // window

alert([Link]()); // o1

alert([Link](o2)); // o2

alert([Link](o3)); // o3

As you can see, you can change function context (this) by using function method call() or apply().

alert([Link](o3)); // still o3

This example further shows that even we reference the function as a peroperty of o1, but the function
context for this invocation is o3.

The important thing to know is not how function is declared, but how it is invoked.

4.3. Scope
In JavaScript, scope is kept within function, but not within blocks (such as while, if and for
statement).

If you don’t use var, then it is implictly in global scope.

var foo = ‘test’;

// within a block if (true) { // this is still within global scope var foo = ‘new test’; }

alert( foo == ‘new test’ ) // true

function test() { var foo = ‘old test’; }

// even called, ‘foo’ remains within the scope of the function test();

alert ( foo == ‘new test’ ) // still true

4.4. Closure

A closure is a Function instance coupled with the local variables from its environement that are ncessary
for its exeuction.

4.5. Argument checking

[Link]/~fwang2/web/[Link] 8/9
3/23/2021 JavaScript Study Notes

function sendMessage( msg, obj ) {


// if both a message and object are provided
if ( [Link] == 2 )
// send message to the object.
[Link]( msg );
else
// otherwise, assume only a message is provided
// so just display default msg
alert( msg );
}

4.6. Type checking

function displayError( msg ) {


// check and make sure that msg is not undefined

if ( typeof msg == 'undefined' ) {


// set default
msg = "An error occured.';
}

// display the message


alert( msg );
}

5. JavaScript Development Tools


5.1. Firebug (error console, debugger, DOM inspector)

5.2. Venkman (debugging)

5.3. JSUnit (unit testing)

[Link]/~fwang2/web/[Link] 9/9

Common questions

Powered by AI

In JavaScript, the '==' operator compares two values for equality with type coercion, meaning it converts operands to the same type before comparing them. In contrast, the '===' operator checks for strict equality, comparing both value and type without performing type conversion. This difference makes '===' safer to use when an exact match without type conversion is crucial, reducing unexpected results due to implicit type conversion .

The 'call' method allows you to set the context ('this' value) explicitly when invoking a function in JavaScript. Instead of the function executing in its original context, 'call' assigns a new context, enabling the function to access properties and methods of the newly assigned context. This is particularly useful in scenarios where object-specific behavior is needed from a shared function .

JavaScript's built-in objects provide methods and properties that facilitate routine operations required during data manipulation and presentation. For example, the Date object allows easy manipulation and formatting of dates, while the Array object offers methods for sorting, joining, and transforming collections of data. These built-in tools reduce the need for verbose custom implementations, promoting efficient and readable code .

Closures allow functions in JavaScript to retain access to their lexical environment, providing a means to encapsulate function logic along with the variables in scope when the function was declared. This encapsulation retains the state even after the context in which they were created has completed execution, empowering functions to maintain state across invocations, effectively creating private state variables .

The 'arguments' object in JavaScript functions offers flexibility by allowing functions to accept an unspecified number of arguments, enabling developers to write more generic and versatile functions. However, relying on it can limit the function's clarity and intention by making argument types and counts implicit rather than explicit, and in strict mode, 'arguments' does not behave appropriately with arrow functions, which lack their own 'arguments' object .

Creating object templates in JavaScript, such as using functions to define properties and methods, allows developers to instantiate multiple objects with similar behavior and properties without repeatedly writing the same code. This approach enhances code scalability by making it easier to manage changes across similar objects and promotes reusability, as changes in the template are automatically reflected in all instantiated objects .

JavaScript maintains function scope rather than block scope, meaning variables declared within a function are local to that function and inaccessible outside it. However, variables declared with 'var' inside a block (like an 'if' or 'for' block) are not block-scoped but instead hoisted to the function or global scope. This can lead to unexpected behaviors where block-contained variables affect the broader scope, influencing variable lifespan and accessibility .

Using external JavaScript files in web development allows multiple HTML pages to share the same script content, simplifying maintenance and development. Updating the script content becomes more efficient as changes need to be made only once in the external file, with all pages that include the file automatically reflecting the updates. This practice also contributes to cleaner HTML code and better separation of concerns between content and behavior .

JavaScript event handling enhances web page interactivity by allowing developers to specify dynamic behavior in response to user actions. Events like 'onLoad', 'onClick', and 'onChange' can trigger specified functions, enabling real-time updates and interactions on a page without requiring page reloads. This allows for creating dynamic, responsive user experiences fundamental to modern web applications .

Declaring JavaScript functions as first-class objects allows them to be assigned to variables, passed as parameters, and returned as function results, enabling higher-order functions and callbacks. This capability significantly enhances flexibility and abstraction in code. However, potential pitfalls include increased complexity and difficulty in debugging, as functions can be created and invoked in multiple contexts without clear visibility into where they are being utilized .

3/23/2021
JavaScript Study Notes
users.nccs.gov/~fwang2/web/javascript.html
1/9
JavaScript Study Notes
fwang2@ornl.gov
Table
3/23/2021
JavaScript Study Notes
users.nccs.gov/~fwang2/web/javascript.html
2/9
  x=5; 
  var x=5;
Arithmetic Operators:
  +,
3/23/2021
JavaScript Study Notes
users.nccs.gov/~fwang2/web/javascript.html
3/9
  if (condition)  
  { ... } 
  else if (cond
3/23/2021
JavaScript Study Notes
users.nccs.gov/~fwang2/web/javascript.html
4/9
1.5. Event
Every element on a web page has ce
3/23/2021
JavaScript Study Notes
users.nccs.gov/~fwang2/web/javascript.html
5/9
    } 
};
This notation, come to be known as
3/23/2021
JavaScript Study Notes
users.nccs.gov/~fwang2/web/javascript.html
6/9
  // add to last 
  family.push("jenny") 
  /
3/23/2021
JavaScript Study Notes
users.nccs.gov/~fwang2/web/javascript.html
7/9
Notice that:
An object tempalte is just plain
3/23/2021
JavaScript Study Notes
users.nccs.gov/~fwang2/web/javascript.html
8/9
Example:
var o1 = { handle: 'o1' }; 
var o2 =
3/23/2021
JavaScript Study Notes
users.nccs.gov/~fwang2/web/javascript.html
9/9
function sendMessage( msg, obj ) {
    // if

You might also like