Introduction to JavaScript Tutorial
By Neil Williams
2007-11-09
Functions and operators
Functions
A function can be used as standalone code to make it easier to execute multiple lines of
Javascript code, e.g. in response to <a
href="javascript:my_func();">Execute</a>
In Javascript 1.2, functions can also be assigned to a Javascript object to create a method
for that object. Use the keyword
this to refer to the object for which the function is a method.
<script type="text/javascript">
<!--
function sum(x,y) {
return x + y;
}
var total = sum(4,7);
alert(total);
-->
</script>
Operators
Javascript Operators
| Operator | Operation: | Syntax |
= | assignment | x="one"; |
[] | Access an array element |
array[<name|number>] |
() |
Invoke a function or separate operations |
myfunc(<values>) x=(y*z)-4; |
++ |
pre or post increment by one | ++x or x++ |
-- |
pre or post decrement by one | --x or x-- |
+ - | addition, minus | x-y+z |
+=,-=,*= |
shorthand for assign and add etc. |
a+=x; same as: a=a+x; |
! |
boolean false |
if (!var) {} |
delete | delete an object property |
delete object; |
new | create a new object |
new object; |
typeof | return type of operand |
typeof var; |
void | return undefined value |
var = void; |
* / % |
multiply, divide, modulus | c=((x*y)/z)%a; |
+ | string concatenation |
x="one"+" two"; |
<,<= |
less than, less than or equal | if(x<="2"){} |
>,>= |
greater than, greather than or equal | if(x>="2"){} |
==, != |
test for equality or inequality | if(x=="1") {} |
&& |
Logical AND | if((x!="2")&&(y=="1")) {} |
|| |
Logical OR | if((x!="2")||(y=="1")) {} |
? : | Conditional, if ?then:else |
if(x=="2") ? {y=2;} : {y=3;} |
. |
Access object property | object.property |
When using multiple operators, use () to make sure the calculation works as
you expect.
x=y-2*z; will actually execute as x=y-(2*z);. To calculate x as
y minus 2 all multiplied by z, use x=(y-2)*z;
Tutorial Pages:
»
It's flavours and versions
»
Structure and syntax
»
Data types and objects
» Functions and operators
»
JavaScript Statements A-F
»
JavaScript Statements G-Z
»
JavaScript Events
»
JavaScript Global Properties
»
Javascript code to identify your browser
»
Redirecting the browser once identified
Copyright © Neil Williams
|

|