JavaScript: Difference between revisions

From XPUB & Lens-Based wiki
 
(21 intermediate revisions by 2 users not shown)
Line 40: Line 40:
</source>
</source>


A newer compact "splat" notation using the symbols "=>" is increasingly popular.
A newer compact "arrow" notation using the symbols "=>" is increasingly popular. (If you are doing things with classes, there's a subtle but important difference: An arrow function does ''not'' redefine the special symbol ''this'' -- which makes arrow functions convenient when writing callbacks in an object method (no more ''that'' variables needed).)


<source lang="javascript">
<source lang="javascript">
Line 88: Line 88:
== Fetch API & making HTTP requests ==
== Fetch API & making HTTP requests ==


Loading external data was added to javascript via the XMLHTTPRequest object, spawning a set of practices called "AJAX". Modern browsers now support the so-called "Fetch API" that makes loading files relatively straightforward. As fetching is essentially asynchronous (it takes time, your code continues at some point in the future when it's done rather than directly), the API uses Promises. Note that there are two stages to a fetch: (1) The request itself, and (2) retrieving the "body" of the results as typically either json or text.
Loading external data was added to javascript via the XMLHTTPRequest object, spawning a set of practices called "AJAX". Modern browsers now support the so-called "Fetch API" that makes loading files relatively straightforward (and finally remove the need for libraries like jquery). As fetching is essentially asynchronous (it takes time, your code continues at some point in the future when it's done rather than directly), the API uses Promises. Note that there are two stages to a fetch: (1) The request itself, and (2) retrieving the "body" of the results as typically either JSON (the popular alternative of XML) or text.


https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
Line 97: Line 97:
   .then(data => console.log(data));
   .then(data => console.log(data));
</source>
</source>
Or avoiding callbacks with await...
<source lang="javascript">
async function getdata () {
  let resp = await fetch('http://example.com/movies.json');
  let data = await resp.json();
  console.log("we got data", data);
}
</source>
== Read/write data to/from the server with PHP and fetch()==
In this example '''data''' is a '''string''' saved into a .txt file: <code>data.txt</code>.
You can also work with '''json''' and save your '''data''' into a .json file: <code>data.json</code>.
* PHP - for an intro to PHP, you can have a look here: https://www.w3schools.com/php/php_intro.asp
* JS - we will use fetch(), see above and also here: https://developer.mozilla.org/en-US/docs/Web/API/fetch
===read===
PHP: read.php
* Open a file in PHP: https://www.w3schools.com/php/php_file_open.asp
<syntaxhighlight lang="php">
<?php
# echo is what is print() in Python
echo "hello";
$filename = "data.txt";
$myfile = fopen($filename, "r") or die("Unable to open file!");
$data =  fread($myfile, filesize($filename));
# this will be taken as the response data in js
echo $data;
fclose($myfile);
?>
</syntaxhighlight>
JS
<syntaxhighlight lang="javascript">
<script>
async function getdata(){
  let response = await fetch('read.php');
  console.log(response);
  let data = await response.text();
  console.log("data:", data);
}
getdata()
</script>
</syntaxhighlight>
===write===
PHP: write.php
* write to a file in PHP: https://www.w3schools.com/php/php_file_create.asp
* debug: http://localhost:2000/write.php?post=post1
<syntaxhighlight lang="php">
<?php
echo $_GET["post"];
echo "<br>";
$filename = "data.json";
# read json data from data.json
$myfile = fopen($filename, "r") or die("Unable to open file!");
$data =  fread($myfile, filesize($filename));
$data_json = json_decode($data, true);
fclose($myfile);
echo $data;
echo "<br>";
var_dump($data_json);
echo "<br>";
$currentcount = $data_json["a"];
var_dump($currentcount);
echo "<br>";
$data_json["a"] = $currentcount + 1;
var_dump($data_json);
echo "<br>";
# write json data back to data.json
$myfile = fopen($filename, "w") or die("Unable to open file!");
fwrite($myfile, json_encode($data_json));
fclose($myfile);
?>
</syntaxhighlight>
JS
<syntaxhighlight lang="javascript">
<script>
async function writedata(){
  let response = await fetch('write.php');
}
writedata()
</script>
</syntaxhighlight>
===submit form data===
See this page for good examples: https://gist.github.com/jesperorb/a6c12f7d4418a167ea4b3454d4f8fb61


== From Python ==
== From Python ==
Line 119: Line 234:
* http://www.webteacher.com/javascript/
* http://www.webteacher.com/javascript/
* http://www.cs.brown.edu/courses/bridge/1998/res/javascript/javascript-tutorial.html
* http://www.cs.brown.edu/courses/bridge/1998/res/javascript/javascript-tutorial.html
==FAQ==
JS not-so-frequently asked Questions
'''What is the difference between "let" and "var"?'''
1) the initialization
var is initialize before it was defined. what means that?
<pre>
<script>
console.log(something); //console returns a undefined
var something = "whatever";
console.log(something); // returns "whatever"
</script>
</pre>
let is not initalized until its defined
<pre>
<script>
console.log(something); //console returns ERROR
let something = "whatever";
console.log(something); // returns "whatever"
</script>
</pre>
2) scoping
var belongs to the function body. what means var exists in the whole function!
let belongs only inside the {}. what means it can for example only exist in a if statement
Clear! Thanks
'''Oh one more question: can you also define a variable without using "var" or "let"?'''
there is const //cant be changed
var, let and const I think are all! Nice oke!
If you work with an external JS file, what is good practice of placing it in a page? In the header? At the bottom of the body? Outside the body but inside the html element?
in the header I would do it but not sure. mhm.
the only really important thing is that the library is first and then the code that uses the library.
Does this mean that the page loads first (all the elements, including the media files, and the CSS), before the javascript is executed?
good question, let me look that up!
<blockquote>
"While the CSS is being parsed and the CSSOM created, other assets, including JavaScript files, are downloading (thanks to the preload scanner). JavaScript is interpreted, compiled, parsed and executed. The scripts are parsed into abstract syntax trees. Some browser engines take the Abstract Syntax Tree and pass it into an interpreter, outputting bytecode which is executed on the main thread. This is known as JavaScript compilation."
</blockquote>
https://developer.mozilla.org/en-US/docs/Web/Performance/How_browsers_work
while css is parsed it downloads javascript.
'''When is JS making a page too heavy?'''
1) if it executes a lot of tasks in the background that are not necessary! javascript can be very heavy in performance and the cpu goes up. keep in mind javascript is totally necessary for almost everything that is used nowadays in the web. there would be no etherpad without js
2) js can make the traffic a little bit "bloated", the alternative would be vanilla js (only js without libraries)
http://vanilla-js.com/ for example this website makes jokes about donwloading the library that is actually 0 bytes because vanilla js is just js and can be found in every browser!  on the bottom of the website are some speed comparsions
'''How can we introduce the anti-JS religion? ;) And also critique it again'''
maybe this can be found in one of the principles of the permacomputing religion ah permacomputing, yes!
http://permacomputing.net/

