Difference between revisions of "JavaScript"

From Sinfronteras
Jump to: navigation, search
(Using JavaScript)
(Data types)
Line 12: Line 12:
  
 
JavaScript is one of the 3 languages all web developers must learn:
 
JavaScript is one of the 3 languages all web developers must learn:
# HTML to define the content of web pages
+
 
# CSS to specify the layout of web pages
+
#HTML to define the content of web pages
# JavaScript to program the behavior of web pages
+
#CSS to specify the layout of web pages
 +
#JavaScript to program the behavior of web pages
  
  
Line 235: Line 236:
 
<br />
 
<br />
 
==Data types==
 
==Data types==
{| class="wikitable" style="margin: 0 auto;"
+
There are five types of primitive data types in JavaScript.
|+
+
<br />
 +
{| class="wikitable"
 
!
 
!
 
!'''Data Type'''
 
!'''Data Type'''
!'''Default Value'''
 
!'''Size'''
 
 
!Description
 
!Description
! colspan="2" |Example
+
!Example
 +
|-
 +
| rowspan="6" |'''Primitives'''
 +
|'''Number'''
 +
|There is only one type of Number in JavaScript. Numbers can be written with or without a decimal point. A number can also be <code>+Infinity</code>, <code>-Infinity</code>, and <code>NaN</code> (not a number).
 +
|
 +
var num1 = 32;
 +
 
 +
var num2 = +Infinity;
 
|-
 
|-
| rowspan="6" |'''Numeric'''
+
|'''String'''
|byte
+
|Strings are used for storing text. Strings must be inside of either double or single quotes. In JS, Strings are immutable (they cannot be changed).
|0
+
|
|1 byte
+
var str1 = 'hello, it is me';
|Stores whole numbers from -128 to 127
+
 
| colspan="2" |<code>byte myNum = 100;
+
var str2 = "hello, it's me";
System.out.println(myNum);</code>
 
 
|-
 
|-
|short
+
|'''Boolean'''
|0
+
|A boolean represents only one of two values: true, or false.
|2 byte
+
|
|Stores whole numbers from -32,768 to 32,767
+
var boo1 = true;
| colspan="2" |<code>short myNum = 5000;</code>
+
 
 +
var boo2 = false;
 
|-
 
|-
|int
+
|'''Undefined'''
|0
+
|A variable that has no value is '''undefined'''.
|4 byte
+
|
|Stores whole numbers from -2,147,483,648 to 2,147,483,647
+
var testVar;
| colspan="2" |<code>int myNum = 100000;</code>
+
 
 +
console.log(testVar); // undefined
 
|-
 
|-
|long
+
|'''Null'''
|0L
+
|Null has one value: '''null.''' It is explicitly nothing.
|8 byte
+
|var nothing = null;
|Stores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
 
| colspan="2" |<code>long myNum = 15000000000L;</code>
 
 
|-
 
|-
|float
+
|'''Symbol'''
|0.0f
+
|Symbols are new in ES6. A Symbol is an '''immutable''' primitive value that is '''unique'''. For the sake of brevity, that is the extent that this article will cover Symbols.
|4 byte
+
|const mySymbol = Symbol('mySymbol');
|Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits.
 
 
 
The <code>float</code> data type can store fractional numbers from 3.4e−038 to 3.4e+038. Note that you should end the value with an "f":
 
|<code>float myNum = 5.75f;</code>
 
| rowspan="2" |'''Scientific Numbers'''
 
 
 
A floating point number can also be a scientific number with an "e" to indicate the power of 10:
 
 
 
 
 
<code>float f1 = 35e3f;</code>
 
 
 
<code>double d1 = 12E4d;</code>
 
 
|-
 
|-
|double
+
| rowspan="3" |'''Non-primitives'''
|0.0d
+
|'''Object'''
|8 byte
+
|An object is a collection of properties. These properties are stored in key/value pairs. Properties can reference any type of data, including objects and/or primitive values.
|Stores fractional numbers. Sufficient for storing 15 decimal digits.
+
|<syntaxhighlight lang="javascript">
 
+
var obj = {
The <code>double</code> data type can store fractional numbers from 1.7e−308 to 1.7e+308. Note that you should end the value with a "d"
+
  key1: 'value',
|<code>double myNum = 19.99d;</code>
+
  key2: 'value',
 +
  key3: true,
 +
  key4: 32,
 +
  key5: {}
 +
}
 +
</syntaxhighlight>
 
|-
 
|-
|'''Character'''
+
|'''Array'''
|char
+
|
|'\u0000'
+
|
|2 byte
 
|The <code>char</code> data type is used to store a '''single''' character. The character must be surrounded by single quotes, like 'A' or 'c':
 
| colspan="2" |<code>char myGrade = 'B';</code>
 
 
 
 
 
Alternatively, you can use ASCII values to display certain characters:
 
 
 
<code>char a = 65, b = 66, c = 67;</code>
 
 
 
'''Tip:''' A list of all ASCII values can be found at https://www.w3schools.com/charsets/ref_html_ascii.asp
 
 
|-
 
|-
|'''Boolean'''
+
|'''RegExp'''
|boolean
+
|
|false
+
|
|1 bit
 
|Stores true or false values
 
| colspan="2" |<code>boolean isJavaFun = true;</code>
 
 
|}
 
|}
 
 
 
