Coding hints I: JavaScript Syntax

This article contains coding hints and mini examples about JavaScript. You may find them helpful during your JavaScript language exploration on codeguppy.com.

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

let x;

Declare x and initialize it with a numerical value

let x = 1;

Declare s and initialize it with a string

let s = "Hello, World!";

Assigning values to variables

Once a variable has been declared with let 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, the else if is used to test another condition, and if is true, the block of that else if is executed.

The block after the last else is executed only if no other condition was true until that point.

if (minute <= 15)
{
}
else if(minute <= 30)
{
}
else
{
}

Note: You can have multiple else if blocks in this kind of experessions.

for loop

Prints numbers from 0 to 4 using a for loop and println

for(let i = 0; i < 5; i++)
{
	println(i);
}

Prints numbers from 10 down to 0 using a for loop

for(let i = 10; i >= 0; i--)
{
	println(i);
}

Prints even numbers from 0 to 100

for(let i = 0; i <= 100; i+=2)
{
	println(i);
}

let ar = [10, 20, 30];

for(let element of ar)
{
	println(element);
}

while loop

let i = 0;

while(i < 10)
{
	println(i);
	i++;
}

do while

let i = 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

A switch statement is another instruction besides if / 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 any case value.

Usually switch is used less often than if / else if / else.

switch(myExpresion)
{
	case 100:
		//...
		break;
	case 200:
		//...
		break;
	case 300:
		//...
		break;
	default:
		//...
}

Functions

Functions are great for creating new language instructions 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 function balloon

// 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 balloon
function balloon(x, y, shapeColor)
{
    let r = 30;
    let stringLen = 100;
    
    fill(shapeColor);
    stroke(shapeColor);
    
    circle(x, y, r);
    line(x, y + r, x, y + r + stringLen);
}

// Call function balloon with different parameters
balloon(100, 100, "red");
balloon(300, 300, "blue");
balloon(500, 200, "yellow");

Functions that return values

function addNumbers(x, y)
{
	return x + y;
}

// Call a function
var sum = addNumbers(100, 200);
println(sum);

Note: codeguppy.com includes a big number of built-in functions such as circle, 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 initializing ar to an empty array

let ar = [];

Declaring and initializing ar to an array of 3 numbers

let ar = [10, 20, 30];

Length of an array

let ar = [10, 20, 30];
println("Length of array: ", ar.length); 

Append an element at the end of the array

let ar = [10, 20, 30];
ar.push(100);

println(ar);

Insert an element at the beginning of an array

let ar = [10, 20, 30];
ar.unshift(1);

println(ar);

Insert an element at an arbitrary position

let ar = [10, 20, 30];

// 1 -> after element with potion 1
// 0 -> delete 0 elements
// 15 -> insert number 15
ar.splice(1, 0, 15);

println(ar);

Insert an element at an arbitrary position (easy mode)

Note: The insert array method is present only in codeguppy.com

let ar = [10, 20, 30];
ar.insert(1, 17);

println(ar);

Read the value of element 2 of an array

let ar = [10, 20, 30];
println(ar[2]);

Calculate the sum of elements of an array

let ar = [10, 20, 30];
let sum = 0;

for(let element of ar)
{
	sum += element;
}

println(sum);

Assign a different value to al element of an array

let ar = [10, 20, 30];
ar[2] = 100;

println(ar); 

Accesing the first element

let ar = [10, 20, 30];
println(ar[0]);

Accessing the last element

let ar = [10, 20, 30];
let len = ar.length;
println(ar[len - 1]); 

Accessing the last element (easy way)

Note: The peek array method is present only in codeguppy.com

let ar = [10, 20, 30];
println(ar.peek()); 

Remove the first element of the array

let ar = [10, 20, 30];
ar.shift();

println(ar);

Remove the last element of the array

let ar = [10, 20, 30];
ar.pop();

println(ar);

Remove an element at an arbitrary position

let ar = [10, 20, 30];

// 0 -> element index
// 1 -> number of elements to remove
ar.splice(0, 1);

println(ar);

Remove all elements of an array

let ar = [10, 20, 30];

// clear() is CodeGuppy specific
// use ar.lenght = 0; outside CodeGuppy
ar.clear();

println(ar);

Concatenate two arrays

// Merge / concatenate 2 arrays
let ar1 = ["a", "b", "c"];
let ar2 = ["d", "e", "f"];

let ar = 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):

let ar = ["a", "b", "c", "d", "e", "f"];

// Extracting a 'slice' from an array
let arSlice = ar.slice(2, 4);
println(arSlice);

Joining elements of an array

let ar = ["a", "b", "c", "d", "e", "f"];

// Join all elements in a string using separator ;
let s = ar.join(";");
println(s);

String methods

Just like with arrays, you can access and manipulate independent characters within a string.

Length of a string

let txt = "JavaScript";
println(txt.length);

Iterating all characters of a string

let txt = "JavaScript";

for(let chr of txt)
{
    println(chr);
}

Accessing string characters by position

let txt = "JavaScript";

for(let i = 0; i < txt.length; i++)
{
    println(txt[i]);
}

Converting text to uppercase

let txt = "JavaScript";

txt = txt.toUpperCase();
println(txt);

Converting text to lowercase

let txt = "JavaScript";

txt = txt.toLowerCase();
println(txt);

Determine if the string contains another substring

let txt = "Coding is cool!";
let search = "cool";

if (txt.includes(search))
{
	println(search + " was found in " + txt);
}

Determine if the string starts with a specified prefix

let txt = "JavaScript is cool!";
let search = "JavaScript";

if (txt.startsWith(search))
{
	println(txt + " starts with " + search);
}

Determine if the string ends with a specified sufix

let txt = "JavaScript is cool!";
let search = "!";

if (txt.endsWith(search))
{
	println("It is an exclamation!");
}

Find the position of a substring. Search starts at the beginning

let txt = "JavaScript is cool!";
let search = "cool";

let foundAt = txt.indexOf(search);

if (foundAt < 0)
	println("Not found!");

else
	println("Found at position " + foundAt);

Find the position of a substring. Search starts at specified index.

let txt = "JavaScript is cool! Super cool!";

let search = "cool";
let startAt = 18;

let foundAt = txt.indexOf(search, startAt);

if (foundAt < 0)
	println("Not found!");

else
	println("Found at position " + foundAt);

Extract a substring from the string

let txt = "JavaScript is cool!";

let index1 = 14;
let index2 = 18;

let txt2 = txt.substring(index1, index2);

println(txt2);

Remove whitespaces from beginning and end of the string

let txt = "    I love coding !    ";

txt = txt.trim();
println("'" + txt + "'");

Remove whitespaces from beginning of the string

let txt = "    I love coding !    ";

txt = txt.trimStart();
println("'" + txt + "'");

Remove whitespaces from the end of the string

let txt = "    I love coding !    ";

txt = txt.trimEnd();
println("'" + txt + "'");

Pads the start of the string with another string

let no = 3;

let txt = no.toString(2).padStart(8, '0');
println(txt);

Pads the end of the string with another string

let n1 = "1";
let n2 = "3";

txt = n1 + "." + n2.padEnd(4, '0');
println(txt);

Codes of characters

let txt = "JavaScript";

for(let chr of txt)
{
    // Obtain the Unicode code point value
    // ... identical to ASCII code for the range of ASCII values
    let code = chr.codePointAt(0);

    let line = chr + "\t" + code.toString() + "\t" + code.toString(16).toUpperCase() + "\t" + code.toString(2).padStart(7, "0");

    println(line);
}

Characters from codes

let msg = "73 32 76 79 86 69 32 67 79 68 73 78 71"
let base = 10;

let arMsg = msg.split(" ");

for(let i = 0; i < arMsg.length; i++)
{
    if (!arMsg[i])
        continue;
    
    let code = 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)
    let chr = String.fromCodePoint(code);
    
    println(chr);
}

Random numbers

Random numbers are extremly useful in coding.

To obtain a random number in JavaScript between 0 (inclusive) and 1 (exclusive) you can use Math.random() function.

let r = 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 as Math.random()

let n = random();
println(n);

Random floating point number between 0 and n (n not included)

let n = random(100);
println(n);

Random floating point number between n1 and n2 (n2 not included)

let n = random(-100, 100);
println(n);

Random int between min and max (both included)

You can use either randomInt or randomNumber

let n = randomInt(0, 10);
println(n);

Random char between chr1 and chr2 (both included)

function randomChar(chr1, chr2)

let char = randomChar("A", "Z");
println(char);

Random element of an array

let ar = ["J", "a", "v", "a", "S", "c", "r", "i", "p", "t"];

let char = random(ar);
println(char);

Shuffle an array

let ar = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let ar2 = 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 to require that module.

Main program

const math = require("MathUtils");

let sum = math.add(2, 3);
let prod = math.prod(3, 4);

println(sum);
println(prod);

Module MathUtils content

function add(a, b)
{
	return a + b;
}

function prod(a, b)
{
	return a * 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 Game Development article for more details.


This article is part of a series of mini-articles containing JavaScript coding hints applicable to codeguppy.com environment:

Read more blog articles Browse JavaScript projects

About codeguppy

CodeGuppy is a FREE coding platform for schools and intependent learners. If you don't have yet an account with codeguppy.com, you can start by visiting the registration page and sign-up for a free account. Registered users can access tons of fun projects!


Follow @codeguppy on Twitter for coding tips and news about codeguppy platform. For more information, please feel free to contact us.