Various Tips
alert, confirm en prompt
Using alert allows us to present text or data in a pop-up window. This is ofte used in this book like this:
alert("this is an alarm")
There is also a less known option to get a confirmation from a user. It works like this:
if (confirm("Are you sure"))
{
alert( "Ok you are certain");
}
else
{
alert( "You are still in doubt");
}
And even less widely known is that we can ask the user for information in a pop-up window like this:
var answer = (prompt('please enter a number'))
alert(answer)
Please be aware that the answer is always a string even if you entered a number.
And can give weird results
The AND function is used to test conditions and gives a boolean value as outcome:
var first = 3;
var second = 6;
alert(first < 4 && second > 4);
The alert will show "true" as both comparisons are true.
However using the AND function when the comparisons do not give a boolean value will show the last value:
alert(first < 4 && second > 4 && 6 && 90);
The alert will now show 90.
alert("today" && "tomorrow");
Now the alerts will show "tomorrow".
The AND function is used to test conditions and gives a boolean value as outcome:
var first = 3;
var second = 6;
alert(first < 4 && second > 4);
The alert will show "true" as both comparisons are true.
However using the AND function when the comparisons do not give a boolean value will show the last value:
alert(first < 4 && second > 4 && 6 && 90);
The alert will now show 90.
alert("today" && "tomorrow");
Now the alerts will show "tomorrow".
Another way to write one-line comments
Normally we write a comment on one line as
// this is a comment
But this is also valid:
<!-- this is also a comment.
Officilally it is a html comment but Javascript accepts it too.
Array with functions instead of switch
It is perfectly possible to replace a switch command by an array with functions. This is speedier and often shorter to program. The disadvantage is that this only works when the parameter is a number.
This is a normal switch setup:
number = 1;
switch(number)
{
case 1:
alert("number 1");
break;
case 2:
alert("number 2");
break;
case 3:
alert("number 3");
break;
}
We can replace this with:
var number = 1;
testarray =
[
function(){alert("number 1")},
function(){alert("number 2")},
function(){alert("number 3")}
];
testarray[number]();
Assign a default value to a variable
A variable may exist but may not have gotten a value assigned and therefore is empty. Using that variable in your program may give unpredictable results or throw an error and crash the program. The solution is to give the variable a default value which can be done as follows:
var author = "Luc ";
var country ;
country = country || "The Netherlands";
alert(author + country);
The || comparison returns the second value if the first value is empty.
This works slightly different when used with objects:
var origin =
{
name: 'Luc',
country: null
};
var country = origin.country || "The Netherlands";
alert(origin.name + " " + country);
The default value "The Netherlands" will be shown if the country element in the object is equal to: "", 0, null or undefined.
Clear all intervals
If you have multiple intervals running in your script and you want to stop them all you can use this snippet.
var interval_id = window.setInterval(()=>{}, 99999);
for (var i = 0; i < interval_id; i++)
window.clearInterval(i);
If you have multiple intervals running in your script and you want to stop them all you can use this snippet.
var interval_id = window.setInterval(()=>{}, 99999);
for (var i = 0; i < interval_id; i++)
window.clearInterval(i);
Clear localstorage
With just one command you can clear all information in localstorage. Please be aware that also info from other pages/scripts are cleared.
localStorage.clear();
Convert a variable to a boolean value
If you need to convert a variable to a Bolean (true or false) value you can do that with the double negate (!!) function. You can use this for example in a while loop.
var a = ""
!a gives true
!!a gives false
var a = "hallo"
!a gives false
!!a gives true
var a = 0
!a gives true
!!a gives false
Convert a Boolean value to a string
A Boolean variable has the value true or false. If yyou need to convert the value into a string you can do that with variable.toString like this :
bool = true
alert(typeof(bool))
stringbool = bool.toString()
alert(typeof(stringbool))
A Boolean variable has the value true or false. If yyou need to convert the value into a string you can do that with variable.toString like this :
bool = true
alert(typeof(bool))
stringbool = bool.toString()
alert(typeof(stringbool))
Convert a variable name to a string
The next tip shows how you can convert the name of a variable into a string.
var name = 'John'
varname = Object.keys({name})[0]
alert(varname)
The next tip shows how you can convert the name of a variable into a string.
var name = 'John'
varname = Object.keys({name})[0]
alert(varname)
Convert an RGB value into hex
The next snippet converts an rgb value into a hex value. You can use this to set a color of an element on your webpage,
function rgbintohex (r, g, b) {
return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}
hex = rgbintohex(255, 51, 255);
alert(hex)
The next snippet converts an rgb value into a hex value. You can use this to set a color of an element on your webpage,
function rgbintohex (r, g, b) {
return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}
hex = rgbintohex(255, 51, 255);
alert(hex)
Convert ASCII codes to a string
When working with sensors in an IOT project they might send their data as ascii codes instead of strings. The next line shows how to convert the ascii codes into strings.
String.fromCharCode(65,66,67);
When working with sensors in an IOT project they might send their data as ascii codes instead of strings. The next line shows how to convert the ascii codes into strings.
String.fromCharCode(65,66,67);
Delay in a foreach loop
If you want to put a delay into a foreach loop you can use the following example.
var numbers=[1,2,3,4,5]
var i=0
numbers.forEach((element,i) => {
setTimeout(function()
{
alert(element), i * 2000);
});
In this example the array elements are shown in an alert every 2 seconds
If you want to put a delay into a foreach loop you can use the following example.
var numbers=[1,2,3,4,5]
var i=0
numbers.forEach((element,i) => {
setTimeout(function()
{
alert(element), i * 2000);
});
In this example the array elements are shown in an alert every 2 seconds
Delay in a loop
If you need to delay while iterating here is how its done.
var counter = 1;
var times = 10;
function testloop() {
setTimeout(function() {
console.log('Javascript Tips '+ counter);
counter++;
if (counter < times) {
testloop();
}
}, 3000)
}
testloop();
Each time after counter is incremented we test if the value is lower then times and if so we call the function again.
If you need to delay while iterating here is how its done.
var counter = 1;
var times = 10;
function testloop() {
setTimeout(function() {
console.log('Javascript Tips '+ counter);
counter++;
if (counter < times) {
testloop();
}
}, 3000)
}
testloop();
Each time after counter is incremented we test if the value is lower then times and if so we call the function again.
Determine schreen width and height
To get the screen resolutions width and height you can use the next snippet.
alert("The screenwidth is: "+screen.width);
alert("The screenheightis: "+screen.height);
Encrypt and decode (base-64)
The commands btoa and atob allow us to encrypt text and numbers in an easy way. Here is an example:
var text = 'Javascript tips';
var encoded = window.btoa(text);
alert(encoded);
var decoded = window.atob(encoded);
alert(decoded)
The commands btoa and atob allow us to encrypt text and numbers in an easy way. Here is an example:
var text = 'Javascript tips';
var encoded = window.btoa(text);
alert(encoded);
var decoded = window.atob(encoded);
alert(decoded)
Escape characters
Here is a list of the most common escape characters used to format your text.
\' — Single quote
\" — Double quote
\\ — Backslash
\b — Backspace
\f — Form feed
\n — New line
\r — Carriage return
\t — Horizontal tabulator
WebsiteSetup.org - Beginner’s Javascript Cheat Sheet 7
\v — Vertical tabulator
Here is a list of the most common escape characters used to format your text.
\' — Single quote
\" — Double quote
\\ — Backslash
\b — Backspace
\f — Form feed
\n — New line
\r — Carriage return
\t — Horizontal tabulator
WebsiteSetup.org - Beginner’s Javascript Cheat Sheet 7
\v — Vertical tabulator
Forget OR use switch-case
It is obvious that using switch-case in stead of multiple if statements is much more organised and clear. Much less known is that it is also much clearer to use switch-case in stead of an if statement with multiple OR tests. The next example demonstrates this.
var language = "Javascript";
if (language == 'Javascript' || language == 'C++' || language == 'Python' )
{ console.log('The most frequently used programming languages')
}
switch(language)
{
case 'Javascript':
case 'C++':
case 'Python':
console.log('The most frequently used programming languages')
}
Both statements do the same but the switch-case statements look more organised and are easier to debug.
Generate a password of x characters
If you want to generate a password of x characters you can use the following snippet.
function newpass(numberchars)
{
var password = "";
var letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < numberchars; i++)
{
password += letters.charAt(Math.round(Math.random() * letters.length));
}
return password;
}
alert(newpass(10));
Generate a password of x characters 2
The next code shows how to generate a password of x characters.
The number of letters in the password is put in the variable amount. Next we generate
a random number from 1 to 26 and add that to 97. 97 is the start ascii code for letters in the alphabet.
var amount = 8;
function password(amount)
{
var newpas = '';
for(var i = 0; i < amount; i++)
{
var rand = Math.floor(Math.random() * 27);
newpas += String.fromCharCode(97 + rand);
};
return newpas;
};
newpassword = password(8)
alert(newpassword);
Generate a pseudo random number
You can generate a large pseudo random number by taking the time or part of it.
Here is an example.
newrand = Number(new Date())
alert (newrand)
You can generate a large pseudo random number by taking the time or part of it.
Here is an example.
newrand = Number(new Date())
alert (newrand)
Generate a random hex value
The next snippet shows how to generate a random hex value.
var hex = Math.floor(Math.random()*16777215).toString(16);
var hex = "#" + hex
alert(hex)
The next snippet shows how to generate a random hex value.
var hex = Math.floor(Math.random()*16777215).toString(16);
var hex = "#" + hex
alert(hex)
Get a random hex color
If you need a random hex color code youn can generate it with the following snippet.
var hexletters = '0123456789ABCDEF';
var color = '';
while(color.length < 6)
{
var random = Math.floor(Math.random() * 16);
color += hexletters[random];
};
color = "#" + color;
alert(color);
Get a random number within a certain range
To get a random number that falls into a certain range you can use the following snippet:
var minimum = 100;
var maximum = 200;
var difference = maximum-minimum;
var randomval = Math.random();
var newnumber = Math.floor((randomval * difference) + minimum);
alert(newnumber);
Get a list of all variables on a page
The next snippet shows how to obtain a list of all variables that are used on the current webpage.
var variables = "";
for (var name in this) variables += name + "\n";
alert(variables);
The next snippet shows how to obtain a list of all variables that are used on the current webpage.
var variables = "";
for (var name in this) variables += name + "\n";
alert(variables);
Give multiple variables simultaneous the same value
If you have multiple variables that you want to give the same value simultaneous you can use the following code.
var i;
var j;
var k;
var count;
var begin;
var i=j=k=count=begin=1;
You can use this also with strings.
Javascript undefined bug
There is a strange bug in the Javascript language. If a variable is defined but empty it is undefined. However undefined is not a reserved word.
var test;
var undefined = "fooled";
if (typeof test === "undefined")
{
alert("empty variabele");
}
alert (undefined)
Inspect what is stored in localstorage
You can find what is stored in localstorage with the following program lines.
var i;
console.log("local storage");
for (i = 0; i < localStorage.length; i++)
{
console.log(localStorage.key(i) + "=[" + localStorage.getItem(localStorage.key(i)) + "]");
}
You can find what is stored in localstorage with the following program lines.
var i;
console.log("local storage");
for (i = 0; i < localStorage.length; i++)
{
console.log(localStorage.key(i) + "=[" + localStorage.getItem(localStorage.key(i)) + "]");
}
Inspect what is stored in sessionstorage
Using the next lines you can find what is stored in session storage.
console.log("session storage");
for (i = 0; i < sessionStorage.length; i++)
{
console.log(sessionStorage.key(i) + "=[" + sessionStorage.getItem(sessionStorage.key(i)) + "]");
}
Using the next lines you can find what is stored in session storage.
console.log("session storage");
for (i = 0; i < sessionStorage.length; i++)
{
console.log(sessionStorage.key(i) + "=[" + sessionStorage.getItem(sessionStorage.key(i)) + "]");
}
Click Let your code run endlessly
The following trick lets your code run endlessly.
var a=0;
while(true)
{
alert(a++)
}
While true is of course always tru this loop will run endlesshere to edit.
The following trick lets your code run endlessly.
var a=0;
while(true)
{
alert(a++)
}
While true is of course always tru this loop will run endlesshere to edit.
Local storage clearing
There are two ways to clear Local Storage. The first method is by using clear().
localStorage.clear();
The second method is by iterating over all elemenets and deletingn the keys.
for(key in localStorage)
{
delete localStorage[key];
There are two ways to clear Local Storage. The first method is by using clear().
localStorage.clear();
The second method is by iterating over all elemenets and deletingn the keys.
for(key in localStorage)
{
delete localStorage[key];
Localstorage only stores strings
Local storage can be used for temporarely store data. But be aware that you can only store strings in local storage.
The way to store strings and numbers in local storage is to put all data in an array and convert that array to a string with JSON.stringify()
Local storage can pose a safety problem
Local storage can be used to temporarely store data. This can pose a safety breech as the data is stored on your local harddisk and is not encrypted or password prorected. So other programs or jabascript scripts can get access to the data and even alter it. So be carefull with what you store in localstorage.
Make your code looking good
If your program is (at last) ready you need to document it for future use. One of the things that makes code easier to read is to have indents and brackets etc consistent all over the code. The next website allows you to paste your code and makes it looking good.
https://beautifier.io/
Measure how long a function or piece of code runs
You might want to know how long it takes for a function or a block of code to run. Testing the performance might show if you need to optimise for speed. In this book there is a section that tells how to pause a program. We use that here and measure how long the pause took.
var startTime = performance.now();
// pause 2000 millieseconds
let millies = 2000;
let start = new Date().getTime();
let end = start;
while(end < start + millies) {
end = new Date().getTime();
}
var endTime = performance.now();
var totalTime=endTime-startTime;// time took to run in milliseconds
You might want to know how long it takes for a function or a block of code to run. Testing the performance might show if you need to optimise for speed. In this book there is a section that tells how to pause a program. We use that here and measure how long the pause took.
var startTime = performance.now();
// pause 2000 millieseconds
let millies = 2000;
let start = new Date().getTime();
let end = start;
while(end < start + millies) {
end = new Date().getTime();
}
var endTime = performance.now();
var totalTime=endTime-startTime;// time took to run in milliseconds
Measure the performance of a code block
During developing software you might wonder how fast the code you are writing is. You can measure this with console.time and console.timeEnd. The time measured is only shown in the console (hence the name). Here is an example.
console.time("primeornot");
function testprime()
{
if (figure===1)
{
return false;
}
if(figure === 2)
{
return true;
}
if (figure > 2)
{
for(var x = 2; x < figure; x++)
{
if(figure % x === 0)
{
return false;
}
}
return true;
}
}
console.log(testprime(155035219));
console.timeEnd("primeornot");
Multiple lines in an alert
When showing an alert most of the times all information is shown on a single line. You can make things more clear by showing the information on multiple lines. To get multiple lines use \r\n in your text as the next snippet demonstrates.
text = "Javascript Tips \r\n";
text = text + "Luc Volders \r\n";
text = text + "English version"
alert(text);
When showing an alert most of the times all information is shown on a single line. You can make things more clear by showing the information on multiple lines. To get multiple lines use \r\n in your text as the next snippet demonstrates.
text = "Javascript Tips \r\n";
text = text + "Luc Volders \r\n";
text = text + "English version"
alert(text);
NaN is sometimes not equal to NaN
Here is a example that will make you wonder.
alert (NaN == NaN)
alert (NaN === NaN)
Both alerts will show "false"
Now add the next lines
var NaN = 5
alert (NaN)
And now both alerts will show false...........
IN JSFiddle the outcome will be "false" and NaN like it should. In Javascript tester the outcome is "true"and 5.
So be carefull with NaN.
Here is a example that will make you wonder.
alert (NaN == NaN)
alert (NaN === NaN)
Both alerts will show "false"
Now add the next lines
var NaN = 5
alert (NaN)
And now both alerts will show false...........
IN JSFiddle the outcome will be "false" and NaN like it should. In Javascript tester the outcome is "true"and 5.
So be carefull with NaN.
Pause in Javascript
If you need a pause (sleep, delay) function in your program you can use the next snippet.
function pause(ms)
{
var time = new Date();
var time2 = null;
do { time2 = new Date(); }
while(time2-time < ms);
}
pause(5000)
alert("5 seconds later")
If you need a pause (sleep, delay) function in your program you can use the next snippet.
function pause(ms)
{
var time = new Date();
var time2 = null;
do { time2 = new Date(); }
while(time2-time < ms);
}
pause(5000)
alert("5 seconds later")
Pause in Javascript 2
To pause your script you can use the next lines. The variable millies contains the time in milliseconds.
let millies = 2000;
let start = new Date().getTime();
let end = start;
while(end < start + millies) {
end = new Date().getTime();
}
alert("time is up")
To pause your script you can use the next lines. The variable millies contains the time in milliseconds.
let millies = 2000;
let start = new Date().getTime();
let end = start;
while(end < start + millies) {
end = new Date().getTime();
}
alert("time is up")
Press a single key to activate a function
The next code shows how you can intercept a keypress to activate a function. Pressing the letter d on your keyboard makes the background color of the page black. Pressing the letter l sets it back to default.
document.addEventListener('keydown', function (event)
{
if (event.key === 'd')
{
document.body.style = "color: white; background-color: black";
}
if (event.key === 'l')
{
document.body.style = '';
}
});here to edit.
The next code shows how you can intercept a keypress to activate a function. Pressing the letter d on your keyboard makes the background color of the page black. Pressing the letter l sets it back to default.
document.addEventListener('keydown', function (event)
{
if (event.key === 'd')
{
document.body.style = "color: white; background-color: black";
}
if (event.key === 'l')
{
document.body.style = '';
}
});here to edit.
Prevent errors
Here is a simple method to prevent errors in formula's or commands.
var a = "";
alert(a*a || 0);
Using || 0 will give 0 if the formula throws an error. Here are some
more examples.
alert(0/0 || 0);
alert(" "*5 || 0);
You can replace 0 by an error message like the following shows:
alert(0/0 || "error !!");
Here is a simple method to prevent errors in formula's or commands.
var a = "";
alert(a*a || 0);
Using || 0 will give 0 if the formula throws an error. Here are some
more examples.
alert(0/0 || 0);
alert(" "*5 || 0);
You can replace 0 by an error message like the following shows:
alert(0/0 || "error !!");
Random true or false
If you need a random true or false (like head or tails in a game) you can check whether Math.random() is larger then 0.5 as the next snippet shows.
function randbool()
{
return Math.random() >= 0.5;
}
alert(randbool());
If you need a random true or false (like head or tails in a game) you can check whether Math.random() is larger then 0.5 as the next snippet shows.
function randbool()
{
return Math.random() >= 0.5;
}
alert(randbool());
Remove a variable from localstorage
We can store variables in localstorage for later use. And sometimes you will want to remove a variable from localstorage. You can do that with:
window.localStorage.removeItem("my_item_key");
We can store variables in localstorage for later use. And sometimes you will want to remove a variable from localstorage. You can do that with:
window.localStorage.removeItem("my_item_key");
Skip a step in a loop
In a loop you can test the condition of a variable and act on that. You can also test for a variable and skip that step using the command continue; Here is an example.
for (var i = 1; i<10; i++)
{
if (i ==5)
{continue}
console.log(i)
}
Every number from 1 to 10 will be printed in the console except 5.
In a loop you can test the condition of a variable and act on that. You can also test for a variable and skip that step using the command continue; Here is an example.
for (var i = 1; i<10; i++)
{
if (i ==5)
{continue}
console.log(i)
}
Every number from 1 to 10 will be printed in the console except 5.
Speak out your texts
Every web browser has a build in speech synthesizer. This means that you can have all texes on your webpage or variables spoken out loud.
Having the webpage speak to you is easy. Just use:
speechSynthesis.speak(new SpeechSynthesisUtterance('Hello World'));
By altering some variables you can influence the language and speed in which the sentences are spoken.
var u = new SpeechSynthesisUtterance();
u.text = 'This is really good English';
u.lang = 'en-US';
u.rate = 1.2;
speechSynthesis.speak(u);
The voice is browser dependend. So the spoken words sound different on Firefox as on Chrome. But the pronunciation is generally excellent.
For using other languages you can use the letter codes from the BCP 47 language tag like:
English, United States : en-US
German, Germany : de-DE
Spanish : es-ES_tradnl
French, France : fr-FR
Japanese, Japan : ja-JP
Portuguese, Brazil : pt-BR
Russian, Russian Federation : ru-RU
Hindi, India : hi-IN
Chinese, China : zh-CN
English, United Kingdom : en-GB */
Every web browser has a build in speech synthesizer. This means that you can have all texes on your webpage or variables spoken out loud.
Having the webpage speak to you is easy. Just use:
speechSynthesis.speak(new SpeechSynthesisUtterance('Hello World'));
By altering some variables you can influence the language and speed in which the sentences are spoken.
var u = new SpeechSynthesisUtterance();
u.text = 'This is really good English';
u.lang = 'en-US';
u.rate = 1.2;
speechSynthesis.speak(u);
The voice is browser dependend. So the spoken words sound different on Firefox as on Chrome. But the pronunciation is generally excellent.
For using other languages you can use the letter codes from the BCP 47 language tag like:
English, United States : en-US
German, Germany : de-DE
Spanish : es-ES_tradnl
French, France : fr-FR
Japanese, Japan : ja-JP
Portuguese, Brazil : pt-BR
Russian, Russian Federation : ru-RU
Hindi, India : hi-IN
Chinese, China : zh-CN
English, United Kingdom : en-GB */
Stop a loop after some time
Some loops run undefinitely. The next code shows how you can stop such a loop after a predefined period of time.
var looprunning = true;
var i=0;
setTimeout(function () {
looprunning = false;
}, 100);
while ( looprunning ) {
i++
console.log(i)
}
Some loops run undefinitely. The next code shows how you can stop such a loop after a predefined period of time.
var looprunning = true;
var i=0;
setTimeout(function () {
looprunning = false;
}, 100);
while ( looprunning ) {
i++
console.log(i)
}
Stop running code on a condition
We can put code into a block and stop running that code if a certain condition is met. The next snippet shows how to do this.
var stopcondition = 5;
testblock:
{
alert('This text is shown');
if (stopcondition == 5)
{
break testblock;
}
alert('This line is not shown');
}
alert("here continues the rest of the code");
We can put code into a block and stop running that code if a certain condition is met. The next snippet shows how to do this.
var stopcondition = 5;
testblock:
{
alert('This text is shown');
if (stopcondition == 5)
{
break testblock;
}
alert('This line is not shown');
}
alert("here continues the rest of the code");
Store large amounts of data
You can store a large amount of data (temporarely) in localstorage by converting them into aarray. Here is an example.
myarray = [1,"Luc",2,3,"newbook"]
localStorage.setItem("mytest", JSON.stringify(myarray))
Keep in mind that all items are converted in a string.
To retrieve the data you can use the next code:
arraytwo = JSON.parse(localStorage.getItem("mytest"))
You can get the individual items back by adressing the array elements:
alert(JSON.stringify(arraytwo[0]))
You can store a large amount of data (temporarely) in localstorage by converting them into aarray. Here is an example.
myarray = [1,"Luc",2,3,"newbook"]
localStorage.setItem("mytest", JSON.stringify(myarray))
Keep in mind that all items are converted in a string.
To retrieve the data you can use the next code:
arraytwo = JSON.parse(localStorage.getItem("mytest"))
You can get the individual items back by adressing the array elements:
alert(JSON.stringify(arraytwo[0]))
Store data in a file
Javascript is very cautious on doing things on your harddisk. Nevertheless there is a way to store data collected on your webpage in a file on your computer. Put the data in the variable testtext and the data will be downloaded as a file to your computer with the filename example.txt
<!DOCTYPE html>
<html>
<script>
window.onload = function(){
function download(filename, text) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
// Start file download.
var testtext = "Hello world. This is a test.\nThis starts on a new line.\nAnd here is another line";
download("example.txt", testtext);
alert("done")
}
</script>
</html>
You need to put this into the window.onload = function(){} otherwise it will not execute.
Javascript is very cautious on doing things on your harddisk. Nevertheless there is a way to store data collected on your webpage in a file on your computer. Put the data in the variable testtext and the data will be downloaded as a file to your computer with the filename example.txt
<!DOCTYPE html>
<html>
<script>
window.onload = function(){
function download(filename, text) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
// Start file download.
var testtext = "Hello world. This is a test.\nThis starts on a new line.\nAnd here is another line";
download("example.txt", testtext);
alert("done")
}
</script>
</html>
You need to put this into the window.onload = function(){} otherwise it will not execute.
Swap two or more variables
Here is a fast method to swap the contents of two variables.
var a = 100;
var b = 10;
var c = 5;
[a, b, c] = [c, a, b];
a will get the value of c, b will get the value of a and c will get the value of b.
Here is a fast method to swap the contents of two variables.
var a = 100;
var b = 10;
var c = 5;
[a, b, c] = [c, a, b];
a will get the value of c, b will get the value of a and c will get the value of b.
Switch case with comparisons
Swtch-case is ideal for testing a bunch of variables. It is however only possible to test absolute values.
var temperature = 18;
switch(temperature)
{
case 15:
alert("Cold");
break;
case 20:
alert ("Just right");
break;
default:
alert("Not in test sequence");
}
In this situation "Not in test sequence" would be shown.
It would be more convenient if we could do test like larger as (>) or smaller then (<). This is possible with a trick as you can see in the next snippet.
function gettemperature(temp)
{
var feelslike = "";
switch (true)
{
case isNaN(temp):
feelslike = "No figure given";
break;
case (temp >= 25):
feelslike = "Hot";
break;
case (temp <= 18):
feelslike = "Cold";
break;
default:
feelslike = "Normal";
break;
};
return feelslike;
}
alert(gettemperature(20));
By putting switch inside a function it is possible to use comparisons.
Swtch-case is ideal for testing a bunch of variables. It is however only possible to test absolute values.
var temperature = 18;
switch(temperature)
{
case 15:
alert("Cold");
break;
case 20:
alert ("Just right");
break;
default:
alert("Not in test sequence");
}
In this situation "Not in test sequence" would be shown.
It would be more convenient if we could do test like larger as (>) or smaller then (<). This is possible with a trick as you can see in the next snippet.
function gettemperature(temp)
{
var feelslike = "";
switch (true)
{
case isNaN(temp):
feelslike = "No figure given";
break;
case (temp >= 25):
feelslike = "Hot";
break;
case (temp <= 18):
feelslike = "Cold";
break;
default:
feelslike = "Normal";
break;
};
return feelslike;
}
alert(gettemperature(20));
By putting switch inside a function it is possible to use comparisons.
Switch case with multiple parameters
Normally we test switch-case with a single parameter in each case statement. It is nor widely known that you can put multiple parameters in the case statement. Here is an example that shows how to do this.
var room = "bedroom";
var upordown="";
switch(room) {
case "cellar":case "kitchen":case "mancave":
upordown = "Downstairs";
break;
case "bedroom":case "shower":case "attick":
upordown = "Upstairs";
break;
default:
upordown = "Unknown";
}
alert(upordown)
Cellar, kitchen and mancave will all give Downstairs as an answer. Bedroom, shower and attick will each give Upstairs ans the answer.
Normally we test switch-case with a single parameter in each case statement. It is nor widely known that you can put multiple parameters in the case statement. Here is an example that shows how to do this.
var room = "bedroom";
var upordown="";
switch(room) {
case "cellar":case "kitchen":case "mancave":
upordown = "Downstairs";
break;
case "bedroom":case "shower":case "attick":
upordown = "Upstairs";
break;
default:
upordown = "Unknown";
}
alert(upordown)
Cellar, kitchen and mancave will all give Downstairs as an answer. Bedroom, shower and attick will each give Upstairs ans the answer.
Switch case with return statements
By placing a switch-case statement inside a function we can place the outcome of the test in a return statement just like in a normal function. The next snippet shows how to achieve this.
function gettemperature(temp)
{
var tempfeel = "";
switch (true)
{
case isNaN(temp):
return "No figure given";
break;
case (temp >= 25):
tempfeel = "Hot";
return tempfeel;
break;
case (temp <= 18):
tempfeel = "Cold";
return tempfeel;
break;
default:
tempfeel = "normal";
return tempfeel;
break;
};
}
alert(gettemperature("20")); ere to edit.
By placing a switch-case statement inside a function we can place the outcome of the test in a return statement just like in a normal function. The next snippet shows how to achieve this.
function gettemperature(temp)
{
var tempfeel = "";
switch (true)
{
case isNaN(temp):
return "No figure given";
break;
case (temp >= 25):
tempfeel = "Hot";
return tempfeel;
break;
case (temp <= 18):
tempfeel = "Cold";
return tempfeel;
break;
default:
tempfeel = "normal";
return tempfeel;
break;
};
}
alert(gettemperature("20")); ere to edit.
Switch-Case
If we need to chose between many options the switch-case commands is more efficient as using a lot of if-thens. A draw-back is when working with strings this is case-sensitive. The words need to match exactly. If case needs to react on "Javascript" then "javascript" will not activate the case function. To avoid these kinds of problems convert the search-string to lowercase (or uppercase) as the next example shows.
var teststring = "Javascript";
teststring = teststring.toLowerCase();
switch (teststring)
{
case 'javascript':
alert("Javascript chosen");
break;
case 'python':
alert("To bad you chose Python");
break;
default:
alert("Totally wrong")
}
If we need to chose between many options the switch-case commands is more efficient as using a lot of if-thens. A draw-back is when working with strings this is case-sensitive. The words need to match exactly. If case needs to react on "Javascript" then "javascript" will not activate the case function. To avoid these kinds of problems convert the search-string to lowercase (or uppercase) as the next example shows.
var teststring = "Javascript";
teststring = teststring.toLowerCase();
switch (teststring)
{
case 'javascript':
alert("Javascript chosen");
break;
case 'python':
alert("To bad you chose Python");
break;
default:
alert("Totally wrong")
}
Test if a variable exists
In the HTML section you can find a snippet that shows all variables that are used on a page. If you just need to know if a certain variable exists you can use the next snippet. In this example we test if the variable test3345 exists.
if (typeof(test3345) !== undefined) {
alert("unknown varaiable")
}
In the HTML section you can find a snippet that shows all variables that are used on a page. If you just need to know if a certain variable exists you can use the next snippet. In this example we test if the variable test3345 exists.
if (typeof(test3345) !== undefined) {
alert("unknown varaiable")
}
Test if a variable is empty
A variable might be declared but not yet given a value. Of you perform an operation on that variable you might get an error. You can test if a variable ie empty to prevent these errors. You can do that like the next snippet shows.
var test;
if (Boolean(test))
{
alert ("variabele has a value");
}
else
{
alert ("variabele is empty");
}
A variable might be declared but not yet given a value. Of you perform an operation on that variable you might get an error. You can test if a variable ie empty to prevent these errors. You can do that like the next snippet shows.
var test;
if (Boolean(test))
{
alert ("variabele has a value");
}
else
{
alert ("variabele is empty");
}
Test if the browser support touch events
Sometimes you need to know if a program runs on a computer or a tablet/phone. You can test that by checking if the touch events are supported as the following code shows:
const touchscreen = () =>
window && 'ontouchstart' in window;
alert(touchscreen());
Sometimes you need to know if a program runs on a computer or a tablet/phone. You can test that by checking if the touch events are supported as the following code shows:
const touchscreen = () =>
window && 'ontouchstart' in window;
alert(touchscreen());
Test if localstorage is activated
We can use localstorage for storing data that can be used later on. This might pose a problem if the user or one of his programs has disabled localstorage. The next snippet shows how to test whether localstorage is activated or not.
function localtest ()
{
try
{
var item = "tipstest";
var value = "yes or no";
localStorage.setItem(item, value);
localStorage.removeItem(item);
return true;
}
catch (e)
{
return false;
}
};
alert(localtest());
We can use localstorage for storing data that can be used later on. This might pose a problem if the user or one of his programs has disabled localstorage. The next snippet shows how to test whether localstorage is activated or not.
function localtest ()
{
try
{
var item = "tipstest";
var value = "yes or no";
localStorage.setItem(item, value);
localStorage.removeItem(item);
return true;
}
catch (e)
{
return false;
}
};
alert(localtest());
Test if localstorage is used or empty
If you need to test wether localstorage contains elements or not you can use the next snippet.
if (localStorage.length > 0)
{
alert("There are elements in localstorage")
}
else
{
alert("Local storage is empty")
}
If you need to test wether localstorage contains elements or not you can use the next snippet.
if (localStorage.length > 0)
{
alert("There are elements in localstorage")
}
else
{
alert("Local storage is empty")
}
Test if sessionstorage is activated
If you need to store some data only for the duration of the window being active you can use sessionstorage. However the user or one of his programs may have disabled sessionstorage. To know if sessionstorage is activated use the next snippet.
function sessiontest ()
{
try
{
var item = "tipstest";
var value = "yes or no";
sessionStorage.setItem(item, value);
sessionStorage.removeItem(item);
return true;
}
catch (e)
{
return false;
}
};
alert(sessiontest());
If you need to store some data only for the duration of the window being active you can use sessionstorage. However the user or one of his programs may have disabled sessionstorage. To know if sessionstorage is activated use the next snippet.
function sessiontest ()
{
try
{
var item = "tipstest";
var value = "yes or no";
sessionStorage.setItem(item, value);
sessionStorage.removeItem(item);
return true;
}
catch (e)
{
return false;
}
};
alert(sessiontest());
Test if user is online
There are several reasons why you should check if a user is online.
If the user is not online you can for example not use external
storage or libraries. To test wether the user is online use the next snippet.
if (window.navigator.onLine==true)
{
alert("user is online");
}
There are several reasons why you should check if a user is online.
If the user is not online you can for example not use external
storage or libraries. To test wether the user is online use the next snippet.
if (window.navigator.onLine==true)
{
alert("user is online");
}
Toggle a Boolean variable
There is a real easy way to toggle a Boolean variable. Meaning that True becomes False and the other way round. it is done with the !(not) operator.
thing = True
thing = !thing
There is a real easy way to toggle a Boolean variable. Meaning that True becomes False and the other way round. it is done with the !(not) operator.
thing = True
thing = !thing
Use AND as a replacement for if()
It is possible to use && as a replacement for an if() command on one line.
var test = 10;
test == 10 && alert ("Yes")
This is the same as if (test = 10) {alert ("Yes")}
However an if() contstruction can use multiple lines and in the example the part aftre the && must be on the same line.
It is possible to use && as a replacement for an if() command on one line.
var test = 10;
test == 10 && alert ("Yes")
This is the same as if (test = 10) {alert ("Yes")}
However an if() contstruction can use multiple lines and in the example the part aftre the && must be on the same line.
Use OR to give a variable a default value
We can use || to give a variable a default value.
test = 0;
test = test || 10;
alert(test)
In this example test will get the value 10.
Actually this is the same as.
if (test = 0) {test = 10};
This not only works when test = 0 but also if test = "" or undefined or false.
We can use || to give a variable a default value.
test = 0;
test = test || 10;
alert(test)
In this example test will get the value 10.
Actually this is the same as.
if (test = 0) {test = 10};
This not only works when test = 0 but also if test = "" or undefined or false.
Use OR to test if a variable is falsey
We can use the previous tip in another way to test if an variable id falsey and act on that.
test = 0;
test = test || alert("empty")
Replace the alert by a function or any other Javascript command you need
We can use the previous tip in another way to test if an variable id falsey and act on that.
test = 0;
test = test || alert("empty")
Replace the alert by a function or any other Javascript command you need
Use promp for a quick answer
We can use prompt to get a quick answer from a user. This snippet shows how to test what de user entered.
var name = prompt("What is your name");
if (name === null)
{
alert("You pressed cancel");
}
else
{
alert("Hello : " + name);
We can use prompt to get a quick answer from a user. This snippet shows how to test what de user entered.
var name = prompt("What is your name");
if (name === null)
{
alert("You pressed cancel");
}
else
{
alert("Hello : " + name);
What is syntactic sugar (software candy)
Syntactic sugar means that the new features of the language
are not really new. Instead, they are a nicer syntax for something existing.
You could do exactly the same by writing something different in the old version.
An example is the arrow function. You can use the arrow functions or use the old equivalent. The arrow functions do not offer anything new. Another example is the Ternary operator that is just a substitution for if - else
Syntactic sugar means that the new features of the language
are not really new. Instead, they are a nicer syntax for something existing.
You could do exactly the same by writing something different in the old version.
An example is the arrow function. You can use the arrow functions or use the old equivalent. The arrow functions do not offer anything new. Another example is the Ternary operator that is just a substitution for if - else
Where is the mouse on your screen
The next lines of code display the mouse location every second in the console window.
<!DOCTYPE html>
<html>
<title>Online Javascript Editor</title>
<head>
<script>
var horizontal = -1;
var vertical = -1;
document.onmousemove = function(event) {
horizontal = event.pageX;
vertical = event.pageY;
}
setInterval(mouselocation, 1000);
function mouselocation() {
console.log('Cursor at: '+horizontal+', '+vertical);
}
</script>
</head>
<body>
The next lines of code display the mouse location every second in the console window.
<!DOCTYPE html>
<html>
<title>Online Javascript Editor</title>
<head>
<script>
var horizontal = -1;
var vertical = -1;
document.onmousemove = function(event) {
horizontal = event.pageX;
vertical = event.pageY;
}
setInterval(mouselocation, 1000);
function mouselocation() {
console.log('Cursor at: '+horizontal+', '+vertical);
}
</script>
</head>
<body>
Where is this webpage located
It might be necessary to know where the current webpage is coming from. It might be a server or a local file. Think about safety: we need to make sure that the page is loaded from the right server or from the right subdirectory.
We can get the current location of the webpage with the following commands:
var protocol = window.location.protocol;
var server = window.location.host;
var path = window.location.pathname;
protocol will be file: or http: or https:
server will provide the name of the server or nothing
path provides the name of the subdirectory
It might be necessary to know where the current webpage is coming from. It might be a server or a local file. Think about safety: we need to make sure that the page is loaded from the right server or from the right subdirectory.
We can get the current location of the webpage with the following commands:
var protocol = window.location.protocol;
var server = window.location.host;
var path = window.location.pathname;
protocol will be file: or http: or https:
server will provide the name of the server or nothing
path provides the name of the subdirectory
Where is this webpage located 2
Here is another way to find the location the current webpage is loaded from. This way you can see if it is from the original server or a copy.
getfrom = window.location.href;
alert(getfrom);
Here is another way to find the location the current webpage is loaded from. This way you can see if it is from the original server or a copy.
getfrom = window.location.href;
alert(getfrom);
Which language does the user use
For some purposes it is important to know which language the user uses. You can check that with the next snippet:
var language = window.navigator.userLanguage || window.navigator.language;
alert(language)
For some purposes it is important to know which language the user uses. You can check that with the next snippet:
var language = window.navigator.userLanguage || window.navigator.language;
alert(language)