<br />
 
<br />
 
 
==Some comments about the Syntax==
 
==Some comments about the Syntax==
 
https://www.w3schools.com/js/js_syntax.asp
 
https://www.w3schools.com/js/js_syntax.asp
Line 325: Line 309:
 
<br />
 
<br />
 
===Variables===
 
===Variables===
* JavaScript uses the '''''var''''' keyword to declare variables. An equal sign is used to assign values to variables. In this example, x is defined as a variable. Then, x is assigned (given) the value 6:
 
  
* JavaScript variables value can be changed anytime.
+
*JavaScript uses the '''''var''''' keyword to declare variables. An equal sign is used to assign values to variables. In this example, x is defined as a variable. Then, x is assigned (given) the value 6:
 +
 
 +
*JavaScript variables value can be changed anytime.
  
* JavaScript variables are loosely-typed which means it does not require a data type to be declared.
+
*JavaScript variables are loosely-typed which means it does not require a data type to be declared.
  
 
<blockquote>
 
<blockquote>
Line 343: Line 328:
  
  
* A variable declared without a value will have the value '''''undefined''''':
+
*A variable declared without a value will have the value '''''undefined''''':
 
<blockquote>
 
<blockquote>
 
<syntaxhighlight lang="javascript">
 
<syntaxhighlight lang="javascript">
Line 359: Line 344:
 
<br />
 
<br />
 
===Identifier===
 
===Identifier===
* Identifiers are names.
+
 
* In JavaScript, identifiers are used to name variables (and keywords, and functions, and labels).
+
*Identifiers are names.
* The rules for legal names are much the same in most programming languages.
+
*In JavaScript, identifiers are used to name variables (and keywords, and functions, and labels).
* In JavaScript, the first character must be a letter, or an underscore (_), or a dollar sign ($). Subsequent characters may be letters, digits, underscores, or dollar signs.
+
*The rules for legal names are much the same in most programming languages.
* Numbers are not allowed as the first character. This way JavaScript can easily distinguish identifiers from numbers.
+
*In JavaScript, the first character must be a letter, or an underscore (_), or a dollar sign ($). Subsequent characters may be letters, digits, underscores, or dollar signs.
* All JavaScript identifiers are '''case sensitive:'''
+
*Numbers are not allowed as the first character. This way JavaScript can easily distinguish identifiers from numbers.
:* The variables lastName and lastname, are two different variables.
+
*All JavaScript identifiers are '''case sensitive:'''
:* JavaScript does not interpret VAR or Var as the keyword var.
+
 
* Hyphens are not allowed. It is not allowed to name a variable as «first-name». Hyphens are reserved for subtractions.
+
:*The variables lastName and lastname, are two different variables.
 +
:*JavaScript does not interpret VAR or Var as the keyword var.
 +
 
 +
*Hyphens are not allowed. It is not allowed to name a variable as «first-name». Hyphens are reserved for subtractions.
  
  
Line 377: Line 365:
 
JavaScript Display Possibilities. JavaScript can "display" data in different ways:
 
JavaScript Display Possibilities. JavaScript can "display" data in different ways:
  