Latest revision as of 10:50, 19 November 2024

Scripting language built into web browsers.

History

Originally designed for the Netscape browser, the name "JavaScript" was chosen to associate with the "Java" programming language developed by Sun which, in 1995, was the first real option for making "live" code run over the web. Other than the name, there is no relation between JavaScript and Java. The formal name for JavaScript now is ECMAScript, but as this sounds more like a skin condition than a programming language, the name JavaScript has persisted.

The introduction of highly interactive "web apps" like Google Maps has helped to reduce some of the differences between browsers in their implementation of JavaScript (which made early JavaScript development quite a nightmare). Traditionally popular JavaScript frameworks like prototype and JQuery have helped to smooth over differences between browsers and led to many techniques (such as using CSS selectors in Javascript code, and "functional" style programming) more popular and better incoporated into "vanilla" javascript.

Node (2009) is an implementation of javascript designed to run outside of the browser aka server-side. Together with its related package manager npm, Node has made a huge impact on the ecosystem of javascript development and npm serves as a foundation for all kinds of javascript development workflows (whether or not the final "target" of a project is a (node) server and/or in the browser).

In 2021, javascript is a vibrant but complex development ecosystem. Important related projects & development communities are webpack and typescript, and frameworks like angular and react.

Data types

Variables

Functions

function hello (x) {
  console.log("Hello", x);
}
hello("Bob");

In practice, javascript functions are often defined "anonymously", as "callbacks" to events like mouse clicks.

let div = document.getElementById("button");

div.addEventListener("click", function (event) {
  console.log("HEY somebody clicked", event);
});

