Mark As Completed Discussion

Static vs Dynamic

Every programming language has data-types. One reason for this is so computers know what operations can be performed on them.

Imagine we're writing a function that will take two inputs; subtracting one from the other.

JAVASCRIPT
1subtract(input1, input2) {
2	input1 - input2    
3}

Note I said inputs, instead of numbers. Technically, we could pass anything through to this function

JAVASCRIPT
1subtract(5,3) // 2
2subtract(19,40) // -21
3subtract(9,3) // 6
4
5subtract("hello","world") // wait, what?!!

What is "hello" - "world" ? No idea? Why not? Because they are both strings, and it doesn't make any sense. Exactly!

Computers won't be able to understand this either, so we need a way of checking to see if we've made any of these mistakes.

This can be done using either Static Typing or Dynamic Typing.

A statically typed language will check for these errors before run-time and, if any are found, it will report the problem and will usually prevent the application from running, until the issues have been fixed.

A dynamically typed language will check for these errors on the fly, during execution. Your application could run without ever having a problem, or it could suddenly crash, possibly after days if there is an unexpected error.

Let's look at an example. The following is the start of our application; we've declared two functions, one with the same subtraction error we discussed earlier, and the other with a completely valid subtraction.

JAVASCRIPT
1subtractionWithError() {
2    "hello" - "world"
3}
4
5validSubtraction() {
6 	9 - 4   
7}
8
9validSubtraction()

Note how only the validSubtraction function is executed.

If you were using a statically typed language, an error would be shown before the application runs.

If you were using a dynamically typed language, an error would never be thrown because the code with the error ( subtractionWithError ) will never be executed, and your application would continue to run without any idea there's an error.

What if our code called the validSubtraction function, waited for 4 hours, and then called the subtractionWithError function?

JAVASCRIPT
1subtractionWithError() {
2    "hello" - "world"
3}
4
5validSubtraction() {
6 	9 - 4   
7}
8
9validSubtraction()
10
11wait(4 hours) // wait for 4 hours before continuing
12
13subtractionWithError()

If you were using a statically typed language, the behaviour would be exactly the same. An error would be shown before the application runs because, executed or not, it knows there's an error.

If you were using a dynamically typed language your application would run fine for the first 4 hours but, as soon as the subtractionWithError function is executed, it would then show an error and possibly crash (depending on what the problem is).