Javascript: Difference between revisions
(20 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
== Reference == |
== Reference == |
||
;On this wiki |
|||
* [[Node.js]] |
|||
* [[Npm]] |
|||
* [[Typescript]] |
|||
;Language |
|||
* [https://www.w3schools.com/jsref/ JavaScript and HTML DOM reference on w3schools.com] |
* [https://www.w3schools.com/jsref/ JavaScript and HTML DOM reference on w3schools.com] |
||
* [https://developer.mozilla.org/en-US/docs/Web/API Web API on mozilla.org] |
|||
* [https://developer.mozilla.org/en-US/docs/Web/Tutorials Mozilla tutorials] |
|||
* [https://medium.freecodecamp.org/here-are-examples-of-everything-new-in-ecmascript-2016-2017-and-2018-d52fa3b5a70e Here are examples of everything new in ECMAScript 2016, 2017, and 2018] |
|||
* [https://dmitripavlutin.com/javascript-sparse-dense-arrays/ Sparse and Dense arrays] |
|||
;Test |
|||
* [https://github.com/facebook/jest Jest] — Delightful JavaScript Testing |
|||
;Typescript |
|||
* '''[[Typescript]]''' is a typed-superset of Javascript. |
|||
;Tools, libraries |
|||
* [https://github.com/formkit/auto-animate AutoAnimate] |
|||
* [https://eruda.liriliri.io/ Eruda] — A javascript console for mobile |
|||
== Syntax == |
== Syntax == |
||
Line 108: | Line 128: | ||
</source> |
</source> |
||
== |
== jQuery == |
||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
In Javascript, jQuery library is often exported as the '''dollar''' symbol, <code>$</code>! |
In Javascript, jQuery library is often exported as the '''dollar''' symbol, <code>$</code>! |
||
=== Document ready === |
|||
A page can't be manipulated safely until the document is "ready." [https://learn.jquery.com/using-jquery-core/document-ready/] jQuery detects this state of readiness for you. Code included inside <code>$( document ).ready()</code> will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. |
|||
<source lang=javascript> |
|||
// A $( document ).ready() block. |
|||
$( document ).ready(function() { |
|||
console.log( "ready!" ); |
|||
}); |
|||
</source> |
|||
Developer frequently use the shorthand version <code>$( ... )</code>, although it is more confusing: [https://learn.jquery.com/using-jquery-core/document-ready/] |
|||
<source lang=javascript> |
|||
// Shorthand for $( document ).ready() |
|||
$(function() { |
|||
console.log( "ready!" ); |
|||
}); |
|||
</source> |
|||
== How-to == |
== How-to == |
||
Line 125: | Line 163: | ||
function WaitForFunction() |
function WaitForFunction() |
||
{ |
{ |
||
// Here we should use (typeof FUNCTION_TO_WAIT_ON_HERE === "function") |
|||
// See https://stackoverflow.com/questions/12206083/whats-the-difference-between-typeof-variable-function-and-jquery-isfunc |
|||
if (!$.isFunction(FUNCTION_TO_WAIT_ON_HERE)) { |
if (!$.isFunction(FUNCTION_TO_WAIT_ON_HERE)) { |
||
setTimeout( WaitForFunction, 100); |
setTimeout( WaitForFunction, 100); |
||
Line 148: | Line 188: | ||
<source lang=javascript> |
<source lang=javascript> |
||
for (var attr in obj) { console.log ("Attribute " + attr + " is: " + obj[attr]); } |
for (var attr in obj) { console.log ("Attribute " + attr + " is: " + obj[attr]); } |
||
</source> |
|||
=== Add property to an undefined object === |
|||
If we want to add a property to an object that is not yet defined, just assign the value <code>{}</code> to it. |
|||
<source lang=javascript> |
|||
var myobj = {}; |
|||
myobj.someProperty = "value"; |
|||
// or... |
|||
window.myobj = {}; |
|||
window.myobj.someProperty = "value"; |
|||
</source> |
|||
=== How to sleep / wait for a delay === |
|||
Just don't, because it would block the execution thread. Instead, fire a time event with <code>setTimeout</code> [https://stackoverflow.com/questions/7854820/is-there-a-sleep-pause-wait-function-in-javascript]: |
|||
<source lang=javascript> |
|||
setTimeout(function(){alert("hi")}, 1000); |
|||
</source> |
|||
=== Format javascript file === |
|||
Using {{deb|clang-format}}: |
|||
<source lang="bash"> |
|||
# Using Google style, inplace |
|||
clang-format -i -style=Google foo.js bar.js |
|||
</source> |
|||
== Build == |
|||
=== Grunt: the Javascript Task Runner === |
|||
* https://gruntjs.com/getting-started |
|||
<source lang=bash> |
|||
grunt // Run default task (usually build), equiv. to "make" |
|||
</source> |
</source> |
||
== Debug == |
== Debug == |
||
=== Print message to console === |
|||
Use <code>console</code> |
|||
<source lang=javascript>console.error(message); //gives you the red errormessage |
|||
console.log(message); //gives the default message |
|||
console.warn(message); //gives the warn message with the exclamation mark in front of it |
|||
console.info(message); //gives an info message with an 'i' in front of the message |
|||
</source> |
|||
=== Firefox === |
=== Firefox === |
||
* In Firefox, {{kb|Ctrl-Shift-C}} to open up the console and debugger tools.\ |
* In Firefox, {{kb|Ctrl-Shift-C}} to open up the console and debugger tools.\ |
||
Line 157: | Line 239: | ||
>> windows |
>> windows |
||
</pre> |
</pre> |
||
=== Chrome === |
|||
* {{kb|F12}} to open up Developers tools ({{kb|Ctrl-Shift-C}} also works but show another tab?). |
|||
* Keyboard: while in developer tools, {{kb|Ctrl-P}} then <code>></code> to have a drop down list and fuzzy search (eg. <code>des</code> to select <code>Show Overrides</code>). |
|||
== Tips == |
|||
=== To grok a mockingbird === |
|||
Or how to make a function recursive, but keep functional composition [http://raganwald.com/2018/08/30/to-grok-a-mockingbird.html] (also about memoization). |
Latest revision as of 10:38, 27 June 2023
Reference
- On this wiki
- Language
- JavaScript and HTML DOM reference on w3schools.com
- Web API on mozilla.org
- Mozilla tutorials
- Here are examples of everything new in ECMAScript 2016, 2017, and 2018
- Sparse and Dense arrays
- Test
- Jest — Delightful JavaScript Testing
- Typescript
- Typescript is a typed-superset of Javascript.
- Tools, libraries
- AutoAnimate
- Eruda — A javascript console for mobile
Syntax
JS type
// Strings
var carname = "Volvo XC60";
// Numbers
var x = 3.14;
var y = 34;
JS operators
// Arithmetic operators
x = y + 2;
x = y - 2;
x = y * 2;
x = y / 2;
x = y % 2; // Modulus (division remainder)
x = ++y; // Pre-increment
x = y++; // Post-increment
x = --y; // Pre-decrement
x = y--; // Post-decrement
// Assignment operators
x = y;
x += y;
x -= y;
x *= y;
x /= y;
x %= y;
// String operators
text3 = text1 + text2; // Concatenation
text1 += text2;
// Comparison operators
x == 8; // equal to
x === 5; // equal value and equal type
x != 8 // not equal
x !== 5 // not equal value or not equal type
x > 5;
x < 5;
x >= 5;
x <= 5;
// Ternary operator
voteable = (age < 18) ? "Too young" : "Old enough";
// Logical operators
x && y; // logical and
x || y; // logical or
!x; // not
// Bitwise operators
x = 5 & 1; // bitwise and
x = 5 | 1; // bitwise or
x = ~5; // bitwise not
x = 5 ^ 1; // bitwise xor
x = 5 << 1; // bitwise left shift
x = 5 >> 1; // bitwise right shift
// typeof
typeof "John"; // returns string
// delete
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
delete person.age; // or delete person["age"] -- delete property from an object
// in
var cars = ["Saab", "Volvo", "BMW"];
"length" in cars // true if property is in the specified object
"firstname" in person
// instanceof
cars instanceof Array; // true if object is instance of specified class
// void
void(0); // evaluate expressions and returns undefined
JS statements
// switch
switch(fruits) {
case "Banana":
text = "Banana is good!";
break;
default:
text = "I have never heard of that fruit...";
}
// while
while (i < 5) {
// ...
}
JS functions
var myfct = function(arg1, arg2) {
return arg1 + ", " + arg2;
}
myfct("Hello", "World");
jQuery
jQuery is a fast, small, and feature-rich JavaScript library for HTML manipulation...
Dollar $
symbol
In Javascript, jQuery library is often exported as the dollar symbol, $
!
Document ready
A page can't be manipulated safely until the document is "ready." [1] jQuery detects this state of readiness for you. Code included inside $( document ).ready()
will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.
// A $( document ).ready() block.
$( document ).ready(function() {
console.log( "ready!" );
});
Developer frequently use the shorthand version $( ... )
, although it is more confusing: [2]
// Shorthand for $( document ).ready()
$(function() {
console.log( "ready!" );
});
How-to
Wait until a function is loaded
We fire a setTimeout
event until the function is available [3]:
$(function(){
$("#loadingGIF").show();
WaitForFunction();
});
function WaitForFunction()
{
// Here we should use (typeof FUNCTION_TO_WAIT_ON_HERE === "function")
// See https://stackoverflow.com/questions/12206083/whats-the-difference-between-typeof-variable-function-and-jquery-isfunc
if (!$.isFunction(FUNCTION_TO_WAIT_ON_HERE)) {
setTimeout( WaitForFunction, 100);
return;
}
Function_Loaded();
}
function Function_Loaded(){
$("#loadingGIF").hide();
}
Note that the code is not recursive because setTimeout
does not call the given function but add it to a timer event queue.
Simulate click on a button
Use jQuery [4]:
$('#mybutton').trigger('click');
$('#mybutton').click(); // Simpler
View object attributes
for (var attr in obj) { console.log ("Attribute " + attr + " is: " + obj[attr]); }
Add property to an undefined object
If we want to add a property to an object that is not yet defined, just assign the value {}
to it.
var myobj = {};
myobj.someProperty = "value";
// or...
window.myobj = {};
window.myobj.someProperty = "value";
How to sleep / wait for a delay
Just don't, because it would block the execution thread. Instead, fire a time event with setTimeout
[5]:
setTimeout(function(){alert("hi")}, 1000);
Format javascript file
Using clang-format:
# Using Google style, inplace
clang-format -i -style=Google foo.js bar.js
Build
Grunt: the Javascript Task Runner
grunt // Run default task (usually build), equiv. to "make"
Debug
Print message to console
Use console
console.error(message); //gives you the red errormessage
console.log(message); //gives the default message
console.warn(message); //gives the warn message with the exclamation mark in front of it
console.info(message); //gives an info message with an 'i' in front of the message
Firefox
- In Firefox, Ctrl-Shift-C to open up the console and debugger tools.\
- To browse an object, go to the console, and type the name of an object to open it up in the object explorer. For instance, to browse from the global context
window
:
>> windows
Chrome
- F12 to open up Developers tools (Ctrl-Shift-C also works but show another tab?).
- Keyboard: while in developer tools, Ctrl-P then
>
to have a drop down list and fuzzy search (eg.des
to selectShow Overrides
).
Tips
To grok a mockingbird
Or how to make a function recursive, but keep functional composition [6] (also about memoization).