The previous article in this series provided an overview of both JavaScript and Go, you should check that out here. This part will be talking about setting up both languages to run on our device, as well as comparing and contrasting some syntax, and operations.
Setup
A text editor or an Integrated Development Environment (IDE) is an integral part of the setup because it allows you to be able to write and run your codes locally on your device. The text editor I use is Visual Studio Code (VS Code). Feel free to use the text editor or IDE you are comfortable with.
Setting up JavaScript
Although JavaScript doesn't require an elaborate setup, in order to be able to run the JavaScript code from Vs Code, Node Js needs to be installed. Of all the super abilities of Node js, we will only use it to run JavaScript codes in the Vs Code terminal. If you don't have it installed already, click here to go to the official Node.js website and follow the installation instructions.
Setting up Go
In order to get Go running on your computer, it needs to be installed. You can find the relevant installation files at https://golang.org/dl/. Go codes will also be written inside of Vs Code and you will be prompted to install some additional packages whenever you attempt to run your first Go code, so keep that in mind. I recommend installing the Go extension for VS Code because it provides “rich go language support”.
Some things to note after creating your first Go file are:
All Go files are part of a package and you must always declare a package before your code runs successfully.
A Go program will not run without a main function. Program execution in Go starts from the main function therefore, a main function must always be declared.
You will be importing Go packages to access the Go features you need. The import keyword is used to bring in the packages. For instance:
package main
import “fmt” // used for single imports
func main(){}
On occasions when multiple Go packages are being imported, the import statement looks slightly different.
package main
import (
“fmt”
“os”
) // used for multiple imports
func main(){}
The import statement comes after the package declaration.
Comments
Comments in JS and Go are written the same way. Single-line comments are written with a double forward slash “//” while multi-line comments are written with an opening forward slash and asterisk “/*" and closed with an asterisk and forward slash “*/”.
// Single line comment in JavaScript and Go
/* Multi line
comment in
javascript and Go*/
Outputting To The Console/Terminal
Outputting In JavaScript
To output to the terminal in JavaScript we make use of the console object. There are a number of functions in the console object but the most commonly used one is the log function. For instance, to output “Hello, World” to the terminal in VS Code, create an hello.js file, and add the following command in our “hello.js” file:
console.log("Hello, World")
Now, open the terminal to run the code. The shortcut to bring up the terminal in vs code is "cmd + ~"
, you can also use the terminal option in VS Code's top menu, and click new terminal in the drop-down to add a new terminal. Now run this command in the terminal:
node hello.js
The output should be:
Outputting to the terminal in Go
To print “Hello, World” to the terminal in Go, create a “hello.go” file and add the following lines of code:
package main
import “fmt”
func main(){
fmt.Print(“Hello, World”)
}
And run this command in the terminal:
go run hello.go
This will output:
As mentioned earlier, the Go programme needs a main function to run. Having declared the package as main, the fmt package which contains functions for formatting text and printing to the console is imported. fmt.Print(“Hello World”)
is the command that prints to the console.
Another function from the fmt package that will let you print to the console is the Println function. The Println function adds a line break (\n)
at the end of the data.
To demonstrate Print and the Println functions:
package main
import “fmt”
func main(){
fmt.Print(“Printing Go World without a line break---”)
fmt.Println(“Printing Go World with a line break”)
}
Output:
By adding a line break "\n"
inside of a fmt.Print will make it function similarly to the Println function.
package main
import “fmt”
func main(){
fmt.Print(“Printing with a line break \n”)
fmt.Println(“Printing with a println”)
fmt.Print(“Another print”)
}
Output:
Also from the fmt package is the Printf. Printf lets you print formatted data. The function takes a template string that contains the text that needs to be formatted, plus some annotation/formatting verbs that tell the fmt functions how to format the trailing arguments.
package main
import “fmt”
func main(){
fmt.Printf(“Printing Hello, %v with %v specifiers. \n”, “World”, “Format”)
}
this should output:
Formatting verbs are preceded by the per cent symbol “%”, and you can specify the variable type, and format by using the assigned formatting verb and format. %v is a generic formatting verb that can be used for all variable types. Some others are:
%t for boolean,
%T (block letter T) prints the data type of the variable,
%f for floats,
%d for integers, etc.
When using multiple formatting verbs, the order of the variables should match the order of the formatting verbs. For instance:
package main
import “fmt”
func main(){
fmt.Printf("It is %t that %.1f of %d years is a %v ", true, 0.5, 20, "decade")
}
Quick note, in the above example, %.1f
formats the float to 1 decimal place.
You can read more on output and formatting verbs here (https://www.w3schools.com/go/go_formatting_verbs.php)
Variables and Constants
Declaring Variables and Constants in JavaScript:
In JavaScript, variables are created mostly using keywords; although you can create a variable without a keyword, it is best practice to create a variable with a keyword. The keywords are:
var
let
const (for constants)
A variable declaration often begins with any of these keywords, followed by the variable name. For instance var color; let age; const height
. The process of assigning a value to a declared variable is called initialisation.
JavaScript is a dynamically typed language, therefore we do not need to specify the data type of the value we are initialising because JavaScript will infer that for us, and the variable type can be changed later when the value changes, except in the case of a const, whose value cannot change once it is declared. For instance
var age = five;
age = 15; //variable type changes
const genre = “action”;
genre = “comedy” // will throw assignment to constant variable error.
JavaScript allows for multiple variables to be declared in one line of code like so:
var name= ”Daniel”, color= ”blue”, count=”2”;
console.log(name, color, count)
//output : Daniel, blue, 2
Declaring Variables and Constants in Go:
Go provides us with various ways to declare a variable with or without the var keyword. However, to declare a constant, the const keyword is always required.
To declare a variable in Go,
use the var or const keyword
followed by the variable name (which should be in block letters in the case of a const)
The variable data type //optional, type can be inferred
And assign it a value
For instance:
var petName string = “Jerry”
const NEWNAME = “Tom”
Go is a statically typed language, therefore the data type of both variables declared above cannot be changed later. If a different value is assigned to the petName variable for instance, it has to be of the same type string, otherwise, it would throw an error.
In order to declare a variable without the var keyword, the short variable assignment operator “:=” is required. example action := “dance”.
While this is shorter and more concise, it can only be used for variables inside a function i.e variables with a local scope. Declaring a variable with a global scope like this will throw an error. Also, Short variable assignments cannot be used to declare constants.
Go also allows for multiple variable declarations on one line. If the type is specified, all the variables have to be of the same type, otherwise, multiple variables of different types can be declared at once. For instance:
package main
func main (){
// with the type specified
var name, action, location string = “Drew”, “sings”, “shower”
// without a specified type
var name, rating, remark = “Drew”, 3, “good”
//using the short variable assignment operator
age, hasChild, status := 54, true, “qualified”
}
Operators
Operators in JavaScript and Go perform similar functions except in cases where an operator is present in JavaScript but not in Go and vice versa. JavaScript has operators like the ternary operator, the exponential operator, etc which Go does not currently have, and go has some bitwise assignment operators that JavaScript does not have. Besides this, most other operators present in both languages perform similar functions.
JavaScript being a dynamically typed language can compare both the types and values of operands using the “===”
or “!==”
operators. Go on the other hand does not have these operators being a statically typed language. VS Code will flag the error as soon as such a comparison is attempted in Go.
We will touch on four types of operators briefly, they are:
Arithmetic Operators
Assignment Operators
Logical Operators
Conditional Operators
Arithmetic Operators: perform common mathematical operations. The symbols "+, -, *, /, %, --, ++"
performs a similar role in both JavaScript and Go.
Assignment Operators: are used to assign values to variables. Common assignment operators are : "=, +=,-="
. These operators also perform similar roles in both JavaScript and Go.
Logical Operators: There are three logical operators, namely AND, OR, and NOT operators represented by the "&&, ||, !"
symbols respectively. They are used to evaluate expressions and return either true or false.
Comparison Operators: are used to check if the values of two variables are the same or different. The operators include "==, !=, <,>,<=,>="
and perform the same functions the both JavaScript and Go. As mentioned earlier, JavaScript has the "===, !=="
that are not present in Go because Go is statically typed.
We will be seeing and examining some if not all of these operators in subsequent articles in the series, for now though, we have examined setup and some basic syntax in both JavaScript and Go. Next up is Data type, see you then.