JAVASCRIPT

Introduction to JavaScript:


JavaScript was first developed by the Netscape company, with the name "Live Script", a scripting language that extended HTML capabilities, offers a partial alternative to using a large number of CGI scripts to process forms and information that add dynamism to web pages.
HTML Web page authors offer some flexibility, but static. HTML documents can not interact with the user in other things more dynamic than it provides links to other resources (URLs). Creating CGI's (Common Graphics Interface) - [programs running on Web server and accept incoming information from the website and returns HTML] - led to the enrichment of work opportunities. Thus, an important step to interaction was made by JavaScript that allows to insert scripts that run within the web page, specifically in the user's browser, thus easing traffic between server and client. For example, a page for collecting data from the user can add JavaScript scripts to validate the accuracy of introduction and then the server sends only datas to be processed correctly.
JavaScript contains a fairly extensive list of features and commands to help with mathematical operations, string manipulation, sounds, images, objects and browser windows, checking URL links and data entries of the forms. The code for these actions can be inserted into the web page and executed by the visitor's computer.

Jscript 1.0 is roughly compatible with JavaScript 1.1, which is recognized by Netscape Navigator. However, later versions of JavaScript and specific differences between browsers platforms have started to give web developers enough problems. Netscape, Microsoft and other vendors have agreed to pass the language of international standardization organizations - ECMA, it finalized a specification language known as ECMAScript, recognized by all distributors. Although ECMA standard is useful, both Netscape and Microsoft have their own implementations of the language and continue to expand beyond the standard basic language.


 However, JavaScript became known as the standard for web scripting language. It is generally considered that there are ten fundamental aspects of the JavaScript language that any programmer in the language should knows:



  1. JavaScript can be included in HTML - JavaScript code is usually hosted and executed inside HTML documents. Most JavaScript objects have HTML tags that represent, so the program is included on the client side. JavaScript uses HTML to get into the web application working.
  2. JavaScript is dependent on the environment - JavaScript is a scripting language; the software program which is actually running is the web browser (Firefox, Opera, Netscape Navigator, Internet Explorer, Safari, etc..) It is important to consider this dependence browser when you use aplicatiiJavaScript.
  3. JavaScript is an entirely interpreted language - the script code will be interpreted by the browser before being executed. JavaScript does not require compilation or preprocessing, but remains part of the HTML document.
  4. JavaScript is a flexible language - In JavaScript we can declare a variable of some kind of type, or we can work with a variable although we not know the specified type before running.
  5. JavaScript is based on objects - JavaScript is an object oriented programming language like Java, but more accurately, is "based on objects" JavaScript object model is based on the instance and not on inheritance.
  6. JavaScript is event driven - most of the JavaScript code responds to events generated by user or system. HTML objects, such as buttons, are enhanced to support event handlers.
  7. JavaScript is not Java - The two languages have been created by different companies, the reason of these similar name is just marketing.
  8. JavaScript is many-functionally - this language can be used in a variety of contexts to solve various problems: graphics, mathematical, and others.
  9. JavaScript is evolving - JS is an evolving language, a positive thing, but it can generate problems, the programmers need to always check what version to use for applications that can be available for a larger number of users of different browsers.
  10. .JavaScript covers diverse contexts - this programming language is directed mainly towards the client side, but we can use JavaScript on server side too. JavaScript is the language native to some web development tools like Macromedia Dreamweaver or IntraBuilder Borland.

  •  Adding JavaScript in an HTML page

To insert JavaScript into an existing HTML document, it is necessary to introduce the label . This tag requires the "type" attribute, or the attribute "language" (the latter is depreciated in XHTML) that will specify to the browser the language used to interpret the included code.
Inside the label we write our JS code.
To write and execute JavaScript programs we need a simple text editor (such as Windows Notepad or emacs Unix) and a browser (Mozilla Firefox, Internet Explorer).- The "language" attribute (which is not used in XHTML, but only in standard HTML Web pages) - will have the following syntax:                language = "JavaScript"- the browser specifies which language is used.- The "type" attribute - replacement of "language" - will have the following syntax:                type = "text/javascript"- this tells the browser that the script is written in plaintext format with JavaScript code.We can also place the JS instructions in a separate JavaScript file, external, that will have the ".js" extension. To edit this file is needed only a simple text editor, like Notepad. The advantage of an external file is that we can use the same code in multiple HTML pages in case of a # necessary change in the JavaScript code, we just need to modify the data in a single file (the one with the extension. "js"), the disadvantage of this method is that in an ".js" external file we can't use HTML tags, but JavaScript instructions.If the JavaScript code is in an external file, the label 

 delimiting with this the JavaScript instructions, thus it avoids the appearance of script in web page:

 Syntax conventions:


In any language, the code has conventions and rules of syntax.
Now it's presented the JavaScript syntax rules:
  1. Case-sensitive - It makes distinction between large and small letters, such words as "examples, Examples" will be treated differently.
  1. Semicolon (;) - All line statements must end with a semicolon character (;) (Example" var1 = 3; var2 = 8;).
  1. Blank spaces - JavaScript ignores blank spaces, tabs and blank lines that appear in the instructions, they are useful for making code more structured and easy to read. Admit only the spaces that appear in strings. (Example: var1 = 2; is the same as var1 = 2;).
  1. Quotes - The single quotes ('') and double quotes (" ") are used to delimit strings. (Example: 'I learn JavaScript' or "I learn JavaScript").
  1. Special Characters - When we write scripts, sometimes we need to use a special character in values or in data output, or a key press such as the TAB key, or a new line. In that case we must use the backslash character "\" in front of one of the Escape codes:

  • \b - backspace 
  • \f - new page 
  • \n - new line 
  • \r - indicate a carriage return 
  • \t - indicate a pressing TAB key 
  • \\ - a backslash character 
  • \' - indicate an apostrophe (single quotes) 
  • \" - double quotes

  • - For example, if you want to display a text using document.write(), and that text should include quotes and backslash character "\", like ("JavaScript" Course \ www.MarPlo.net), to not confuse the script in code interpretation, becouse the quotes and backslash are part of the syntax, we add \ in front of these characters within the string. The command for display the string will be: document.write ("\" JavaScript \" Course \\ www.MarPlo.net");

  1. Comments - The comments within the code are necessary when we want to specify the role and functions of certain variables or instructions, for easy understanding of the script later.
    To add a comment on a single line, inside the code, use double slash //. All characters to the right of the double slash represent a comment.
            Example:   // Comment on a single line
    If you want to write comments on multiple lines, use /* at the beginning of the comment, and */ at its end
            Example:
    /* comment on ...
    multiple lineas

    ... */
    .

  1. The name of the variables and functions - 

    • - The first character must be a letter, an underscore (_) or $ sign.
      - The first character can not be a number.
      - the name should not contain blank space.
      - Do not use reserved words that are part of the JavaScript language (such as "array", "status", "alert"), because the interpreter program will not make the difference between these names and JavaScript commands with the same name.
-->

  •  Using variables

In a script (or program) we use constants and variables datas. The variables can change their values during program execution. These data are called "variables".
  • Variable = name of a location in computer memory, used to store data.
The simplest way to use and refer to a variable is to write it. The name of the variable permits the access at its value and also can change the value if necessary. 
You can create a variable and assign a value to it in this way:
- With statement var

var name = value;
- You can change its value just using the variable name (without "var"):
name = other_value;
Variable Types - Unlike other languages (such as Pascal or C), JavaScript has no fixed types of data, that allows you to change the type of a variable in the script, it can recognizes when the data is a string, numerical or other type. 
For example:

//var x = "xyz";
//x = 8;
Notice that the 'string' values (consisting of letters) are written between quotation marks (simples or doubles), and the 'number' can be written without quotation marks. 

The life spam of a variable - A variable written within a function is a local variable, its value is recognized only within that function, it doesn't exist out of that function. Thus, another function can declare a variable with same name, JS (JavaScript) treats the two as different variables ( functions and working with it will be explained in a subsequent lessons ).
The variables created out of the functions can be used everywhere in that script, inclusively inside the functions and other JS script from that HTML page.

  •  Operators

To work with datas in a script and manipulate variable values we use operators.
Operators are symbols and identifiers that determines how data are modified and how it is evaluated a combination of expressions and variables.

