DEV Community

Matt Gahrns
Matt Gahrns

Posted on

Strongly vs Weakly Typed Languages

The Compiler

The compiler is something that strongly typed languages use. Basically, before it allows the code to run, it "compiles" it to check for errors. If any errors are found it won't allow the code to run and you as the developer must fix it. What it is also doing is translating your code from a high level language to machine language that the computer can actually read and execute.

Variable Declaration

When declaring variables in a strongly typed language the developer must specify which type of variable is being declared. For example declaring an integer in Java looks like this:

int i = 5;

and in JavaScript:

let i = 5;

Functions

In strongly typed languages when declaring functions, the developer must also declare if the function will return a something and if so which type of variable it will return. For example if we wanted to declare a function in Java that simply prints "Hello world!" we would declare:

public void helloWorld(){
  System.out.print.ln("Hello world!");
}

The 'void' keyword is letting the compiler know that we are not returning anything with this function. If we wanted to instead return the string "Hello world!" we would declare:

public String helloWorld(){
  return "Hello world!";
}

Now we are letting the compiler know that we want to return a String object. If we did not have a line with the key word 'return' in our function the compiler would throw an error telling us that our 'helloWorld()' function must return a type of String. Hand in hand if we tried to return a variable of any other type than a String we would get a similar error saying that the return value of 'helloWorld()' is not of type String.

Sticking to the same comparison language, all of the following functions would be completely valid in JavaScript:

function helloWorld(){
  console.log("Hello world!");
}

function helloWorld2(){
  console.log("Hello world!");
  return 5;
}

function helloWorld3(){
  return "Hello world!";
}

As we can see there's no need to specifically declare whether or not our functions are returning anything or not. We can console log, return a string, or return an integer all while following the same function declaration format.

Thanks for reading!

Top comments (0)