Nice syntax! - Popular languages' syntaxes compared

There are many different programming languages - everybody knows it. They are tools for developers for creating awesome software, but each tool is different and serves a different purpose. Programming languages vary in functionality, ecosystem, paradigms, goals, syntax and few other factors. In this post, I'd like to take a look at syntaxes of some popular/industry-leading programming languages. For this purpose, I'll compare trivia aspects that every language has ( e.g. variable declaration ) and standard Hello World! code. Also from this point on, every time I write language I mean programming language (obviously) 😉


aerial photo of pile of enclose trailer
Photo by chuttersnap / Unsplash

Popular / Industry-leading languages

Let's cover some basic information about languages we're going to cover.

C++

  • compiled
  • statically typing
  • multi-paradigm
  • multi-platform
  • 35 years old

C++ is one of the most used languages in the world. It's the go-to when you need performance and access to low-level features and optimizations. C++ syntax is influenced by the one of C and can feel a bit complex for some programmers (mainly because of how many features it gives access to). Basic code "lives" inside the main function. Semicolons are really important in C++ and cannot be omitted!

C#

  • compiled
  • strongly typed
  • for CLI platform
  • multi-paradigm
  • 18 years old

C# is a language developed by Microsoft for use in its .NET platform. Since its release, it has proven to be useful in many other ways. It's object-oriented and has syntax inspired by languages like Java and C/C++. The main logic is located inside a class's static main method which is placed inside a namespace. Semicolons cannot be omitted.

Java

  • compiled to byte code for Java VM
  • strongly typed
  • multi-platform/Java VM
  • multi-paradigm
  • 23 years old

Java gained a lot of popularity since its release. It's used to easily create multi-platform (especially Android) application and also powers a big part of Android OS. The main logic is placed in a class' main method. Semicolons cannot be omitted.

JavaScript

  • interpreted / JIT-compiled
  • dynamically typed
  • WWW and Node.js ( V8 ) "platform"
  • multi-paradigm
  • 22 years old

JavaScript is one of three languages that dominate today's WWW. With Node.js it can also be used for running as a backend and creating desktop and mobile apps. With its new releases, starting from ES6, it rapidly evolves, getting new features and more performance. Main logic doesn't have any predefined place and semicolons are optional.

Python

  • interpreted
  • dynamically typed
  • multi-platform
  • multi-paradigm
  • 28 years old

Python nowadays is known for its use in machine learning and AI. It features easy-to-learn syntax and emphasizes code readability. The main code doesn't require to be placed in any specific place ( just as in JS ). Semicolons are rarely used in python ( only to divide inline expression, which is not recommended in Python ) but indentation place a significant role.

Go

  • compiled
  • statically typed
  • multi-platform
  • multi-paradigm
  • 9 years old

Go is the youngest language on this list, not having even a full decade. It aims to provide a connection between ease of use of languages like Python and speed of compiled language, such as C. Design by Google to improve programming productivity. Main logic "lives" inside the main function of the main package, semicolons are auto-inserted in the compilation time, so they aren't a necessity.


white Hello LED sign
Photo by Adam Solomon / Unsplash

Hello World!

Hello World is one if not the most popular piece of code repeated across all languages. So, how to say "Hello" in any of the given above languages?

C++

#include <iostream>
using namespace std;

int main() {
   // Output "Hello World" to console
   cout << "Hello World";
   return 0;
}

C#

using System;

namespace HelloWorldApplication {
   class HelloWorld {
      static void Main(string[] args) {
         Console.WriteLine("Hello World");
         Console.ReadKey();
      }
   }
}

Java

public class HelloWorld {
   public static void main(String []args) {
      System.out.println("Hello World");
   }
}

JavaScript

console.log("Hello World")

Python

print "Hello World"

Go

package main

import "fmt"

func main() {
	fmt.Println("Hello World")
}

person typing on Apple keyboard
Photo by Ilya Pavlov / Unsplash

