Difference between revisions of "JavaScript"
Adelo Vieira (talk | contribs) (→Methods) |
Adelo Vieira (talk | contribs) (→Methods) |
||
Line 628: | Line 628: | ||
<br /> | <br /> | ||
+ | ==Reading JSON from URL in JavaScript== | ||
+ | http://zetcode.com/articles/javascriptjsonurl/ | ||
+ | |||
+ | |||
+ | <br /> | ||
+ | |||
==Hoisting in JavaScript== | ==Hoisting in JavaScript== | ||
https://scotch.io/tutorials/understanding-hoisting-in-javascript | https://scotch.io/tutorials/understanding-hoisting-in-javascript |
Revision as of 20:20, 30 October 2019
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:
- 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
Contents
JSFiddle
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 + 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);
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
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.
|
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 You can consider it a bug in JavaScript that You can empty an object by setting it to |
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 | 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
|
||||||
// | 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()
|
<!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()
|
<!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()
|
<!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