Difference between revisions of "JavaScript"

From Sinfronteras
Jump to: navigation, search
 
(67 intermediate revisions by the same user not shown)
Line 1: Line 1:
* Javascript runs on the client side in the browser.
+
 
* Javascript code is interpreted by the browser.
+
<br />
* In JavaScript, instructions are called statements and are separated by a semicolon (;).
+
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 <span style="color:green">'''and run by a JavaScript Engine in the user's web browser'''</span>. 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:
 +
 
 +
#HTML to define the content of web pages
 +
#CSS to specify the layout of web pages
 +
#JavaScript to program the behavior of web pages
 +
 
 +
 
 +
'''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.
 +
 
 +
 
 +
<br />
 +
 
 +
==Installation==
 +
 
 +
 
 +
<br />
 +
==IDE for JavaScript==
 +
 
 +
 
 +
<br />
 +
==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.  
  
  
 
<br />
 
<br />
==Script tag in a html file==
+
===From the web browser console===
* <script> tag allows us to include a piece of Javascript in a HTML document:
+
Let's see how that works. Open the Web Browser console («Ctrl + Shit + i» and go to the console tab). This console is a JavaScript shell. You can so execute JavaScript commands.
<syntaxhighlight lang="php">
+
 
<h1>Testing alert</h1>
+
 
<script>alert("hello!");</script>
+
For example, you can display the body of the web page by executing:
 +
<syntaxhighlight lang="javascript">
 +
document.body
 
</syntaxhighlight>
 
</syntaxhighlight>
  
* Including large programs directly in HTML documents is often impractical. The <script> tag can be given an src attribute in order to fetch a script file (a text file containing a JavaScript program) from a URL.
+
 
<syntaxhighlight lang="php">
+
You can make changes in the background color with:
<h1>Testing alert</h1>
+
<syntaxhighlight lang="javascript">
<script src="js/myfile.js"></script>
+
document.body.style.backgroundColor = "red";
 
</syntaxhighlight>
 
</syntaxhighlight>
  
* '''Variables:'''
 
** JavaScript is case-sensitive username and userName are different.
 
** JavaScript is a dynamically typed language. You don't have to specify the datatype of a variable when you declare it.
 
** Data types are converted automatically as needed during script execution. So, for example, you could define a variable as follows:
 
:: '''var answer = 42;'''
 
:: And later, you could assign the same variable a string value, for example:
 
:: '''answer = "Thanks for all the fish...";'''
 
:* A variable declared using the var statement with no initial value specified has the value '''undefined'''.
 
:** An attempt to access an undeclared variable will result in a ReferenceError exception being thrown:
 
:*** You can use '''undefined''' to determine whether a variable has a value. In the following code, the variable input is not assigned a value, and the if statement evaluates to true:
 
  
<syntaxhighlight lang="php">
+
Another example:
var input;
+
<syntaxhighlight lang="javascript">
if(input === undefined){
+
window.alert(5 + 6);
    doThis();
+
alert(5 + 6);
}else{
 
    doThat();
 
}
 
 
</syntaxhighlight>
 
</syntaxhighlight>
  
* '''Type coercion:'''
+
 
** Depending on the type of operation javascript will attempt to coerce a variable into the correct type. For example, consider the following statements:
+
<br />
<syntaxhighlight lang="javaScript">
+
====Google Chrome Developer Tools====
x = "The answer is " + 42 // "The answer is 42"
+
* Google Chrome Customize Developer Tools: Dark Theme / Color Schema: https://stackoverflow.com/questions/20777454/google-chrome-customize-developer-tools-theme-color-schema
y = 42 + " is the answer" // "42 is the answer"
+
 
 +
 
 +
<br />
 +
 
 +
===JS code embedded in a HTML page===
 +
Try it at https://jsfiddle.net/
 +
<syntaxhighlight lang="html">
 +
<!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>
 
</syntaxhighlight>
 
</syntaxhighlight>
:* In statements involving other operators, JavaScript doesn't convert numeric values to strings. For example:
+
The method that is executed ''onclick'': '''''"document.getElementById('demo').innerHTML = Date()"''''' is a JS method that has been embedded into a HTML code.
<syntaxhighlight lang="javaScript">
+
 
"37" - 7 // 30
+
 
"37" + 7 // "377"
+
<br />
 +
====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: <nowiki> <script type="text/javascript"> </nowiki>. 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 <nowiki> <body> </nowiki>, or in the <nowiki> <head> </nowiki> section of an HTML page, or in both.
 +
 
 +
 
 +
Example 1 - In this example, a JavaScript function is placed in the <nowiki> <head> </nowiki> section of an HTML page. The function is invoked (called) when a button is clicked:
 +
 
 +
Try it at https://jsfiddle.net/
 +
<syntaxhighlight lang="html">
 +
<!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>
 
</syntaxhighlight>
 
</syntaxhighlight>
  
* '''Javascript Strings:'''
 
** The + operator can be used to concatenates strings:
 
** The following line will produce the string "concatenate":
 
<syntaxhighlight lang="javaScript">
 
"con"+"cat"+"e"+"nate"
 
</syntaxhighlight>
 
  
* To output debug statements (on the Terminal) the '''console.log()''' function is used, similar to '''echo''' in php:
+
Example 2 - In this example, a JavaScript function is placed in the <nowiki> <body> </nowiki> section of an HTML page. The function is invoked (called) when a button is clicked:
<syntaxhighlight lang="javaScript">
+
 
var = 10;
+
Try it at https://jsfiddle.net/
for (var i=0 ; i<10 ; i++){
+
<syntaxhighlight lang="html">
    console.log("Loop value: "+i);
+
<!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>
 
</syntaxhighlight>
 
</syntaxhighlight>
  
* '''Javascript Arrays:'''
 
** JavaScript provides a data type specifically for storing sequences of values. It is called an '''array'''. The
 
<syntaxhighlight lang="javaScript">
 
var myArray = [];  //empty array
 
  
var listOfNumbers = [2, 3, 5, 7, 11];
+
<br />
console.log(listOfNumbers[1]);
+
====Calling an external JS file from a HTML page====
console.log(listOfNumbers.length)
+
JavaScript files have the file extension .js
</syntaxhighlight>
+
 
 +
 
 +
*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 <nowiki> <script> </nowiki> tag is located.
 +
*External scripts cannot contain <nowiki> <script> </nowiki> 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
  
:* We can determine the length (or number of elements) of an array using the '''.length property'''
 
<syntaxhighlight lang="javaScript">
 
console.log(listOfNumbers.length)
 
</syntaxhighlight>
 
  
:* '''Array iteration:'''
+
myScript.js
<syntaxhighlight lang="javaScript">
+
<syntaxhighlight lang="javascript">
var myArray = ['none','two','three','four','five','six'];
+
function myFunction() {
for (var num in myArray){
+
document.getElementById("demo").innerHTML = "Paragraph changed.";
    console.log(myArray[num]);
 
 
}
 
}
 
</syntaxhighlight>
 
</syntaxhighlight>
  
:* '''indexOf'''
+
 
<syntaxhighlight lang="javaScript">
+
To use an external script, put the name of the script file in the src (source) attribute of a <nowiki> <script> </nowiki> tag:
var myArray = ['one','two','three','four','five','six'];
+
<syntaxhighlight lang="html">
myArray.indexOf('two');  // 1
+
<script src="myScript.js"></script>
 
</syntaxhighlight>
 
</syntaxhighlight>
  
* Functions in Javascript come in many forms. But predominantly we can have:
 
** named, or
 
** anonymous functions.
 
  
:* A named function looks something like this:
+
External scripts can be referenced with a full URL or with a path relative to the current web page:
<syntaxhighlight lang="javaScript">
+
 
// Define a function
+
 
function myFunction() {
+
Example 1 - This example uses a full URL to link to a script:
    console.log("function called");
+
 
    // do something interesting
+
Try it at https://jsfiddle.net/
}
+
<syntaxhighlight lang="html">
 +
<!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>
  
myFunction(); //execute the function
+
<script src="https://www.w3schools.com/js/myScript.js"></script>
 +
<!--  <p>(myFunction is stored in an external file called "myScript.js")</p>  -->
 +
</body>
 +
</html>
 
</syntaxhighlight>
 
</syntaxhighlight>
  
:* An anonymous function is a function without a name. It is generally assigned as a variable value:
 
<syntaxhighlight lang="javaScript">
 
var func = function(){
 
    console.log("Anonymous function executed...");
 
}
 
  
func(); //Execute the function
+
<br />
 +
===Using Nodejs from the linux terminal===
 +
See [[HTTP REST APIs with Node.js - Express.js|Nodejs]]
 +
 
 +
 
 +
 
 +
'''From the Nodejs console:'''
 +
 
 +
Go to a terminal and execute the command '''''«node»'''''. This will open the Nodejs Shell/Interpreter:
 +
node
 +
 
 +
Try some commands in the shell:
 +
<syntaxhighlight lang="javascript">
 +
console.log("Hello world!");
 
</syntaxhighlight>
 
</syntaxhighlight>
  
:* All functions can accept parameters and can use the '''return''' keyword:
+
<syntaxhighlight lang="javascript">
<syntaxhighlight lang="javaScript">
+
function myFunction() {
function myFunction(var1, var2, var3){
+
    console.log("Hello world!");
    newValue = var1 + var2;
 
    console.log(newValue + var3);
 
 
}
 
}
 +
</syntaxhighlight>
 +
 +
 +
 +
'''You can also create a JS script and run it using the '''''node''''' command:'''
  
var returnValue = myFunction(12, 13, 30);
+
javaScript.js
console.log(returnValue);
+
<syntaxhighlight lang="javascript">
 +
function add(){
 +
    var result = 5 + 10;
 +
    console.log(result);
 +
}
 +
add()
 
</syntaxhighlight>
 
</syntaxhighlight>
  
==JS and DOM==
+
node javaScript.js
'''Based on the [[Web Development#Document Object Model (DOM)|DOM]], JavaScript gets all the power it needs to create dynamic HTML:'''
+
 
* JavaScript can change all the HTML elements in the page
+
 
* JavaScript can change all the HTML attributes in the page
+
<br />
* JavaScript can change all the CSS styles in the page
+
===Using Nodejs from VS Code===
* JavaScript can remove existing HTML elements and attributes
+
 
* JavaScript can add new HTML elements and attributes
+
 
* JavaScript can react to all existing HTML events in the page
+
<br />
* JavaScript can create new HTML events in the page
+
 
 +
==The Syntax==
 +
https://www.w3schools.com/js/js_syntax.asp
 +
 
  
In javascript the root element is defined by the javascript object '''document'''
+
<br />
There are a number of functions we can use to 'traverse' or interrogate the document object i.e. elements of the DOM
+
===Variables===
  
'''docuemnt object:'''
+
*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:
In javascript the root element of the DOM is defined by the javascript object '''document'''.
 
  
 +
*JavaScript variables value can be changed anytime.
  
'''There are a number of functions''' we can use to 'traverse' or interrogate the document object i.e. elements of the DOM:
+
*JavaScript variables are loosely-typed which means it does not require a data type to be declared.
  
'''getElementById''' function allows to pick one element from the DOM tree and check to see what the values current are
+
<blockquote>
<syntaxhighlight lang="php">
+
<syntaxhighlight lang="javascript">
document.getElementById('id') // we pass the id of the element
+
var x, y;
 +
x = 5;
 +
y = 6;
 +
var total = x + y;
 +
var pi = 3.14;
 +
var person = "John Doe";
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
</blockquote>
  
'''document.getElementById(‘id’).value''' allows to extract the value of an element.
 
  
'''createTextNode''' is used to make a new node (to add new elements to the DOM tree):
+
*A variable declared without a value will have the value '''''undefined''''':
<syntaxhighlight lang="php">
+
<blockquote>
var txt = document.createTextNode(" This text was added to the DIV.");
+
<syntaxhighlight lang="javascript">
document.body.appendChild(txt);
+
var carName;  
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
</blockquote>
 +
 +
 +
<br />
 +
 +
===Comments===
 +
Code after double slashes // or between /* and */ is treated as a comment.
 +
  
 +
<br />
 +
===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:'''
  
'''Javascript Events:'''
+
:*The variables lastName and lastname, are two different variables.
 +
:*JavaScript does not interpret VAR or Var as the keyword var.
  
When we want a function to be called when something happens on a page, we use '''event handlers'''. These are just like the ActionListener and ActionPerformed in Java.
+
*Hyphens are not allowed. It is not allowed to name a variable as «first-name». Hyphens are reserved for subtractions.
  
When a button is pressed, for example, we can call a function:
+
 
When a button is pressed we can call a function:
+
<br />
<syntaxhighlight lang="php">
+
==Data types==
<button onclick=’callFunction()’>Submit</button>
+
https://codeburst.io/javascript-data-types-explained-347555cd2d4d
 +
 
 +
https://www.w3schools.com/js/js_datatypes.asp
 +
 
 +
 
 +
You can use the JavaScript <code>typeof</code> operator to find the type of a JavaScript variable.
 +
 
 +
The <code>typeof</code> operator returns the type of a variable or an expression:<syntaxhighlight lang="javascript">
 +
typeof ""            // Returns "string"
 +
typeof "John"        // Returns "string"
 +
typeof "John Doe"    // Returns "string"
 +
 
 +
typeof 0              // Returns "number"
 +
typeof 314            // Returns "number"
 +
typeof 3.14          // Returns "number"
 +
typeof (3)            // Returns "number"
 +
typeof (3 + 4)        // Returns "number"
 +
 
 +
typeof undefined      // undefined
 +
typeof null          // object - You can consider it a bug in JavaScript that typeof null is an object. It should be null.
 +
</syntaxhighlight><br />
 +
{| class="wikitable"
 +
!
 +
!'''Data Type'''
 +
!Description
 +
! colspan="2" |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).
 +
| colspan="2" |
 +
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).
 +
| colspan="2" |
 +
var str1 = 'hello, it is me';
 +
 
 +
var str2 = "hello, it's me";
 +
|-
 +
|'''Boolean'''
 +
|A boolean represents only one of two values: true, or false.
 +
| colspan="2" |
 +
var boo1 = true;
 +
 
 +
var boo2 = false;
 +
|-
 +
|'''Undefined'''
 +
|A variable that has no value is '''undefined'''.
 +
 
 +
 
 +
You can also empty an object by setting it to <code>undefined</code>
 +
|
 +
var testVar;
 +
 
 +
console.log(testVar); // undefined
 +
| rowspan="2" |'''Difference Between Undefined and Null''':
 +
undefined and null are equal in value but different in type:<syntaxhighlight lang="typescript">
 +
typeof undefined  // undefined
 +
typeof null        // object
 +
 
 +
null === undefined // false
 +
null == undefined  // true
 +
</syntaxhighlight><br />
 +
|-
 +
|'''Null'''
 +
|In JavaScript <code>null</code> is "nothing". It is supposed to be something that doesn't exist.
 +
Unfortunately, in JavaScript, the data type of <code>null</code> is an object.
 +
 
 +
You can consider it a bug in JavaScript that <code>typeof null</code> is an object. It should be <code>null</code>.
 +
 
 +
You can empty an object by setting it to <code>null</code>:
 +
<br />
 +
|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.
 +
| colspan="2" |const mySymbol = Symbol('mySymbol');
 +
|-
 +
| rowspan="3" |'''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.
 +
| colspan="2" |<syntaxhighlight lang="javascript">
 +
var obj = {
 +
  key1: 'value',
 +
  key2: 'value',
 +
  key3: true,
 +
  key4: 32,
 +
  key5: {}
 +
}
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
|-
 +
|'''Array'''
 +
|
 +
| colspan="2" |var cars = ["Saab", "Volvo", "BMW"];
 +
|-
 +
|'''RegExp'''
 +
|
 +
| colspan="2" |
 +
|}
 +
 +
 +
<br />
 +
==Operators==
 +
 +
{{#lst:Java|operators}}
 +
 +
 +
<br />
 +
 +
==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 <code>innerHTML</code>.
 +
*Writing into the HTML output using <code>document.write()</code>.
 +
*Writing into an alert box, using <code>window.alert()</code>.
 +
*Writing into the browser console, using <code>console.log()</code>.
  
===Example 1===
+
<br />
When we call the function '''document.getElementById''' it will return is a reference to the element in the DOM tree where that element is. Once we get this reference, we can then make changes to the element. The '''innerHTML''' function allows us to set the HTML of an element dynamically.
+
{| class="wikitable"
 +
!Different ways/Method
 +
!Example
 +
Try the codes at https://jsfiddle.net/
 +
|-
 +
|Writing into an HTML element using '''innerHTML'''
  
/var/www/html/webdevelopment/lecture10-JS/2DOM.html
+
|To access an HTML element, JavaScript can use the <code>document.getElementById(id)</code> method. The <code>id</code> attribute defines the HTML element.
<syntaxhighlight lang="php">
+
The <code>innerHTML</code>  property defines the HTML content.<syntaxhighlight lang="html">
 +
<!DOCTYPE html>
 
<html>
 
<html>
 +
<body>
 +
 +
<h1>My First Web Page</h1>
 +
<p>My First Paragraph</p>
 +
 +
<p id="demo"></p>
  
<head>
+
<script>
</head>
+
document.getElementById("demo").innerHTML = 5 + 6;
 +
</script>
  
 +
</body>
 +
</html>
 +
</syntaxhighlight>
 +
|-
 +
| rowspan="2" |Writing into the HTML output using '''document.write()'''
 +
*It is convenient and It should only be used for testing purposes.
 +
|<syntaxhighlight lang="html">
 +
<!DOCTYPE html>
 +
<html>
 
<body>
 
<body>
      <div id = 'demo'>
 
            <p>This is some content</p>
 
      </div>
 
</body>
 
  
<button onclick='updateDivAdelo()'>Submit</button>
+
<h1>My First Web Page</h1>
 +
<p>My First Paragraph</p>
 +
 
 +
<p id="demo"></p>
  
 
<script>
 
<script>
      function updateDivAdelo() {
+
document.getElementById("demo").innerHTML = 5 + 6;
            document.getElementById('demo').style.color='blue';
 
            document.getElementById('demo').innerHTML = '<p>This is some new content on blue</p>';
 
      }
 
 
</script>
 
</script>
 +
 +
</body>
 +
</html>
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
|-
 +
|Using document.write() after an HTML document is loaded, will '''delete all existing HTML''':<syntaxhighlight lang="html">
 +
<!DOCTYPE html>
 +
<html>
 +
<body>
 +
 +
<h1>My First Web Page</h1>
 +
<p>My first paragraph.</p>
  
===Javascript Validation===
+
<button type="button" onclick="document.write(5 + 6)">Try it</button>
  
  /var/www/html/webdevelopment/lecture10-JS/3CSValidationJS.php
+
</body>
<syntaxhighlight lang="php">
+
</html>
 +
</syntaxhighlight><br />
 +
|-
 +
|Writing into an alert box using '''window.alert()'''
 +
*You can use an alert box to display data.
 +
|<syntaxhighlight lang="html">
 +
<!DOCTYPE html>
 
<html>
 
<html>
 +
<body>
 +
 +
<h1>My First Web Page</h1>
 +
<p>My first paragraph.</p>
  
<head>
+
<script>
</head>
+
window.alert(5 + 6);
 +
</script>
  
 +
</body>
 +
</html>
 +
</syntaxhighlight>
 +
|-
 +
|Writing into the browser console using '''console.log()'''
 +
*For debugging purposes, you can use the <code>console.log()</code> method to display data.
 +
:* <span style="color:#FF0000">You'll need to go to the browser console to see the output.</span>
 +
|<syntaxhighlight lang="html">
 +
<!DOCTYPE html>
 +
<html>
 
<body>
 
<body>
      <form id='form' action='3CSValidationJS.php' method='post' onsubmit="return validate()">
 
            username: <input type='text' name='username' id='username'><br/>    <!-- name es usado por PHP, pero js se base en el id -->
 
            email:    <input type='text' name='email' id='email'><br/>
 
                      <input type='submit' value='Submit'>
 
      </form>
 
</body>
 
  
 
<script>
 
<script>
      function validate(){
+
console.log(5 + 6);
            var uname = document.getElementById('username').value;
 
            // if (uname == ''){
 
            if (uname.trim() == ''){ // con trim, los espacios no son considerados
 
                  alert("Username debe ser definido");
 
                  return false;
 
            }
 
            else if (uname.length <= 3){
 
                  alert("Username must be more than 3 chars!");
 
                  return false;
 
            }
 
            else{
 
                  return true;
 
            }
 
      }
 
 
</script>
 
</script>
  
 +
</body>
 
</html>
 
</html>
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
|}
 +
<br />
 +
 +
==Control flow statements==
 +
 +
 +
<br />
 +
===If statements===
  
==Javascript Debugging==
 
When using javascript in a browser it's vital that we are comfortable using the browser’s developer tools to debug javascript code.
 
  
The first port of call should be the '''console window''' in the developer tool. This will flag any errors when we refresh our web page. Hopefully there will be helpful messages to allow us to fix our code. Syntax errors etc should show up here.
+
<br />
 +
===For Loops===
 +
 
 +
 
 +
<br />
 +
===While Loops===
 +
 
 +
 
 +
<br />
 +
==Functions==
 +
https://www.w3schools.com/js/js_functions.asp
 +
 
 +
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.
 +
 
 +
 
 +
<br />
 +
===Callback Functions===
 +
https://codeburst.io/javascript-what-the-heck-is-a-callback-aba4da2deced
 +
 
 +
https://www.dashingd3js.com/lessons/javascript-callback-functions
 +
 
 +
 
 +
Simply put: A callback is a function that is to be executed after another function has finished executing — hence the name ‘call back’.
 +
 
 +
More complexly put: In JavaScript, functions are objects. Because of this, functions can take functions as arguments, and can be returned by other functions. Functions that do this are called higher-order functions. Any function that is passed as an argument is called a callback function.
 +
 
 +
<syntaxhighlight lang="javascript">
 +
function functionOne(x){
 +
    return x;
 +
};
 +
 
 +
 
 +
function functionTwo(var1){
 +
    // some code
 +
}
 +
 
 +
functionTwo(functionOne);
 +
</syntaxhighlight>
 +
 
 +
 
 +
<br />
 +
 
 +
==Methods==
 +
 
 +
 
 +
<br />
 +
===Some of the most important methods===
 +
https://www.w3schools.com/js/js_intro.asp
 +
 
 +
 
 +
<br />
 +
====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":
 +
<syntaxhighlight lang="javascript">
 +
document.getElementById("demo").innerHTML = "Hello JavaScript";
 +
</syntaxhighlight>
 +
 
 +
 
 +
<br />
 +
 
 +
====Change HTML Attribute Values====
 +
In this example JavaScript changes the value of the src (source) attribute of an <img> tag:
 +
 
 +
<syntaxhighlight lang="javascript">
 +
<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>
 +
</syntaxhighlight>
 +
 
 +
 
 +
<br />
 +
====Change HTML Styles - CSS====
 +
Changing the style of an HTML element, is a variant of changing an HTML attribute:
 +
<syntaxhighlight lang="javascript">
 +
document.getElementById("demo").style.fontSize = "35px";
 +
</syntaxhighlight>
 +
 
 +
 
 +
<br />
 +
====Hide HTML Elements====
 +
Hiding HTML elements can be done by changing the display style:
 +
<syntaxhighlight lang="javascript">
 +
document.getElementById("demo").style.display = "none";
 +
</syntaxhighlight>
 +
 
 +
 
 +
<br />
 +
====Show HTML Elements====
 +
Showing hidden HTML elements can also be done by changing the display style:
 +
<syntaxhighlight lang="javascript">
 +
document.getElementById("demo").style.display = "block";
 +
</syntaxhighlight>
 +
 
 +
 
 +
<br />
 +
==Reading JSON from URL in JavaScript==
 +
http://zetcode.com/articles/javascriptjsonurl/
 +
 
 +
 
 +
<br />
 +
 
 +
==Hoisting in JavaScript==
 +
https://scotch.io/tutorials/understanding-hoisting-in-javascript
 +
 
 +
 
 +
<br />

Latest revision as of 19:18, 21 June 2020


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 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. Open the Web Browser console («Ctrl + Shit + i» and go to the console tab). This console is a JavaScript shell. You can so execute JavaScript commands.


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";


Another example:

window.alert(5 + 6);
alert(5 + 6);



Google Chrome Developer Tools



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>



Using Nodejs from the linux terminal

See Nodejs


From the Nodejs console:

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



Using Nodejs from VS Code


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.



Data types

https://codeburst.io/javascript-data-types-explained-347555cd2d4d

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


You can use the JavaScript typeof operator to find the type of a JavaScript variable.

The typeof operator returns the type of a variable or an expression:

typeof ""             // Returns "string"
typeof "John"         // Returns "string"
typeof "John Doe"     // Returns "string"

typeof 0              // Returns "number"
typeof 314            // Returns "number"
typeof 3.14           // Returns "number"
typeof (3)            // Returns "number"
typeof (3 + 4)        // Returns "number"

typeof undefined      // undefined
typeof null           // object - You can consider it a bug in JavaScript that typeof null is an object. It should be null.


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.


You can also empty an object by setting it to undefined

var testVar;
console.log(testVar); // undefined
Difference Between Undefined and Null: undefined and null are equal in value but different in type:
typeof undefined   // undefined
typeof null        // object

null === undefined // false
null == undefined  // true

Null In JavaScript null is "nothing". It is supposed to be something that doesn't exist.

Unfortunately, in JavaScript, the data type of null is an object.

You can consider it a bug in JavaScript that typeof null is an object. It should be null.

You can empty an object by setting it to null:

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 var cars = ["Saab", "Volvo", "BMW"];
RegExp



Operators

Operator Name/Description Example Same as
Python

s2

Java JS R Python Java F R
Arithmetic Operators + + Addition x + y
- - Subtraction x - y
* * Multiplication x * y
/ / Division x / y
% % Modulus x % y
** java.util.Math Exponentiation x ** y import java.util.Math

Double result = Math.pow(number, exponent);

// Floor division x // y
++ Increment: Increases the value of a variable by 1 ++x
-- Decrement: Decreases the value of a variable by 1 --x
Assignment Operators = = x = 5
+= += x+= 3 x = x + 3
-= -= x -= 3 x = x - 3
*= *= x *= 3 x = x * 3
/= /= x /= 3 x = x / 3
%= %= x %= 3 x = x % 3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= &= x &= 3 x = x & 3
|= |= x |= 3 x = x | 3
^= ^= x ^= 3 x = x ^ 3
>>= >>= x >>= 3 x = x >> 3
<<= <<= x <<= 3 x = x << 3
Comparison Operators == == Equal x == y
!= != Not equal x != y
> > Greater than x > y
< < Less than x < y
>= >= Greater than or equal to x >= y
<= <= Less than or equal to x <= y
Logical Operators and && Logical and: Returns True if both statements are true x < 5 and x < 10 x < 5 && x < 10
or || Logical or: Returns True if one of the statements is true x < 5 or x < 4 x < 5 || x < 4
not ! Logical not: Reverse the result, returns False if the result is true not(x < 5 and x < 10) !(x < 5 && x < 10)
Identity Operators is Returns true if both variables are the same object x is y
is not Returns true if both variables are not the same object x is not y
Membership Operators in Returns True if a sequence with the specified value is present in the object x in y
not in Returns True if a sequence with the specified value is not present in the object x not in y
Bitwise Operators &
AND

Sets each bit to 1 if both bits are 1

| OR

Sets each bit to 1 if one of two bits is 1

^ XOR

Sets each bit to 1 if only one of two bits is 1

~ NOT

Inverts all the bits

<< Zero fill left shift

Shift left by pushing zeros in from the right and let the leftmost bits fall off

>> Signed right shift

Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off

Added by myself
String concatenation +
"Coucou ' + 'c\'est ' + 'nous !";
conca()
'Coucou '.concat('c\'est ', 'nous !');
join()
['Coucou ', 'c\'est ', 'nous !'].join();



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.
  • You'll need to go to the browser console to see the output.
<!DOCTYPE html>
<html>
<body>

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

</body>
</html>


Control flow statements


If statements


For Loops


While Loops


Functions

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

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.



Callback Functions

https://codeburst.io/javascript-what-the-heck-is-a-callback-aba4da2deced

https://www.dashingd3js.com/lessons/javascript-callback-functions


Simply put: A callback is a function that is to be executed after another function has finished executing — hence the name ‘call back’.

More complexly put: In JavaScript, functions are objects. Because of this, functions can take functions as arguments, and can be returned by other functions. Functions that do this are called higher-order functions. Any function that is passed as an argument is called a callback function.

function functionOne(x){
    return x;
};


function functionTwo(var1){
    // some code
}

functionTwo(functionOne);



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";



Reading JSON from URL in JavaScript

http://zetcode.com/articles/javascriptjsonurl/



Hoisting in JavaScript

https://scotch.io/tutorials/understanding-hoisting-in-javascript