* Writing into an HTML element, using <code>innerHTML</code>.
+
*Writing into an HTML element, using <code>innerHTML</code>.
* Writing into the HTML output using <code>document.write()</code>.
+
*Writing into the HTML output using <code>document.write()</code>.
* Writing into an alert box, using <code>window.alert()</code>.
+
*Writing into an alert box, using <code>window.alert()</code>.
* Writing into the browser console, using <code>console.log()</code>.
+
*Writing into the browser console, using <code>console.log()</code>.
  
 
<br />
 
<br />
Line 391: Line 379:
  
 
|To access an HTML element, JavaScript can use the <code>document.getElementById(id)</code> method. The <code>id</code> attribute defines the HTML element.
 
|To access an HTML element, JavaScript can use the <code>document.getElementById(id)</code> method. The <code>id</code> attribute defines the HTML element.
 
 
The <code>innerHTML</code>  property defines the HTML content.<syntaxhighlight lang="html">
 
The <code>innerHTML</code>  property defines the HTML content.<syntaxhighlight lang="html">
 
<!DOCTYPE html>
 
<!DOCTYPE html>
Line 411: Line 398:
 
|-
 
|-
 
| rowspan="2" |Writing into the HTML output using '''document.write()'''
 
| rowspan="2" |Writing into the HTML output using '''document.write()'''
* It is convenient and It should only be used for testing purposes.
+
*It is convenient and It should only be used for testing purposes.
 
|<syntaxhighlight lang="html">
 
|<syntaxhighlight lang="html">
 
<!DOCTYPE html>
 
<!DOCTYPE html>
Line 445: Line 432:
 
|-
 
|-
 
|Writing into an alert box using '''window.alert()'''
 
|Writing into an alert box using '''window.alert()'''
* You can use an alert box to display data.
+
*You can use an alert box to display data.
 
|<syntaxhighlight lang="html">
 
|<syntaxhighlight lang="html">
 
<!DOCTYPE html>
 
<!DOCTYPE html>
Line 463: Line 450:
 
|-
 
|-
 
|Writing into the browser console using '''console.log()'''
 
|Writing into the browser console using '''console.log()'''
* For debugging purposes, you can use the <code>console.log()</code> method to display data.
+
*For debugging purposes, you can use the <code>console.log()</code> method to display data.
 
|<syntaxhighlight lang="html">
 
|<syntaxhighlight lang="html">
 
<!DOCTYPE html>
 
<!DOCTYPE html>

Revision as of 00:21, 15 October 2019

https://www.javascript.com/

https://www.w3schools.com/js/default.asp

JavaScript enables interactive web pages and is an essential part of web applications. JavaScript was initially created to execute in the browser. Historically, JavaScript was used primarily for client-side scripting, in which scripts written in JavaScript are embedded in a HTML webpage and run by a JavaScript engine in the user's web browser. Today, JavaScript can execute not only in the browser, but also on the server, or actually on any device that has a special program called the JavaScript engine. Node.js, for example, is an open-source, cross-platform JavaScript run-time environment that executes JavaScript code outside of a browser.

Web pages are not the only place where JavaScript is used. Many desktop and server programs use JavaScript. Node.js is the best known. Some databases, like MongoDB and CouchDB, also use JavaScript as their programming language.


Note: JavaScript and Java are completely different languages, both in concept and design.


JavaScript is one of the 3 languages all web developers must learn:

  1. HTML to define the content of web pages
  2. CSS to specify the layout of web pages
  3. JavaScript to program the behavior of web pages


What JavaScript can do: What JavaScript can do / What is used for / some of the most important methods:

  • JavaScript Can Change HTML Content
  • JavaScript Can Change HTML Attribute Values
  • JavaScript Can Change HTML Styles (CSS)
  • JavaScript Can Hide HTML Elements
  • JavaScript Can Show HTML Elements


JSFiddle

https://jsfiddle.net/

JSFiddle is an online community for testing and showcasing user-created and collaborational HTML, CSS and JavaScript code snippets, known as 'fiddles'. It allows for simulated AJAX calls.



Installation


IDE for JavaScript


Using JavaScript

Historically, JavaScript was used primarily for client-side scripting, in which scripts written in JavaScript are embedded in a HTML webpage and run by a JavaScript engine in the user's web browser. Today, JavaScript can execute not only in the browser, but also on the server, or actually on any device that has a special program called the JavaScript engine. Node.js, for example, is an open-source, cross-platform JavaScript run-time environment that executes JavaScript code outside of a browser.



