Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

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 oncodeguppy.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

letx;
Enter fullscreen modeExit fullscreen mode

Declare x and initialize it with a numerical value

letx=1;
Enter fullscreen modeExit fullscreen mode

Declare s and initialize it with a string

lets="Hello, World!";
Enter fullscreen modeExit fullscreen mode

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

Assign string "Hello" to variable s

s="Hello";
Enter fullscreen modeExit fullscreen mode

Assign an empty array to variable ar

ar=[];
Enter fullscreen modeExit fullscreen mode

Assign an array of 3 numbers to variable ar

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

Assign and array of 2 strings to variable ar

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

Assign an inline object to variable o

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

Variable sum is equal to a + b

sum=a+b;
Enter fullscreen modeExit fullscreen mode

Assign an expression to variable avg

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

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

sum=sum+10;
Enter fullscreen modeExit fullscreen mode

Variable i is increased (incremented) by 1

i++;
Enter fullscreen modeExit fullscreen mode

Variable i is incremented by 2

i+=2;
Enter fullscreen modeExit 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 modeExit fullscreen mode

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

if(hour<12){}else{}
Enter fullscreen modeExit 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, 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{}
Enter fullscreen modeExit fullscreen mode

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

Prints numbers from 10 down to 0 using a for loop

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

Prints even numbers from 0 to 100

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

Print all elements of an array

letar=[10,20,30];for(letelementofar){println(element);}
Enter fullscreen modeExit fullscreen mode

While loop

Print numbers from 0 to 9 using awhile loop

leti=0;while(i<10){println(i);i++;}
Enter fullscreen modeExit fullscreen mode

Do While

Print numbers from 0 to 10 using ado while loop

leti=0;do{println(i);i++;}while(i<10)
Enter fullscreen modeExit 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

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

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

Functions that return values

functionaddNumbers(x,y){returnx+y;}// Call a functionvarsum=addNumbers(100,200);println(sum);
Enter fullscreen modeExit fullscreen mode

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

Declaring and initializingar to an array of 3 numbers

letar=[10,20,30];
Enter fullscreen modeExit fullscreen mode

Length of an array

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

Append an element at the end of the array

letar=[10,20,30];ar.push(100);println(ar);
Enter fullscreen modeExit fullscreen mode

Insert an element at the beginning of an array

letar=[10,20,30];ar.unshift(1);println(ar);
Enter fullscreen modeExit fullscreen mode

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

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

Read the value of element2 of an array

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

Calculate the sum of elements of an array

letar=[10,20,30];letsum=0;for(letelementofar){sum+=element;}println(sum);
Enter fullscreen modeExit fullscreen mode

Assign a different value to al element of an array

letar=[10,20,30];ar[2]=100;println(ar);
Enter fullscreen modeExit fullscreen mode

Accesing the first element

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

Accessing the last element

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

Accessing the last element (easy way)

Note: Thepeek array method is present only in codeguppy.com

letar=[10,20,30];println(ar.peek());
Enter fullscreen modeExit fullscreen mode

Remove the first element of the array

letar=[10,20,30];ar.shift();println(ar);
Enter fullscreen modeExit fullscreen mode

Remove the last element of the array

letar=[10,20,30];ar.pop();println(ar);
Enter fullscreen modeExit fullscreen mode

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

Remove all elements of an array

letar=[10,20,30];// clear() is CodeGuppy specific// use ar.lenght = 0; outside CodeGuppyar.clear();println(ar);
Enter fullscreen modeExit fullscreen mode

Concatenate two arrays

// Merge / concatenate 2 arraysletar1=["a","b","c"];letar2=["d","e","f"];letar=ar1.concat(ar2);println(ar);
Enter fullscreen modeExit 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):

letar=["a","b","c","d","e","f"];// Extracting a 'slice' from an arrayletarSlice=ar.slice(2,4);println(arSlice);
Enter fullscreen modeExit fullscreen mode

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

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