Type system

C++

C++ has vastly developed type system. It includes based types such as bool, char, int, float, double, void, etc. and multiple features for its extension like interfaces, namespaces, structs, and other types.

C#

C# type system is similar to one of C++. C# includes some types that are not defined in C++ like: object and dynamic. As an object-oriented language, it also contains advanced functionality for extension of its type system and other types, such as interfaces, namespaces, and enums.

Java

Java doesn't fall behind C++ and C# providing robust type system. As above there are basic types, interfaces etc. But the role of namespaces is fulfilled by Java packages.

JavaScript & Python

As JS and Python are dynamically typed languages, there's no type system to leverage in these languages.

Go

Go type system is very much similar to the one used in C and Java. The basic types are strict, bit-aware (e.g. uint8) and role of namespaces is fulfilled by packages just like in Java.


Colorful software or web code on a computer monitor
Photo by Markus Spiske / Unsplash

Comments

Comments are an important feature of every language. That's why their syntax should be simple, intuitive and fast to type. Maybe that's why in 5 of 6 languages that I'm taking a look here, the comment syntax is the same!

C++ / C# / Java / JavaScript / Go

// Single-line comment
/*
Multi-line comment
*/

The only language that has different comment syntax is Python. Python favors single-line comments although multi-line ones do exist:

Python

# Single-line comment
"""
Multi-line comment
"""

This difference comes mainly from the nature of Python as it's often used in REPL mode and encourages to just code without any prepared boilerplate.


turned on flat screen monitor
Photo by Pankaj Patel / Unsplash

Variable declaration

C++

Variables are no different in C++ than in any other language. For declaration precede variable by its type and follow by assignment operator or colon for either assignment or declaration of another variable. Of course, variable names are case-sensitive, can consist of basic letters, underscore and digits (not as the first character) and cannot use reserved keywords like types and etc.

int main() {
   int a, b;
   char _c = 'a';
   a = 1;
   b = 2;
   return 0;
}

C#

The basic syntax for declaring a variable is similar to C++. In fact, besides from some different type names, there's almost no difference at all!

namespace VariableDefinition {
   class Program {
      static void Main(string[] args) {
         short a;
         int b ;
         a = 10;
         b = 20;
         double c = a + b;
      }
   }
}

Java

Normal variables declarations in Java are just like in the other two languages above. Apart from that, in Java so-called instance and class variables are important too. These can be declared with the same syntax with the addition of access modifier at the beginning.

public class VariableDefinition {
   public int a = 10;
   public int b;
   public static void main(String args[]) {
      b = 20;
      int c = a + b;
   }
}

JavaScript

JS is a little different when it comes to defining a variable. As JS is dynamically typed, there's no need to provide the type information. So, the syntax is even easier just precede your variable's name with a keyword such as var or let - for variable or const - for constant ( let & const are recommended but supported only in ES6 and above ).

const a = 10;
let b, c;
b = 20;
c = a + b;

Python

If you like the simplicity of JS, then you're going to like Python too! There's no type definition and keyword usage whatsoever!

a = 10
b = 20
c = a + b

Go

With Go we're back to types... but not completely! Go provides so-called type inference so, when declaring a variable with value assign just right at the moment, you don't need to provide type info. You can also mix variable of different types into lists and assign them to a list of values to get type inference for all of them! Besides that, variables are declared using var keyword with preceding name and type after that. If you're using type inference, then you can omit var keyword and just use := symbol for assignment and that's all!

package main

func main() {
    var a, b = 10, 20; // can be used with different types
    var c int;
    c = a + b;
    d := c
}

turned on gray laptop computer
Photo by Luca Bravo / Unsplash

Function declaration

C++

In C++ a function can be declared with a simple syntax. Basically, you precede function name with return type and follow it by parenthesis with argument names preceded by their types and divided by colons inside. That's what's needed for the declaration, which needs to be placed before the main function. Then you can either repeat above steps after the main function and define your function's code there or continue with it right here and there. To define your function, after closing parenthesis inside curly brackets you put your code. I know, the code can demonstrate it a little bit better 😅:

int divide(int a, int b);

int main(){
    int a = 10, b = 2;
    int divided = divide(a, b);
    
    return 0;
}

int divide(int a, int b) {
    return a / b;
}

C#

As C# is an object-oriented language, there are no functions in it. Instead, there are methods which are defined inside given class. Basic syntax looks much like one used in C++, just with additional preceding modifiers.

namespace FunctionDefinition {

   class FuncDef {
   
      public int multiply(int a, int b) {
         return a * b;
      }
   }
   class Program {
      
      static void Main(string[] args) {
         int a = 10;
         int b = 20;
         FuncDef c = new FuncDef();
         int d = c.multiply(a, b);
      }
   }
}

Java

In Java, the same syntax rules as in C# applies, so nothing new.

public class FunctionDefinition {
   
   public static void main(String[] args) {
      int a = 10;
      int b = 20;
      int c = multiply(a, b);
   }

   public static int multiply(int a, int b) {
      return a * b; 
   }
}

JavaScript

JS has a bit different syntax or rather syntaxes. First, the standard way is normal function keyword followed by name and parenthesis with argument names inside after which comes curly brackets with function's code. The second way is a so-called function expression. In this form, everything above implies without a name following function keyword. Instead, its placed just like in a normal variable, which value is equal to declared function. In ES6 there's also new arrow function syntax. Keep in mind that all these constructs serve different purposes and have some custom behaviors, which I'm not talking here about, as it's just a bit off-topic.

function multiply(a, b){
    return a * b;
}
const divide = function(a, b){
    return a / b;
}
const add = (a, b) => {
    return a + b;
}
const a = 10;
const b = 20;
const c = multiply(a, b);
const d = divide(b, a);
const e = add(a, b);

Python

Like any other part of Python's syntax, function definitions are also really simple. You define your function using the def keyword, followed by name of your function and list of arguments inside the parenthesis. This ends with : symbol. Then you start your function's code in new line with correct 4 space indention.

def multiply(a, b):
    return a * b
a = 10
b = 20
c = multiply(a, b)

Go

Go provides its own different syntax for declaring functions. You start with func keyword followed by function's name and parenthesis in which you specify arguments just like variables without var keyword. After that comes the return type and curly brackets with your code inside.

package main

func divide(a, b int) int {
    return a * b
}
func main() {
    var a, b = 10, 20
    var c = divide(b,a)
}

spiral concrete staircase
Photo by Tine Ivanič / Unsplash

Loops

C++

C++ provides us with 3 types of loops which is kind-of standard in many languages. These are while loop, do... while loop and for loop. I'll focus on the for loop here. You declare that loop by the keyword for followed by parenthesis in which you put (in given order):

  • Loop variables declarations (init step)
  • Loop condition
  • Step after loop's code execution

All of these steps are separated by a semicolon.

#include <iostream>
using namespace std;
 
int main () {
   int whileVar = 0;
   int doWhileVar = 0;
   
   for( int forVar = 0; forVar < 5; forVar++ ) {
      cout << "For loop value: " << forVar << endl;
   }
   
   while(whileVar < 5) {
       cout << "While loop value: " << whileVar << endl;
       whileVar++;
   }
   
   do {
       cout << "Do... while loop value: " << doWhileVar << endl;
       doWhileVar++;
   } 
   while( doWhileVar < 5 );
 
   return 0;
}

C#

In C# there's no difference in loops syntaxes from C++. Also, C# provides the same loops as C++ - no more no less than 3.

using System;