JavaScript recognizes:

  • binary operators - that need two operands.
  • unary operators - that need only one operand.
Operators are several types:
  • - Arithmetic operators
    - Assigning operators
    - Comparation operators
    - Logical operators (booleans)
    - Operators for strings
    - Typeof operator
    - Conditional operator (? :) 
    - Operators for functions
    - Operators for objects
These will be detailed in the next lesson.


  •  Arithmetic operators

We can say that arithmetic operators are the main operators for numbers, they make arithmetic operations:
  • = (used to asign values) - eg, (x=8)
  • + (used to add values) - eg, (x=7+8)
  • - (substraction) - eg, (x=7-8)
  • * (multiplication) - eg, (x=7*8)
  • / (division) - eg, (x=7/8)
- Besides these operators there are other special operators used in programming.
  • Modulo (%) - it determines the rest of the division of two numbers
    Example:
    • 8%3 result 2
      10%2 result 0
  • Increment (++) - This operator increases the value by one unit, is often used in programming.
  • For example, if we have a variable 'i', we can use the increment operator: i++ which is similar to i = i+1.
    Example:
    • x = 7;
      x++;
      the result is x = 8
  • Decrement (--) - This operator substract the value by one unit.
  • If we have a variable 'i', we can use the decrement operator: i-- which is similar to i = i-1.
    Example:
    • x = 7;
      x--;
      the result is x = 6
  • These two operators can be also placed before the variable name (++i, --i). The result value is the same, but the order of operation is different. In this case, first modify the value and then it assign it to the variable.

 Assigning operators

These operators evaluate first the operand on the right and the value is assigned to the variable of the left side of the sign "=".
OperatorExampleSame as
=     x = y        x = y
+=     x += y        x = x+y
-=     x -= y        x = x-y
*=     x *= y        x = x*y
/=     x /= y        x = x/y
%=     x %= y        x = x%y

  •  Comparation operators

Expressions using these operators make a question about two values which they compare. The answer can be TRUE or FALSE.
A commonly used comparison operator is the identity operator, represented by two equal signs "==".
Comparison operators are presented below:
OperatorMeaningExample
==     Identical     3 == 8   result FALSE
!=     Different     3 != 8   result TRUE
>     Bigger     3 > 8   result FALSE
<     Smaller     3 < 8   result TRUE
>=     Bigger or identical     3 >= 8   result FALSE
<=     Smaller or identical     3 <= 8   result TRUE

  •  Logical operators (booleans)

The logical operators compare two expressions and return TRUE or FALSE.
  • && - AND - It compare two expressions and return TRUE if both are true, otherwise it returns FALSE.
    • x = 5
      y = 8
      x<7 amp="" y="">3
      (return TRUE)
  • || - OR - It compare two expressions and return TRUE if at least one of them is true, otherwise it returns FALSE.
    • x = 5
      y = 8
      x>7 || y<3 span="">
      (return FALSE)
  • ! - NOT - unary operator, uses a single expression and returns TRUE if the expression is false, if the expression is true, returns FALSE.
    • x = 5
      y = 8
      !(x==y)
      (it returns TRUE becouse 'x' and 'y' are different)

 Operator used on strings

The "+" operator can also be used to join (add) string variables or text values together.
  • t1 = "Have a good "
    t2 = "life."
    t3 = t1+t2

    (The 't3' variable will contain the string "Have a good life.")

 The typeof operator

This operator returns the data type of its operand. It is especially useful to determine if a variable is defined with a specific data type. 
Studying the table below you can understand how thi operator works:

OperatorDescription
 typeof parseFloat returns the string 'function'
 typeof 33 returns the string 'number'
 typeof "some text" result 'string'
 typeof true returns the string 'boolean'
 typeof window returns the string 'object'

  •  Operators used on functions

Functions will be explained in one of the following lessons, however it is useful to be familiar with two operators:

1. The first is known as calling operator and is represented by a pair of parentheses () who are always after the function name. A function is declared as follows:
function function_name() {
  // Instructions
}
Then, the "callig operator" is used when we call the function in the script:
  • function_name()
The parentheses shows that we use a function. 

The second operator for functions is the comma operator (,) which is used to separate multiple arguments that a function receives. 
The arguments are always written inside parenthesis, and separated by commas. 
A function with two arguments would look like:

function function_name(arg1, arg2) {
  // Corpul functiei
}

  •  Operators used on objects

1. The main operator for objects is the character point (.). This operator allows us to refer to a member (variable, function or object) that belongs to the specified object. 
The syntax is:

  • objectName.variable_name
    objectName.function_name()
    objectName.childObject
This way of referring to an information, called point notation, returns the value of variable, function or object at the right.

2. The operator for array elements, a pair of brackets [], called the array index operator, allow us to refer to any member of an array. 
JavaScript arrays are objects and will be detailed in subsequent lessons. 
The syntax for using this operator is

  • array_name[key]

 Conditional operator "? :"


JavaScript contains a conditional operator ? : that assigns a value to a variable based on condition.
The syntax for using this operator:

  • variable = (condition) ? val1 : val2;
- It evaluates the condition, if it's True then the variable takes the value 'VAL1', otherwise, takes the value 'VAL2'. 
Here's an example:

< type="text/javascript">

var visitor = "man";
message = (visitor=="man") ? "Sir. " : "Dear Madam";
document.write(message) 
<>
If the variable "visitor" has the value 'man', the variable "message" gets the value 'Sir.', otherwise receives the value "Dear Madam". And the display instruction "document.write()" will display the value of "message".

  •  Operators precedence

When in expressions are used many operators, the JavaScript takes into account the precedence (the importance) of each operator. As in arithmetic, in an equation with multiplication and addition (2 + 3 * 4), if there aren't parentheses, multiplication is performed first. The same thing is for the programming operators, too. 
If there are several operators with the same precedence, JavaScript will evaluate them from left to right. 
The following table apresents in order the precedence of the operators:

OperatorDescription
()   []   .     for calling, data structures
!   ++   --     negation, increment
*   /   %     multiplication, division
+   -     addition, subtraction
<   <=   >   >=     comparison
==   !=     equality
&&     logical AND
||     logical OR
? :     conditionnal
=   +=   -=   *=   /=   %=     assigning
,     comma
JavaScript uses the following conditional instructions:
  • if - use if statement to execute some code only if a specified condition is True.
  • if ... else - it executes some code if a condition is True and another code if the condition is not true..
  • switch - selects which piece of code to be executed.

 The "if" statement


The general form of this instruction is the following:
if (condition) {
  The code will be executed if condition is true
}
- 'condition' can be any logical expresion.
- If 'ondition' return TRUE, executes the code within curly braces, otherwise, when the condition returns false, it passes over the code.
Here's an example. The following script prints "Hello" if the hour is greater than 11.
- We use the Date object, will be explained in another lesson.

- We defined the variable 'd', whose value is an object with the current date, then the variable 'time' takes only the hour from the variable 'd'. The condition of 'if' statement checks if 'time' is greater than 11 and if True executes the command of the braces, which displays the message.
If the hour is less than 11, the script will do nothing.

  •  The "if ... else" statement

In the previous example we saw that it displays "Hello!" if "time>11" and if not, nothing happens.
Using the instruction "if ... else" we can set commands to be executed when the condition of "if" instruction" is FALSE.
The general form of the "if ... else" instruction is:

if (condition) {
  The code will be executed if condition is True
}
else {
  The code will be executed if condition is False
}
- 'condition' can be any logical expresion.
If 'ondition' return TRUE it is executed the code inside the first braces (that belongs to "if"), otherwise, when the condition returns false it is executed the code of the second group of braces (after else).
Here again the previous example, this time using the "if ... else" statement.
The script displays "Hello!" if the hour is greater than 11, otherwise display "It's ... o`clock".


- If 'time' is less than 11 the script will execute the code of second braces group, from "else".

  •  switch statement