From the web browser console

Let's see how that works. From the Web Browser console (Ctrl + i), you can display the structure of the page and make changes on it using JS. For example, you can display the body of the web page by executing:

document.body


You can make changes in the background color with:

document.body.style.backgroundColor = "red";



JS code embedded in a HTML page

Try it at https://jsfiddle.net/

<!DOCTYPE html>
<html>
<body>

<h2>My First JavaScript</h2>

<button type="button"
onclick="document.getElementById('demo').innerHTML = Date()">
Click me to display Date and Time.</button>

<p id="demo"></p>

</body>
</html>

The method that is executed onclick: "document.getElementById('demo').innerHTML = Date()" is a JS method that has been embedded into a HTML code.



Inside a HTML file using the -script- Tag

https://www.w3schools.com/js/js_whereto.asp

In HTML, JavaScript code must be inserted between script tags.

Old JavaScript examples may use a type attribute: <script type="text/javascript"> . The type attribute is not required. JavaScript is the default scripting language in HTML.

You can place any number of scripts in an HTML document.

Scripts can be placed in the <body> , or in the <head> section of an HTML page, or in both.


Example 1 - In this example, a JavaScript function is placed in the <head> section of an HTML page. The function is invoked (called) when a button is clicked:

Try it at https://jsfiddle.net/

<!DOCTYPE html>
<html>

<head>
<script>
function myFunction() {
  document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>

<h1>A Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>

</body>
</html>


Example 2 - In this example, a JavaScript function is placed in the <body> section of an HTML page. The function is invoked (called) when a button is clicked:

Try it at https://jsfiddle.net/

<!DOCTYPE html>
<html>
<body>

<h1>A Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>

<script>
function myFunction() {
 document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>

</body>
</html>



Calling an external JS file from a HTML page

JavaScript files have the file extension .js


  • You can place an external script reference in head or body as you like.
  • The script will behave as if it was located exactly where the <script> tag is located.
  • External scripts cannot contain <script> tags.


External JavaScript Advantages:

  • It separates HTML and code
  • It makes HTML and JavaScript easier to read and maintain
  • Cached JavaScript files can speed up page loads


myScript.js
function myFunction() {
 document.getElementById("demo").innerHTML = "Paragraph changed.";
}


To use an external script, put the name of the script file in the src (source) attribute of a <script> tag:

<script src="myScript.js"></script>


External scripts can be referenced with a full URL or with a path relative to the current web page:


Example 1 - This example uses a full URL to link to a script:

Try it at https://jsfiddle.net/

<!DOCTYPE html>
<html>
<body>

<h2>External JavaScript</h2>

<p id="demo">A Paragraph.</p>

<button type="button" onclick="myFunction()">Try it</button>

<p>(myFunction is stored in an external file called "myScript.js")</p>

<script src="https://www.w3schools.com/js/myScript.js"></script>
<!--  <p>(myFunction is stored in an external file called "myScript.js")</p>  -->
</body>
</html>



From the Nodejs console

See Nodejs

Go to a terminal and execute the command «node». This will open the Nodejs Shell/Interpreter:

node

Try some commands in the shell:

console.log("Hello world!");
function myFunction() {
    console.log("Hello world!");
}


You can also create a JS script and run it using the node command:

javaScript.js
function add(){
    var result = 5 + 10;
    console.log(result);
}
add()
node javaScript.js



Data types

There are five types of primitive data types in JavaScript.

Data Type Description Example
Primitives Number There is only one type of Number in JavaScript. Numbers can be written with or without a decimal point. A number can also be +Infinity, -Infinity, and NaN (not a number).
var num1 = 32;
var num2 = +Infinity;
String Strings are used for storing text. Strings must be inside of either double or single quotes. In JS, Strings are immutable (they cannot be changed).
var str1 = 'hello, it is me';
var str2 = "hello, it's me";
Boolean A boolean represents only one of two values: true, or false.
var boo1 = true;
var boo2 = false;
Undefined A variable that has no value is undefined.
var testVar;
console.log(testVar); // undefined
Null Null has one value: null. It is explicitly nothing. var nothing = null;
Symbol Symbols are new in ES6. A Symbol is an immutable primitive value that is unique. For the sake of brevity, that is the extent that this article will cover Symbols. const mySymbol = Symbol('mySymbol');
Non-primitives Object An object is a collection of properties. These properties are stored in key/value pairs. Properties can reference any type of data, including objects and/or primitive values.
var obj = {
  key1: 'value',
  key2: 'value',
  key3: true,
  key4: 32,
  key5: {}
}
Array
RegExp


Some comments about the Syntax

https://www.w3schools.com/js/js_syntax.asp



Variables

  • JavaScript uses the var keyword to declare variables. An equal sign is used to assign values to variables. In this example, x is defined as a variable. Then, x is assigned (given) the value 6:
  • JavaScript variables value can be changed anytime.
  • JavaScript variables are loosely-typed which means it does not require a data type to be declared.
var x, y;
x = 5;
y = 6;
var total = x + y;
var pi = 3.14;
var person = "John Doe";


  • A variable declared without a value will have the value undefined:
var carName;



Comments

Code after double slashes // or between /* and */ is treated as a comment.



Identifier

  • Identifiers are names.
  • In JavaScript, identifiers are used to name variables (and keywords, and functions, and labels).
  • The rules for legal names are much the same in most programming languages.
  • In JavaScript, the first character must be a letter, or an underscore (_), or a dollar sign ($). Subsequent characters may be letters, digits, underscores, or dollar signs.
  • Numbers are not allowed as the first character. This way JavaScript can easily distinguish identifiers from numbers.
  • All JavaScript identifiers are case sensitive:
  • The variables lastName and lastname, are two different variables.
  • JavaScript does not interpret VAR or Var as the keyword var.
  • Hyphens are not allowed. It is not allowed to name a variable as «first-name». Hyphens are reserved for subtractions.



Output

https://www.w3schools.com/js/js_output.asp

JavaScript Display Possibilities. JavaScript can "display" data in different ways:

  • Writing into an HTML element, using innerHTML.
  • Writing into the HTML output using document.write().
  • Writing into an alert box, using window.alert().
  • Writing into the browser console, using console.log().


Different ways/Method Example

Try the codes at https://jsfiddle.net/

Writing into an HTML element using innerHTML To access an HTML element, JavaScript can use the document.getElementById(id) method. The id attribute defines the HTML element. The innerHTML property defines the HTML content.
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p>My First Paragraph</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>

</body>
</html>
Writing into the HTML output using document.write()
  • It is convenient and It should only be used for testing purposes.
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p>My First Paragraph</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>

</body>
</html>
Using document.write() after an HTML document is loaded, will delete all existing HTML:
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p>My first paragraph.</p>

<button type="button" onclick="document.write(5 + 6)">Try it</button>

</body>
</html>

Writing into an alert box using window.alert()
  • You can use an alert box to display data.
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p>My first paragraph.</p>

<script>
window.alert(5 + 6);
</script>

</body>
</html>
Writing into the browser console using console.log()
  • For debugging purposes, you can use the console.log() method to display data.
<!DOCTYPE html>
<html>
<body>

<script>
console.log(5 + 6);
</script>

</body>
</html>


Control flow statements


If statements


For Loops


While Loops


Functions

A JavaScript function is a block of JavaScript code, that can be executed when "called" for.

For example, a function can be called when an event occurs, like when the user clicks a button.



Methods


Some of the most important methods

https://www.w3schools.com/js/js_intro.asp



Change HTML Content

This example uses the method to "find" an HTML element (with id="demo") and changes the element content (innerHTML) to "Hello JavaScript":

document.getElementById("demo").innerHTML = "Hello JavaScript";



Change HTML Attribute Values

In this example JavaScript changes the value of the src (source) attribute of an tag:

<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on the light</button>

<img id="myImage" src="pic_bulboff.gif" style="width:100px">

<button onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn off the light</button>



Change HTML Styles - CSS

Changing the style of an HTML element, is a variant of changing an HTML attribute:

document.getElementById("demo").style.fontSize = "35px";



Hide HTML Elements

Hiding HTML elements can be done by changing the display style:

document.getElementById("demo").style.display = "none";



Show HTML Elements

Showing hidden HTML elements can also be done by changing the display style:

document.getElementById("demo").style.display = "block";