
This article contains coding hints and mini examples about JavaScript. You may find them helpful during your JavaScript language exploration oncodeguppy.com.
- Variables
- if statement
- For loop
- While loop
- Do While loop
- Switch statement
- Functions
- Array methods
- String methods
- Random numbers
- Modules
Declaring variables
Variables are used to store data such as numbers, strings (text) or even complex objects. Remember:
- You can have as many variables as you want inside a program.
- You need to name each variable with a name that represents the data it stores.
- Give different names to variables inside the same code block (e.g. whats between
{ ... }
) or even inside a function
Declare variable x
letx;
Declare x and initialize it with a numerical value
letx=1;
Declare s and initialize it with a string
lets="Hello, World!";
Assigning values to variables
Once a variable has been declared withlet
it can be assigned / reassigned with different values as many times as you want.
You can assign it with simple constants or even complex expressions that include constants, other variables and even the same variable! Computers are very good at evaluating expressions.
Assign number 100 to variable x
x=100;
Assign string "Hello" to variable s
s="Hello";
Assign an empty array to variable ar
ar=[];
Assign an array of 3 numbers to variable ar
ar=[1,2,3];
Assign and array of 2 strings to variable ar
ar=["A","B"];
Assign an inline object to variable o
o={Type:'car',x:100,y:200};
Variable sum is equal to a + b
sum=a+b;
Assign an expression to variable avg
avg=(a+b)/2;
Variable sum is increased by 10 (the new sum becomes the older sum + 10)
sum=sum+10;
Variable i is increased (incremented) by 1
i++;
Variable i is incremented by 2
i+=2;
If statement
if
statements are great for controlling the flow of the program. Normally a program is executed one instruction at a time, from top to bottom.
if
allow to take a decision and execute a set of instructions if the condition is met.
Executes the block of instructions between {} if condition is true
if(mouseX<width){}
Executes the first block of instructions if condition is true, otherwise the second block
if(hour<12){}else{}
Executing different blocks based on different conditions
In the following example, if the first condition is true, then the first block will be executed and the others not.
However, if the first condition is not true, theelse if
is used to test another condition, and if is true, the block of thatelse if
is executed.
The block after the lastelse
is executed only if no other condition was true until that point.
if(minute<=15){}elseif(minute<=30){}else{}
Note: You can have multipleelse if
blocks in this kind of experessions.
For loop
Prints numbers from 0 to 4 using a for loop and println
for(leti=0;i<5;i++){println(i);}
Prints numbers from 10 down to 0 using a for loop
for(leti=10;i>=0;i--){println(i);}
Prints even numbers from 0 to 100
for(leti=0;i<=100;i+=2){println(i);}
Print all elements of an array
letar=[10,20,30];for(letelementofar){println(element);}
While loop
Print numbers from 0 to 9 using awhile
loop
leti=0;while(i<10){println(i);i++;}
Do While
Print numbers from 0 to 10 using ado while
loop
leti=0;do{println(i);i++;}while(i<10)
Note:do while
loop places condition after the code block, therefore the block can execute at least once even if the condition is false.
Switch Statement
Aswitch
statement is another instruction besidesif
/else if
for controlling the flow of a program. You can use switch to compare an expression against different values and then run the coresponding set of instructions based if that expression is equal to anycase
value.
Usuallyswitch
is used less often thanif
/else if
/else
.
switch(myExpresion){case100://...break;case200://...break;case300://...break;default://...}
Functions
Functions are great for creating new languageinstructions
that you can use over and over again in a program.
Once you define a new instruction, it becomes indistinguishable from the built-in instructions present in JavaScript and codeguppy.com
Defining and calling the functionballoon
// Function balloon draws a balloon using simple shapes such as circle and line// It expects as arguments the coordinates for balloon center and the color of the balloonfunctionballoon(x,y,shapeColor){letr=30;letstringLen=100;fill(shapeColor);stroke(shapeColor);circle(x,y,r);line(x,y+r,x,y+r+stringLen);}// Call function balloon with different parametersballoon(100,100,"red");balloon(300,300,"blue");balloon(500,200,"yellow");
Functions that return values
functionaddNumbers(x,y){returnx+y;}// Call a functionvarsum=addNumbers(100,200);println(sum);
Note: codeguppy.com includes a big number of built-in functions such ascircle
,rect
, etc. You can call these functions in the same way you're calling your own custom function.
Array methods
Use an array to conveniently store a series of values using a single variable name. An array has properties and methods that allow to manipulate its elements.
Declaring and initializingar
to an empty array
letar=[];
Declaring and initializingar
to an array of 3 numbers
letar=[10,20,30];
Length of an array
letar=[10,20,30];println("Length of array:",ar.length);
Append an element at the end of the array
letar=[10,20,30];ar.push(100);println(ar);
Insert an element at the beginning of an array
letar=[10,20,30];ar.unshift(1);println(ar);
Insert an element at an arbitrary position
letar=[10,20,30];// 1 -> after element with potion 1// 0 -> delete 0 elements// 15 -> insert number 15ar.splice(1,0,15);println(ar);
Insert an element at an arbitrary position (easy mode)
Note: Theinsert
array method is present only in codeguppy.com
letar=[10,20,30];ar.insert(1,17);println(ar);
Read the value of element2
of an array
letar=[10,20,30];println(ar[2]);
Calculate the sum of elements of an array
letar=[10,20,30];letsum=0;for(letelementofar){sum+=element;}println(sum);
Assign a different value to al element of an array
letar=[10,20,30];ar[2]=100;println(ar);
Accesing the first element
letar=[10,20,30];println(ar[0]);
Accessing the last element
letar=[10,20,30];letlen=ar.length;println(ar[len-1]);
Accessing the last element (easy way)
Note: Thepeek
array method is present only in codeguppy.com
letar=[10,20,30];println(ar.peek());
Remove the first element of the array
letar=[10,20,30];ar.shift();println(ar);
Remove the last element of the array
letar=[10,20,30];ar.pop();println(ar);
Remove an element at an arbitrary position
letar=[10,20,30];// 0 -> element index// 1 -> number of elements to removear.splice(0,1);println(ar);
Remove all elements of an array
letar=[10,20,30];// clear() is CodeGuppy specific// use ar.lenght = 0; outside CodeGuppyar.clear();println(ar);
Concatenate two arrays
// Merge / concatenate 2 arraysletar1=["a","b","c"];letar2=["d","e","f"];letar=ar1.concat(ar2);println(ar);
Extract a slice of an array
slice()
is an interesting method that can be used to extract a "slice" from an array. The "slice" will be retured as an independent array. The method receives as arguments the index of the first element (inclusive) and the index of the last element that we want in the slice (exclusive):
letar=["a","b","c","d","e","f"];// Extracting a 'slice' from an arrayletarSlice=ar.slice(2,4);println(arSlice);
Joining elements of an array
letar=["a","b","c","d","e","f"];// Join all elements in a string using separator ;lets=ar.join(";");println(s);
String methods
Just like with arrays, you can access and manipulate independent characters within a string.
Length of a string
lettxt="JavaScript";println(txt.length);
Iterating all characters of a string
lettxt="JavaScript";for(letchroftxt){println(chr);}
Accessing string characters by position
lettxt="JavaScript";for(leti=0;i<txt.length;i++){println(txt[i]);}
Converting text to uppercase
lettxt="JavaScript";txt=txt.toUpperCase();println(txt);
Converting text to lowercase
lettxt="JavaScript";txt=txt.toLowerCase();println(txt);
Determine if the string contains another substring
lettxt="Coding is cool!";letsearch="cool";if(txt.includes(search)){println(search+" was found in"+txt);}
Determine if the string starts with a specified prefix
lettxt="JavaScript is cool!";letsearch="JavaScript";if(txt.startsWith(search)){println(txt+" starts with"+search);}
Determine if the string ends with a specified sufix
lettxt="JavaScript is cool!";letsearch="!";if(txt.endsWith(search)){println("It is an exclamation!");}
Find the position of a substring. Search starts at the beginning
lettxt="JavaScript is cool!";letsearch="cool";letfoundAt=txt.indexOf(search);if(foundAt<0)println("Not found!");elseprintln("Found at position"+foundAt);
Find the position of a substring. Search starts at specified index.
lettxt="JavaScript is cool! Super cool!";letsearch="cool";letstartAt=18;letfoundAt=txt.indexOf(search,startAt);if(foundAt<0)println("Not found!");elseprintln("Found at position"+foundAt);
Extract a substring from the string
lettxt="JavaScript is cool!";letindex1=14;letindex2=18;lettxt2=txt.substring(index1,index2);println(txt2);
Remove whitespaces from beginning and end of the string
lettxt=" I love coding !";txt=txt.trim();println("'"+txt+"'");
Remove whitespaces from beginning of the string
lettxt=" I love coding !";txt=txt.trimStart();println("'"+txt+"'");
Remove whitespaces from the end of the string
lettxt=" I love coding !";txt=txt.trimEnd();println("'"+txt+"'");
Pads the start of the string with another string
letno=3;lettxt=no.toString(2).padStart(8,'0');println(txt);
Pads the end of the string with another string
letn1="1";letn2="3";txt=n1+"."+n2.padEnd(4,'0');println(txt);
Codes of characters
lettxt="JavaScript";for(letchroftxt){// Obtain the Unicode code point value// ... identical to ASCII code for the range of ASCII valuesletcode=chr.codePointAt(0);letline=chr+"\t"+code.toString()+"\t"+code.toString(16).toUpperCase()+"\t"+code.toString(2).padStart(7,"0");println(line);}
Characters from codes
letmsg="73 32 76 79 86 69 32 67 79 68 73 78 71"letbase=10;letarMsg=msg.split("");for(leti=0;i<arMsg.length;i++){if(!arMsg[i])continue;letcode=parseInt(arMsg[i],base);// Obtain the character from the Unicode code point// (the Unicode code point is the same with ASCII code for the range of ASCII values)letchr=String.fromCodePoint(code);println(chr);}
Random numbers
Random numbers are extremly useful in coding.
To obtain a random number in JavaScript between0
(inclusive) and1
(exclusive) you can useMath.random()
function.
letr=Math.random();println(r);
codeguppy.com extends the support for random numbers with additional instructions that let you quickly pick a random number in the prefered range.
Random floating point number between 0 and 1 (1 not included)
This is the same asMath.random()
letn=random();println(n);
Random floating point number between 0 and n (n not included)
letn=random(100);println(n);
Random floating point number between n1 and n2 (n2 not included)
letn=random(-100,100);println(n);
Random int between min and max (both included)
You can use eitherrandomInt
orrandomNumber
letn=randomInt(0,10);println(n);
Random char between chr1 and chr2 (both included)
function randomChar(chr1, chr2)
letchar=randomChar("A","Z");println(char);
Random element of an array
letar=["J","a","v","a","S","c","r","i","p","t"];letchar=random(ar);println(char);
Shuffle an array
letar=[1,2,3,4,5,6,7,8,9,10];letar2=ar.shuffle();println(ar2);
Modules
To better organize your code, especially in bigger programs, codeguppy.com introduces the concept of modules.
Instead of writing all the functions of a program in a single code page, you can split them into several code pages, each code page becoming in this way a module.
A module provides strong encapsulation for variables and functions defined inside. This encapsulation allows you to define functions / variables with same name in different modules.
To use the functions inside a module, you need first torequire
that module.
Main program
constmath=require("MathUtils");letsum=math.add(2,3);letprod=math.prod(3,4);println(sum);println(prod);
ModuleMathUtils
content
functionadd(a,b){returna+b;}functionprod(a,b){returna*b;}
Note: Another use for code pages is for defining game scenes.codeguppy.com has a built-in game scene manager. Please refer to the "Games" article for more details.
codeguppy.com is using thep5.js library at runtime. Advanced users can leverage almost the entire p5.js functionality. If you are familiar with p5.js, please checkcodeguppy for p5.js connoisseurs to see how to properly use it in your codeguppy.com programs.
This article is part of a series of mini-articles containing JavaScript coding hints applicable tocodeguppy.com environment.
Top comments(1)

Awesome...
For further actions, you may consider blocking this person and/orreporting abuse