Iterating all characters of a string

lettxt="JavaScript";for(letchroftxt){println(chr);}
Enter fullscreen modeExit fullscreen mode

Accessing string characters by position

lettxt="JavaScript";for(leti=0;i<txt.length;i++){println(txt[i]);}
Enter fullscreen modeExit fullscreen mode

Converting text to uppercase

lettxt="JavaScript";txt=txt.toUpperCase();println(txt);
Enter fullscreen modeExit fullscreen mode

Converting text to lowercase

lettxt="JavaScript";txt=txt.toLowerCase();println(txt);
Enter fullscreen modeExit fullscreen mode

Determine if the string contains another substring

lettxt="Coding is cool!";letsearch="cool";if(txt.includes(search)){println(search+" was found in"+txt);}
Enter fullscreen modeExit fullscreen mode

Determine if the string starts with a specified prefix

lettxt="JavaScript is cool!";letsearch="JavaScript";if(txt.startsWith(search)){println(txt+" starts with"+search);}
Enter fullscreen modeExit fullscreen mode

Determine if the string ends with a specified sufix

lettxt="JavaScript is cool!";letsearch="!";if(txt.endsWith(search)){println("It is an exclamation!");}
Enter fullscreen modeExit fullscreen mode

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

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

Extract a substring from the string

lettxt="JavaScript is cool!";letindex1=14;letindex2=18;lettxt2=txt.substring(index1,index2);println(txt2);
Enter fullscreen modeExit fullscreen mode

Remove whitespaces from beginning and end of the string

lettxt="    I love coding !";txt=txt.trim();println("'"+txt+"'");
Enter fullscreen modeExit fullscreen mode

Remove whitespaces from beginning of the string

lettxt="    I love coding !";txt=txt.trimStart();println("'"+txt+"'");
Enter fullscreen modeExit fullscreen mode

Remove whitespaces from the end of the string

lettxt="    I love coding !";txt=txt.trimEnd();println("'"+txt+"'");
Enter fullscreen modeExit fullscreen mode

Pads the start of the string with another string

letno=3;lettxt=no.toString(2).padStart(8,'0');println(txt);
Enter fullscreen modeExit fullscreen mode

Pads the end of the string with another string

letn1="1";letn2="3";txt=n1+"."+n2.padEnd(4,'0');println(txt);
Enter fullscreen modeExit fullscreen mode

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

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

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);
Enter fullscreen modeExit 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 asMath.random()

letn=random();println(n);
Enter fullscreen modeExit fullscreen mode

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

letn=random(100);println(n);
Enter fullscreen modeExit fullscreen mode

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

letn=random(-100,100);println(n);
Enter fullscreen modeExit fullscreen mode

Random int between min and max (both included)

You can use eitherrandomInt orrandomNumber

letn=randomInt(0,10);println(n);
Enter fullscreen modeExit fullscreen mode

Random char between chr1 and chr2 (both included)

function randomChar(chr1, chr2)

letchar=randomChar("A","Z");println(char);
Enter fullscreen modeExit fullscreen mode

Random element of an array

letar=["J","a","v","a","S","c","r","i","p","t"];letchar=random(ar);println(char);
Enter fullscreen modeExit fullscreen mode

Shuffle an array

letar=[1,2,3,4,5,6,7,8,9,10];letar2=ar.shuffle();println(ar2);
Enter fullscreen modeExit 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 torequire that module.

Main program

constmath=require("MathUtils");letsum=math.add(2,3);letprod=math.prod(3,4);println(sum);println(prod);
Enter fullscreen modeExit fullscreen mode

ModuleMathUtils content

functionadd(a,b){returna+b;}functionprod(a,b){returna*b;}
Enter fullscreen modeExit 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 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)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
jwokiri profile image
Joe Oketch
GIS => Python and Javascript.

Awesome...

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

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

Teaching coding to kids, teens and creative adults at https://codeguppy.com
  • Joined

More fromAdrian

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp