DEV Community

Cover image for Coding Hints. Part I: JavaScript syntax
Adrian
Adrian

Posted on

Coding Hints. Part 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.

Alt Text

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;
Enter fullscreen mode Exit fullscreen mode

Declare x and initialize it with a numerical value

let x = 1;
Enter fullscreen mode Exit fullscreen mode

Declare s and initialize it with a string

let s = "Hello, World!";
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

Assign string "Hello" to variable s

s = "Hello";
Enter fullscreen mode Exit fullscreen mode

Assign an empty array to variable ar

ar = [];
Enter fullscreen mode Exit fullscreen mode

Assign an array of 3 numbers to variable ar

ar = [1, 2, 3];
Enter fullscreen mode Exit fullscreen mode

Assign and array of 2 strings to variable ar

ar = ["A", "B"];
Enter fullscreen mode Exit fullscreen mode

Assign an inline object to variable o

o = {   Type: 'car', 
        x : 100, 
        y : 200 
    };
Enter fullscreen mode Exit fullscreen mode

Variable sum is equal to a + b

sum = a + b;
Enter fullscreen mode Exit fullscreen mode

Assign an expression to variable avg

avg = (a + b) / 2;
Enter fullscreen mode Exit fullscreen mode

Variable sum is increased by 10 (the new sum becomes the older sum + 10)

sum = sum + 10;
Enter fullscreen mode Exit fullscreen mode

Variable i is increased (incremented) by 1

i++;
Enter fullscreen mode Exit fullscreen mode

Variable i is incremented by 2

i += 2;
Enter fullscreen mode Exit fullscreen mode

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)
{

}
Enter fullscreen mode Exit fullscreen mode

Executes the first block of instructions if condition is true, otherwise the second block

if (hour < 12)
{

}
else
{

}
Enter fullscreen mode Exit fullscreen mode

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
{
}
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

Prints numbers from 10 down to 0 using a for loop

for(let i = 10; i >= 0; i--)
{
    println(i);
}
Enter fullscreen mode Exit fullscreen mode

Prints even numbers from 0 to 100

for(let i = 0; i <= 100; i+=2)
{
    println(i);
}
Enter fullscreen mode Exit fullscreen mode

Print all elements of an array

let ar = [10, 20, 30];

for(let element of ar)
{
    println(element);
}
Enter fullscreen mode Exit fullscreen mode

While loop

Print numbers from 0 to 9 using a while loop

let i = 0;

while(i < 10)
{
    println(i);
    i++;
}
Enter fullscreen mode Exit fullscreen mode

Do While

Print numbers from 0 to 10 using a do while loop

let i = 0;

do
{
    println(i);
    i++;
}
while(i < 10)
Enter fullscreen mode Exit fullscreen mode

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:
        //...
}
Enter fullscreen mode Exit fullscreen mode

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");
Enter fullscreen mode Exit fullscreen mode

Functions that return values

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

// Call a function
var sum = addNumbers(100, 200);
println(sum);
Enter fullscreen mode Exit fullscreen mode

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 = [];
Enter fullscreen mode Exit fullscreen mode

Declaring and initializing ar to an array of 3 numbers

let ar = [10, 20, 30];
Enter fullscreen mode Exit fullscreen mode

Length of an array

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

Append an element at the end of the array

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

println(ar);
Enter fullscreen mode Exit fullscreen mode

Insert an element at the beginning of an array

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

println(ar);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

Read the value of element 2 of an array

let ar = [10, 20, 30];
println(ar[2]);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

Assign a different value to al element of an array

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

println(ar); 
Enter fullscreen mode Exit fullscreen mode

Accesing the first element

let ar = [10, 20, 30];
println(ar[0]);
Enter fullscreen mode Exit fullscreen mode

Accessing the last element

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

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()); 
Enter fullscreen mode Exit fullscreen mode

Remove the first element of the array

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

println(ar);
Enter fullscreen mode Exit fullscreen mode

Remove the last element of the array

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

println(ar);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

Concatenate two arrays

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

let ar = ar1.concat(ar2);
println(ar);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

Iterating all characters of a string

let txt = "JavaScript";

for(let chr of txt)
{
    println(chr);
}
Enter fullscreen mode Exit fullscreen mode

Accessing string characters by position

let txt = "JavaScript";

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

Converting text to uppercase

let txt = "JavaScript";

txt = txt.toUpperCase();
println(txt);
Enter fullscreen mode Exit fullscreen mode

Converting text to lowercase

let txt = "JavaScript";

txt = txt.toLowerCase();
println(txt);
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

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!");
}
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

Remove whitespaces from beginning and end of the string

let txt = "    I love coding !    ";

txt = txt.trim();
println("'" + txt + "'");
Enter fullscreen mode Exit fullscreen mode

Remove whitespaces from beginning of the string

let txt = "    I love coding !    ";

txt = txt.trimStart();
println("'" + txt + "'");
Enter fullscreen mode Exit fullscreen mode

Remove whitespaces from the end of the string

let txt = "    I love coding !    ";

txt = txt.trimEnd();
println("'" + txt + "'");
Enter fullscreen mode Exit fullscreen mode

Pads the start of the string with another string

let no = 3;

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

Pads the end of the string with another string

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

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

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);
}
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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

let n = random(100);
println(n);
Enter fullscreen mode Exit fullscreen mode

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

let n = random(-100, 100);
println(n);
Enter fullscreen mode Exit fullscreen mode

Random int between min and max (both included)

You can use either randomInt or randomNumber

let n = randomInt(0, 10);
println(n);
Enter fullscreen mode Exit fullscreen mode

Random char between chr1 and chr2 (both included)

function randomChar(chr1, chr2)

let char = randomChar("A", "Z");
println(char);
Enter fullscreen mode Exit fullscreen mode

Random element of an array

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

let char = random(ar);
println(char);
Enter fullscreen mode Exit fullscreen mode

Shuffle an array

let ar = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let ar2 = ar.shuffle();

println(ar2);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

Module MathUtils content

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

function prod(a, b)
{
    return a * b;
}
Enter fullscreen mode Exit fullscreen mode

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 the p5.js library at runtime. Advanced users can leverage almost the entire p5.js functionality. If you are familiar with p5.js, please check codeguppy 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 to codeguppy.com environment.

Latest comments (1)

Collapse
 
jwokiri profile image
Joe Oketch

Awesome...