This instruction is used to compare a value with others from a list.
The syntax of switch instruction is:
switch (expresion) {
case value1:
    code executed if expresion = value1
    break
case value2:
    code executed if expresion = value2
    break
case value3:
    code executed if expresion = value3
    break
default :
    code executed if expresion is other then value1, valoare2 or valoare3
}
- First we have a single expression between parentheses (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Usebreak to prevent the code from running into the next case automatically.
Here is a sample script that displays a message depending on weekdays:

- The variable 'day' takes the number of the week-day from the variable 'd' (Sunday = 0, Monday = 1, ...).
- The switch statement compares the value of "day" with the value of each "case". If there is a match, the block of code associated with that 'case' is executed.
- If none of the values of 'case' match the variable 'day', will execute the code associated with 'default'.

For is a repetitive instruction. It is used when you wish to perform a command several times.
In javaScript we can use the following repetitive instruction:
  • for - loops through a block of code a specified number of times
    for ... in - loops through the elements of an array or through the properties of an object.
    Array.forEach - Executes a provided function once per array element.

 The for loop


The for loop is used when you know how many times the script should run. It has the following syntax:
for (nr_start; condition_nr; nr_increment) {
    code to be executed
}
- "nr_start" specifies a variable and assigns an initial value to it. It sets up the initial state for the loop.
"condition_nr" This second part tests for a condition. The loop will keep running as long as this condition is True.
"nr_increment increments or decrements the "nr_start", then its value is checked again with the second parameter, "condition_nr", until the result is FALSE.
Inside the for instruction you can introduce other "for" or any conditional statements.
Here's a simple example using the "for":


for (i=0; i<5 br="" document.write="" i=""> i = "+i);
}

- These statements define a loop that uses the variable "i", initializes it with the value of zero, and loops as long as the value of "i" is less than 5.
- The increment expression, "i++', adds one unit to the value of "i" with each iteration of the loop.
- Because this happens at the end of the loop, the output will list the numbers zero through five.
This script will display the following result:

i = 0
i = 1
i = 2
i = 3
i = 4

 The for ... in loop

The for…in loop is less flexible than an ordinary for() loop. This instruction goes through the elements of an object (or an Array) and gets the name (or key) of each property of that object.
The "for ... in" has the fallowing sintax:
for (variable in object) {
    instructions
}
- "variable" is a index variable that takes the name of the property. For each iteration of the loop, the variable is set to the next property of the object.
Example:


var obj = {apple:100, bool:false, astring:"coursesweb.net"};
for (var prop in obj) {
  document.write(prop + ' - '+ obj[prop]+ '
');
}

- Results:
apple - 100
bool - false
astring - coursesweb.net


  • ForEach

Another loop structure built on the "for" keyword, is the forEach property. Executes a provided function once per array element.
The general syntax is:
array.forEach(callbackF)
- callbackF = the function to execute for each element. This function can have three parameters: callbackF(val, index, array).
      - val = the element value.
      - index = the element index.
      - array = the array being traversed.

Example, printing the contents of an array.


var arr = [100, 'google://www.learningfinest.blogspot.com/"];

// callback function
function parseArr(val, index) {
  document.write('['+ index + '] = ' + val +'
');
}

arr.forEach(parseArr);- This will produce the following output:
[0] = 100
[1] = google
[2] = 
www.learningfinest.blogspot.com


while loop just looks at a short comparison and repeats until the comparison is no longer True.

  •  The while loop

The while loops don't necessarily use a variable to count. Instead, they execute as long as a condition is True. In fact, if the condition starts out as false, the statements won’t execute at all.
The while statement includes the condition in parentheses, and it is followed by a block of statements within braces. Here is its syntax:
while (condition) {
  code to be executed
}
Here's the earlier example, from the "for" instruction, this version use the "while" loop.

var i = 0;
while (i<5 br="" document.write=""> i = "+i);
  i++;
}

- First it's declared a variable "i" with the value of 0. The "while" statement checks the condition (here i<5 5.="" again="" and="" block="" brackets.="" check="" code="" condition.="" execution="" i="" increments="" inside="" it="" loop="" of="" permits="" reach="" s="" span="" stop="" the="" true="" value="" when="" which="" will="">
- This script displays the following results:

i = 0
i = 1
i = 2
i = 3
i = 4

  •  do ... while loops

The do...while loop is a variant of the "while" loop. First will be executed the block of code, and then it will repeat the loop as long as the specified condition is true.
The syntax is:
do {
  code to be executed
}
while (condition)
Here is a simple example:

var x = 8;
do {
  document.write("
 x = "+x);
  x++;
}
while (x<5 font="">
- This example display "x = 8".
As you can notice, although the condition is false (x<5 braces="" code="" executed="" is="" of="" once.="" span="" still="" the="">


Alert, Prompt and Confirm are predefined dialog windows, they belong directly to the JavaScript object "window".

  •  Alert

Alert is a very basic notice box with a message inside it.
Syntax:

window.alert("alert_text");
- The string of text will be displayed in the alert pop-up box. When an alert box pops up, the user will have to click "OK" to proceed.
- For example, the next script opens an Alert window with the message "Welcome".


window.alert("Welcome");

- The user will be presented with a small box containing only the message and a button marked OK, like next image.
Alert window

  •  Confirm

The confirm window displays a confirmation dialog box to the viewer, who must then click OK or Cancel to proceed.
A confirm box is often used if you want the user to verify or accept something.
Syntax:
window.confirm("Question")
- The confirm box displays the text "Question" and two buttons "OK" and "Cancel". 
- If the user clicks "OK", the box returns True. If the user clicks "Cancel", the box returns False.
Aceasta fereastra este folosita pentru a fi executata o comanda cand este apasat butonul "OK" (returneaza TRUE) si alta comanda cand este apasat butonul "Cancel" (returneaza FALSE) 
The next example opens a confirm window with the question "The result of 0+0 is 0?". If it's clicked "OK" it shows an Alert window with the message "Corect", but if it's clicked "Cancel" it opens an Alert window with the message "Incorrect".


var ques = window.confirm("The result of 0+0 is 0?");
if (ques) alert("Corect");
else alert("Incorrect");

The confirm box will look like:
Confirm box

  •  Prompt

Prompt box is used if you want the user to input information. Using this window, you can do things based on what the viewer enters into the text box at the prompt.
Syntax:

window.prompt("Message", DefaultValue)
- The "Message" is the text that will be shown above the text box. The "DefaultValue" argument will be the starting text inside the text box. If you don't want any text in the text box, leave this as an empty string.
- The dialogue will return a string containing the text typed by the user or "null" if the user didn't type anything:
The next example opens a Prompt dialog box.


var msg = window.prompt("Write your name", "Name");
alert(msg);

The prompt window will look like:
Prompt window
- If the user clicks "OK" will display an Alert window with the name typed in the text box, if it's clicked "Cancel", the Alert will display "null".


Functions

Functions help organize the various parts of a script into different tasks that must be accomplished.
A function contains code that will be executed by an event or by a call to the function.
Functions can be used more than once within a script to perform their task. Rather than rewriting the entire block of code, you can simply call the function again.
There are two kinds of functions:
  • predefined - for example: "parseInt(string)", "parseFloat(string)", ...
  • Created by developer
    • - that returns a value
    • - not return a value

                  Declaring Functions

Functions can be defined both in the and in the section of a document. However, to assure that a function is read/loaded by the browser before it is called, it's better to put functions in the section.
The most basic way to define a function is using the word "function", the name of the function followed by two parentheses (where we can add the parameters) and a pair of cfurly brackets that contain the code of the function.
Function syntax
function functionName(var1, var2, ...) {
  code to be executed
}
The parameters var1, var2, etc. are variables or values passed into the function. The brackets { and the } defines the start and end of the function.
- A function with no parameters must include the parentheses () after the function name.

Function names are case sensitive, be sure you use the identical name when you call the function.
The word function must be written in lowercase letters.

  • The Return Statement

return statement is used to specific a value that a function returns to the main script. You place the return statement as the last line of the function before the closing curly bracket and end it with a semicolon.
For example, to return the value of a variable "some_var", the return statement looks like this:
                return some_var; The next function returns the value of a variable 'z' that contain the amount of two parameers (x, y):

function amount(x, y) {
  var z = x+y;
  return z;
}
- The "amount" is the name of the function, "x" and "y" are the parametres. The function returns the value of "z" variable, that contain the amount of "x" and "y".

  • Calling Functions

After the function is defined, we can call and use it.
You may call a function from anywhere within a page (or even from other pages if the function is embedded in an external .js file). You can even call a function inside of another function.
A function with parameters can be called using the syntax:

functionName(arg1, arg2, ...);
- "arg1", "arg2", ... are the arguments passed to the function.
A function without paramentre with the following syntax:

functionName();
Note that the function call no longer use the word "function" and braces 
In the place of the script where we call a function it's executed the code of that function.



JavaScript Strings

First must know what objects are in programming and the fundamental concepts of the object-oriented programming (OOP), becouse thestring is recognized as an object in JavaScript.
JavaScript isn't a object-oriented (OO), such as C++ or Java, but is based on objects.
In the world around us the objects are, for example: a book, a car, a television ..., In JavaScript the object s are, for example: a form, a window, buttons, images, strings ...
JavaScript sees all elements of a page as objects.
An object is a collection of values called properties.
When a property is function, it’s referred to as a method.

  •  String object

There is various ways to create a string: using the new keyword or with the literal form, surround characters with either single quotes (') or double quotes (").
var instance_name = new String("string value here");      // using the "new" keyword

// Literal form
var variable_name1 = "some text: coursesweb.net";     // with double quotes
// or
var variable_name1 = 'some text: coursesweb.net';     // with single quotes
- The most indicated way is the literal form (with quotes).
But whichever quote you use (single or double), you can’t use it again in the middle of the string because that will end the string early.
However, you can escape any character with a backslash (\) to solve this or use single primes inside double primes (and vice versa).

-->
Strings have one built-in property, length.

  • length - returns the number of characters in a string
-->

  • String Methods

The String object has a lot of methods, as shown:

Methods That Add HTML Tags

  • anchor(name) - used to create an HTML anchor. Returns the string embedded in the tag (string
    var txt = 'String object';
    txt.anchor('strings');
    alert(txt.anchor("myanchor"));
  • big() - display a string in a big font. Returns the string embedded in the tag (string)
    var str = "coursesweb.net";
    document.write(str.big());
  • blink() - display a blinking string. Returns the string embedded in the tag (string)
    var str = 'JavaScript strings';
    document.write(str.blink());
  • bold() - display a string in bold. Returns the string embedded in the ta (string)
    var str = 'JavaScript strings';
    document.write(str.bold());
  • fixed() - display a string as teletype text. Returns the string embedded in the tag (string)
    var str = 'String object';
    document.write(str.fixed());
  • fontcolor(color) - display a string in a specified color. This method returns the string embedded in the tag (string)
    var str = 'String object';
    document.write(str.fontcolor('blue'));  
  • fontsize(size) - show a string in a specified size (between 1 and 7); embedded in the tag (string)
    var txt = "Have a good day";
    document.write(txt.fontsize(5));
  • italics() - show a text in italic. Returns the text in the tag (text)
    var txt = "Have a good day";
    document.write(txt.italics());
  • link(url) - makes a string as a hyperlink. This method returns the string in the tag (string)
    var str = "Free Web Developments Tutorials";
    document.write(str.link("http://coursesweb.net"));
  • small() - display a text in small font, return it in (text)
    var str = "Web programming";
    document.write(str.small());
  • strike() - display a string that is struck out. Return it in the (string)
    var str = "Web programming";
    document.write(str.strike());
  • sub() - display a string as subscript text. Return it in the (text)
    var str = "JS programming";
    document.write(str.sub());
  • sup() - display a string as superscript text. Return it in the (text)
    var str = "JS strings tutorial";
    document.write(str.sup());  

The Number and Math Objects

The Number object

The Number object is another predefined JavaScript object that offers some useful properties and methods for use with numbers.

Properties of the Number object

  • MAX_VALUE - Returns the largest number possible in JavaScript (1.79e+308)
  • MIN_VALUE - Returns the smallest number possible in JavaScript (5e-308)
  • NaN - Represents the value of "Not a Number"
  • NEGATIVE_INFINITY - Represents the negative infinity
  • NEGATIVE_INFINITY - Represents the infinity
  • prototype - Enables you to add properties to the object
Example:
In the following JS script we create a new property (mult8) to the Number object, this new property multiplies by 8 the value of a variable.

var nr = 7;

// creates a new property ( mult8 ) to the Number object
Number.prototype.mul8 = nr*8;

// uses the property "mult8"
document.write(nr.mul8);       // 65

No comments:

Post a Comment