namespace Loops {
   class Program {
      static void Main(string[] args) {
         int whileVar = 0;
         int doWhileVar = 0;
         
         for (int forVar = 0; forVar < 5; forVar++) {
            Console.WriteLine("For loop value: {0}", forVar);
         }
         
         while (whileVar < 5) {
            Console.WriteLine("While loop value: {0}", whileVar);
            whileVar++;
         }
         
         do {
            Console.WriteLine("Do... while loop value: {0}", doWhileVar);
            doWhileVar++;
         } 
         while (doWhileVar < 5);
         
         Console.ReadLine();
      }
   }
} 

Java

In Java - the same applies.

public class Loop {

   public static void main(String args[]) {
      int whileVar = 0;
      int doWhileVar = 0;

      for(int forVar = 0; forVar < 5; forVar++) {
         System.out.print("For loop value: " + forVar );
         System.out.print("\n");
      }
      
      while( whileVar < 5 ) {
         System.out.print("While loop value: " + whileVar );
         whileVar++;
         System.out.print("\n");
      }
      
      do {
         System.out.print("Do... while loop value: " + doWhileVar );
         doWhileVar++;
         System.out.print("\n");
      }while( doWhileVar < 5 );
   }
}

JavaScript

In JS - again, the same. Besides the way of declaring variables, nothing changes and... that's totally fine. That fact alone makes learning multiple languages simpler - because of similarities in syntaxes. JavaScript aside from standard loops ( for, while, do... while ) provides the programmer with constructs such as for... in and for... of to iteration over arrays, but these aren't covered here.

var whileVar = 0;
var doWhileVar = 0;

for(var forVar = 0; forVar < 5; forVar++) {
    console.log(`For loop value: ${forVar}`);
}

while (whileVar < 5) {
    console.log(`While loop value: ${whileVar}`);
    whileVar++;
}

do {
  console.log(doWhileVar);
  doWhileVar++;
} while (doWhileVar < 5);

Python

Python is were thing starts to get interesting again. 😄 Here we're limited to for ( or rather for... in ) and while loops only. The while loop can be used for standard loop, but for loop is meant to be used for iterating over items of different sequences. So, while loop consists of while keyword followed by parenthesis with condition inside. It all ends with : symbol and then ( in a new line ) follows loop code with 4 space indentation. For loop, on the other hand, starts with for keyword followed by the name chosen for currently iterated sequence's item. After that comes the in keyword with following static value or variable of a sequence ( string or array ). Everything ends ( naturally for Python ) with : symbol and code on a new line with 4 space indentation.

whileVar = 0
while (whileVar < 5):
   print 'While loop value: ', whileVar
   whileVar += 1

digits = [0,1,2,3,4]

for digit in digits:
   print 'For loop value: ', digit

Go

Now, Go goes extreme and leaves us with one loop only! But men, this loop is powerful! With this one construct, you can iterate using condition, usual for loop syntax and any range of values. So, because code means thousands of words, here we go!

package main

import "fmt"

func main() {
   var forCond = 0
   numbers := [5]int{0,0,0,0,0} // That's array decleration BTW 

   for forStd := 0; forStd < 5; forStd++ {
      fmt.Printf("Standard for loop value: %d\n", forStd)
   }
   for forCond < 5 {
      fmt.Printf("Conditional for loop value: %d\n", forCond)
      forCond++
   }
   
   for item := range numbers {
      fmt.Printf("For in sequence value: %d\n", item)
   }   
}

Brief summary

Well, it's been quite a ride don't you think? 😂 Even if there has been only a small description, variables, functions, and loops, but I think that's enough. It isn't the purpose of this article to teach anyone 6 different languages at once ( but you can at least write Hello World ) - it would be crazy! The main goal was to showcase how many similarities nowadays most popular languages share. As you can notice there are quite many! So, don't be scared to learn new languages when you already know one - it's not that hard. Of course, real ride starts when you enter to world of advanced features - these are different for almost every language.

So, how was this article? Would you like to see something similar for modern languages, which has different syntaxes? Or maybe for functional languages? Let me know what you think in the comments below. Also, share it if you want to. 👍