A newer compact "arrow" notation using the symbols "=>" is increasingly popular. (If you are doing things with classes, there's a subtle but important difference: An arrow function does not redefine the special symbol this -- which makes arrow functions convenient when writing callbacks in an object method (no more that variables needed).)

div.addEventListener("click", (event) => {
  console.log("HEY somebody clicked", event);
});

Loops

words = "Once upon a time, in a galaxy far far away".split()

for w in words:
    print w
var words = "Once upon a time, in a galaxy far far away".split(" ")

for (var i=0; i<words.length; i++) {
    console.log(words[i]);
}

Promises & Asynchronous programming

Promises and new structures like async + await offer an alternative to working with callbacks.

Array methods: forEach() & map()

const array1 = ['a', 'b', 'c'];

array1.forEach(element => console.log(element));

// expected output: "a"
// expected output: "b"
// expected output: "c"

See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

Fetch API & making HTTP requests

Loading external data was added to javascript via the XMLHTTPRequest object, spawning a set of practices called "AJAX". Modern browsers now support the so-called "Fetch API" that makes loading files relatively straightforward (and finally remove the need for libraries like jquery). As fetching is essentially asynchronous (it takes time, your code continues at some point in the future when it's done rather than directly), the API uses Promises. Note that there are two stages to a fetch: (1) The request itself, and (2) retrieving the "body" of the results as typically either JSON (the popular alternative of XML) or text.

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

fetch('http://example.com/movies.json')
  .then(response => response.json())
  .then(data => console.log(data));

Or avoiding callbacks with await...

async function getdata () {
  let resp = await fetch('http://example.com/movies.json');
  let data = await resp.json();
  console.log("we got data", data);
}

Read/write data to/from the server with PHP and fetch()

In this example data is a string saved into a .txt file: data.txt.

You can also work with json and save your data into a .json file: data.json.

read

PHP: read.php

<?php

# echo is what is print() in Python
echo "hello";

$filename = "data.txt";

$myfile = fopen($filename, "r") or die("Unable to open file!");
$data =  fread($myfile, filesize($filename));

# this will be taken as the response data in js
echo $data;

fclose($myfile);

?>

JS

<script>
async function getdata(){
  let response = await fetch('read.php');
  console.log(response);
  let data = await response.text();
  console.log("data:", data);
}
getdata()
</script>

write

PHP: write.php

<?php

echo $_GET["post"];
echo "<br>";

$filename = "data.json";

# read json data from data.json
$myfile = fopen($filename, "r") or die("Unable to open file!");
$data =  fread($myfile, filesize($filename));
$data_json = json_decode($data, true);
fclose($myfile);

echo $data;
echo "<br>";

var_dump($data_json);
echo "<br>";

$currentcount = $data_json["a"];
var_dump($currentcount);
echo "<br>";

$data_json["a"] = $currentcount + 1;
var_dump($data_json);
echo "<br>";

# write json data back to data.json
$myfile = fopen($filename, "w") or die("Unable to open file!");
fwrite($myfile, json_encode($data_json));
fclose($myfile);

?>

JS

<script>
async function writedata(){
  let response = await fetch('write.php');
}
writedata()
</script>

submit form data

See this page for good examples: https://gist.github.com/jesperorb/a6c12f7d4418a167ea4b3454d4f8fb61

From Python

  • Curly braces ({}) instead of colons and indentation (:)
  • Indentation: still important for readability!
  • Semi-colons at ends of lines (though optional, good to get into the practice of using)
  • "var", "let" and "const" to announce a variable (technically optional but important to be explicit about scope)
  • "function" defines functions, also the new "splat" style ( => )
  • Implicit type conversion ("hello" + 7 = "hello7")

Resources

"Core" Documentation from mozilla.org

Online Tutorials

FAQ

JS not-so-frequently asked Questions

What is the difference between "let" and "var"?

1) the initialization

var is initialize before it was defined. what means that?

<script>
console.log(something); //console returns a undefined
var something = "whatever";
console.log(something); // returns "whatever"
</script> 

let is not initalized until its defined

<script>
console.log(something); //console returns ERROR
let something = "whatever";
console.log(something); // returns "whatever"
</script>

2) scoping

var belongs to the function body. what means var exists in the whole function! let belongs only inside the {}. what means it can for example only exist in a if statement Clear! Thanks

Oh one more question: can you also define a variable without using "var" or "let"?

there is const //cant be changed var, let and const I think are all! Nice oke!

If you work with an external JS file, what is good practice of placing it in a page? In the header? At the bottom of the body? Outside the body but inside the html element?

in the header I would do it but not sure. mhm. the only really important thing is that the library is first and then the code that uses the library. Does this mean that the page loads first (all the elements, including the media files, and the CSS), before the javascript is executed? good question, let me look that up!

"While the CSS is being parsed and the CSSOM created, other assets, including JavaScript files, are downloading (thanks to the preload scanner). JavaScript is interpreted, compiled, parsed and executed. The scripts are parsed into abstract syntax trees. Some browser engines take the Abstract Syntax Tree and pass it into an interpreter, outputting bytecode which is executed on the main thread. This is known as JavaScript compilation."

https://developer.mozilla.org/en-US/docs/Web/Performance/How_browsers_work

while css is parsed it downloads javascript.

When is JS making a page too heavy?

1) if it executes a lot of tasks in the background that are not necessary! javascript can be very heavy in performance and the cpu goes up. keep in mind javascript is totally necessary for almost everything that is used nowadays in the web. there would be no etherpad without js

2) js can make the traffic a little bit "bloated", the alternative would be vanilla js (only js without libraries) http://vanilla-js.com/ for example this website makes jokes about donwloading the library that is actually 0 bytes because vanilla js is just js and can be found in every browser! on the bottom of the website are some speed comparsions

How can we introduce the anti-JS religion? ;) And also critique it again

maybe this can be found in one of the principles of the permacomputing religion ah permacomputing, yes!

http://permacomputing.net/