JavaScript vs object-orientated languages: Java and C#
Tags: javascript, java, csharp, oop
Published: 2021-03-16 09:40:43

Java is the first programming language I learned, and something I often used to hear about JavaScript was something akin to:

> JavaScript is a simpler Java that is interpreted instead of compiled and is used mostly for web development.

Looking at the syntax it looks similar enough, but “under the hood” there seem to be some core distinctions.

JavaScript is often seen as just something you need to learn along with HTML and CSS for web development, but it used to be less looked over as a powerful language in itself.

I can see the way JavaScript is used is very different from Java (and C#). Java and C# take on the object-orientated way of doing things in a fixed way, however, in JavaScript, this object-orientated style of programming is much more optional.

Whatever the case I thought I would write an article looking at JavaScript and its syntax for those who are more used to stricter object-orientated languages like Java and C#. I am including C# since I have been learning that and I found it so similar to Java.

I will go through some very short sections noting some idiosyncrasies of JavaScript. I would have appreciated these things pointed out to me at the beginning hence that is the inspiration of this short article.

#Arrays are…?

Arrays in C# and Java are fixed by type and length. For example:

```Java
int[] arr = new int[5];
```

Here we can only populate with integers.

However, in JavaScript, they can be anything.

e.g.

```Javascript
let arr = [5,”Hello”, false, 5.1, true];
```

Fair enough, but there are other interesting things…

Check this out.

* Java

```Java
arr.length();
```

Will be 5.

* JavaScript

```Javascript
arr.Length();
```

Will be 5.

Now let's try this ( still in JavaScript):

```Javascript
arr.foo = “bar”;
arr.Length();
```

Length still 5.

???

JavaScript arrays are like specialized "objects". Each element in the “array” has a key (0 through to n). The length attribute will only be changed according to these specific key-value pairs (0 through to n), not any others that are added… This brings us to JavaScript "objects" something that perhaps should have been mentioned before...

# "Objects"

JavaScript objects are basically key-value pairs... In some ways, they remind me of the Hashmap of Java or the Dictionary of C#. This is why I have written "Objects" and not objects as the title of this section.

Java/C# objects can be thought of like so: instantiations of any class that has a constructor.

For instance, String in Java, is an object. It is an instantiation of the String class. In this example, the String, has a property (i.e. a text value) and various functions(methods) that come as part of that object.

Java and C# are obviously more object-orientated in their design, JavaScript less so, although one can program in an object-orientated way if one desires.

When people talk of objects in JavaScript they may give a simple example like so:

```Javascript
var car = {type:"Fiat", model:"500", color:"white"};
```

There we have key-value pairs, which we are calling an “object”.

Now a key can have a function as a value, and hence it has the flexibility of an object, having the properties and methods (functions) that a Java/C# class/object has.

# Var and let – pick a lane will you?!

`var` and `let` are two ways of declaring variables in JavaScript. Let us explore...

If you type in `a` for instance:

```Javascript
a = 1;
```

And `a` isn’t already defined, JavaScript will simply interpret that as:

```Javascript
var a = 1;
```

So `var` is like the default of JavaScript.

Now if you type again:

```Javascript
var a = 2;
```

JavaScript would essentially over-ride `a` and `a` would become 2.

This could not work for let. If you tried to run:

```Javascript
let a = 1;
let a = 2;
```
There would be an error saying something like "variable a is already declared", just as you would expect in Java/C#.

Also if you try to declare a `var a` if you have already declared `let a` there would be an issue… `a` is taken. `let` is block-scoped, `var` is functionally scoped.

`let` acts like the variables in Java or C#, `var` on the other hand does not.

This is because we can run:

```Javascript
var a=1;
var a=2;
var c=3;
```
And there would be no problem. The `var` can over-ride each other, whereas the `let` ( and the `const` which we will come to later) kind of spread out and occupy the code-block.

I imagine `var` like a pile. If you place a new `var` on-top of the pile it overrides the others.

`let` will act like a Java/C# variable.

Consider the useless JavaScript code below, to show how block-scoping works in `let` (and `const`) which is exactly the same way it works in Java/C#:

```Javascript
{
  let a=1;
  // a === 1
  {
    let a=2; 
    // a === 2
    {
      let a = 3;
      // a === 3
        {
          // a === 3
        }
    }
  }
}
// a === undefined
```
# Const – is it really constant?

Something universal amongst the languages we are comparing today is the constant. In Java, this is using the `final` modifier before a variable.

e.g.

```Java
final int i = 1;
```

So I see `const` used a lot in JavaScript hence this deserved this own section, even though const is not actually that much different from how it is used in Java.

Semantically, the confusing thing with `const` (short for constant) is that in some ways it does appear to change. What cannot change is the thing it points to. What can change is the thing itself.

So a constant of primitive types such as integers, or booleans will not change.

e.g.

```Javascript
const aBool = true;
```

However, we can put a boolean in an array ( or object ):

```Javascript
const  aBool = [true];
```
We can then change it as much as we like:

```Javascript
aBool.pop();
aBool.push(false);
```
OR

```Javascript
aBool[0] = false;
```

(aBool now evaluates to [false])

We could do the same with an object.

```Javascript
const myBool = {value: true};
myBool.value = false;
```

Whenever we see `const`, we must not literally think “constant” in the usual way, but just think of the pointer being constant!

In JavaScript code, we see `const` used far more often than in Java. This may be because Java is written in a far more object-orientated way and variables can often not be changed as easily due to the principle of encapsulation. JavaScript folk on the other hand appear to rely far more on `const` instead of always choosing to use `let`.

I found this unusual since coming from Java you tend not to see “final” done as much.

Usually, people use it for things like mathematical constants. etc… 

I see `const` used a lot for functions, which for those who use Java is an odd thing in itself…

So think of it like this. The thing `const` points to is constant, but the state of that thing isn’t! However, this is actually the same for Java. The internal state of an object that is assigned to a final variable can change, but the object itself will always be that object.

However, in Java, things are more predictable. Yes, array values can be changed, however, the length of the arrays, nor the type of the elements in them will not. The same with objects, the “properties” within the objects will stay the same also, you can’t add any new variables of methods(functions). Not so with JavaScript, hence the `const` is that much more versatile and used more often.

Also, in Java it is an extra modifier that needs to be used “final”, perhaps that puts people off using it more often too!

# Fat arrow functions

OK, so you can get “fat arrow” functions in Java and C# but they are seen a LOT less than in JavaScript, and they are far less core and versatile in Java/C#.

Let us so let’s look into them.  In C# these are “lambda expressions” and you see them done ( for instance) when using the LINQ library. However, in JavaScript, you could write everything with fat arrow functions and never write a single function in the "standard" way if you wanted.

Example “normal” JavaScript function.

```Javascript
function greetPerson(name, question)
{
	return “Hello, ”+name+ “ “+question;
}
```

This looks a lot like a method ( AKA function ) we are used to in Java/C#.

The same thing as a far arrow function could be:

```Javascript
const myFunction =  () =>(“Hello, ”+name+ “ “+question);
```

Have you ever assigned a function to a variable in Java or C#?  I haven’t… However think about it, the const variable is just a reference to the function ( i.e. the name) so it does the same thing...

Fat arrow functions have what is called “implicit return” so they are expected to return something, so can make for good shorthand.

Personally though in a lot of situations I like my wordy "lego-block" style code full of curly braces a lot of times...

# Call-back functions

In JavaScript, you will come across callback functions over and over… Here is an example:

```Javascript
// declare a function
function greet(greeting = “hello”)
{
  return greeting;
}
```

Then we could run:

```Javascript
const f1 = greet;
const f2 = greet();
```

Now, `f1` will be a reference to the function `greet`. `f2` will actually be the string value “hello”.

`f1` is a call-back function. So to call it, we must go `f1.greet()` or `f1.greet(myParam)`.

In `f2` on the other hand, the function has already been called ( which will only happen once) and the returned result (a primitive string in this case) is stored within.

This may sound basic but it can trip people up including myself up at times.

Also, we can come back here to our fat-arrow functions and see their use here.

```Javascript
const f1 = (greeting=hello) => greeting;
```

So the distinction must be the name between a function that can be “called back” and the returned result of a function.

The times when this is important will be when working with the DOM and REACT in JavaScript.

Suppose we are linked to a button component in the DOM and we have named this `button`.

```Javascript
button.onClick(greet);
```

Will work to greet a person each time the button is clicked.

However, if we run

```Javascript
button.onClick(greet());
```

Our button will do nothing when clicked since the function `greet` is called when setting up the onClick property.

`greet()` returns “hello” by default. “hello” is not a function, and so essentially nothing happens on button click.

To review our fat-arrow functions we can also go:

```Javascript
button.onClick(()=>console.log(greeting));
```

We cannot do these call-back type functions in such a simple way in Java.

We could mimic our f2 from before by going:

```Java
String f2 = greet();
```

However, we cannot just assign a function to a variable. We could however create an object that could call a function (method).
Essentially this would just be creating an object in Java ( or C#), then instantiate that object and run the required method.

```Java
Greeter greeter = new Greeter();
greeter.greet();
```
Even so, that is not a call-back function.

#Destructuring – goes without saying (apparently)

So destructuring is something I do not see in Java and C#.

So here is an example from REACT using the useReducer. Never mind what it does since it is rather advanced but it is a clear example of destructuring that is widely used.

```Javascript
const [state, dispatch] = useReducer(reducer, initialState);
```

So here we have a function useReducer which is taking in a reducer (which is a callback function) and an initial state (which can be a primitive type, an array, or an object). It returns two values within an array: `[state, dispatch]`.

It looks weird but essentially we are “destructuring” so the first value that is returned in the array goes to the state, and the second value to dispatch.

Equally, we could write the following and it would do exactly the same thing

```Javascript
const myArray = useReducer(reducer, initialState);
const state = myArray[0];
const dispatch = myArray[1];
```
Now to go to a simpler example:

```Javascript
[a,b] = [1,2];
```

`a` is 1, `b` is 2.

If you did the following:

```Javascript
[a,b,c] = [1,2];
```

`a` and `b` would be the same but now we have `c` also which is `undefined`.

# Conclusion

That concludes our brief and casual look at JavaScript vs Java/C#!