DEV Community

Cover image for Why I love Javascript
Aro Andriamaro
Aro Andriamaro

Posted on • Edited on • Originally published at malagasydev.com

Why I love Javascript

Version française -> Pourquoi j'adore Javascript

I know, I know. Naysayers will tell you that if you love Javascript, you are a person with a bad taste. And that you're not one the true programmers.

You are just another random person who thinks he can be a software developer after attending a bootcamp for 3 months or so - Naysayers

But I really love this language. There is some cool things and tricks in Javascript that I find very interesting and useful. Maybe, I am a person with a bad taste. Maybe. But that's not the question right now.

In this article, I'll try to give you insight or a refresh on some really nice features of Javascript, compared to other programming languages. So let's go.

Destructuring

This one is my favorite. I use it every single day, all the time.

Destructuring syntax allows you to access data inside an object or an array easily and assign them to variables.

Say, you have an object person, with some attributes and a nested object inside it.

const person = {
  fName: "Thomas",
  lName: "Durand",
  age: 25,
  job: {
    title: "Software Developer",
    company: "Renault",
  }
}
Enter fullscreen mode Exit fullscreen mode

Normally if you want to access one or more attributes separately from the object, you would do something like that:

const firstName = person.fName,
const lastName = person.lName,
const job = person.job.title,
// ...
Enter fullscreen mode Exit fullscreen mode

It's not really a convenient way with a big and nested objects. So here comes the destructuring syntax.

It's very simple, it is as if you declare variables. But you include them in curly braces and then asign them the object itself. Ok, less talk, more code..

// with the same object person
const {fName, lName, job} = person;
Enter fullscreen mode Exit fullscreen mode

As you can see, you have to name your variables the same as the person attributes. But don't worry, you can rename them as you want.

const {fName: firstName, lName: lastName, job: profession} = person;
Enter fullscreen mode Exit fullscreen mode

And voilà!

But it is more powerful than that. If you want to access nested objects, you extand the same logic with another curly braces.

const {job: {title, company}} = person;
Enter fullscreen mode Exit fullscreen mode

Now you can just use the variables "title" and "company" directly. And if you want to rename them, again, the logic is the same colon + yourVariableName

const {job: {title: jobTitle, company: companyName}} = person;
Enter fullscreen mode Exit fullscreen mode

Destructuring syntax is especially usefull when you use it when writing functions. It is used a lot in Javascript frameworks like React or Angular.

Instead of doing this:

const myFunction = (person) => {
  const {fName, lName, job: {title, company}} = person;
  // ...
}
Enter fullscreen mode Exit fullscreen mode

You can directly write something like this:

const myFunction = ({fName, lName, job: {title, company}}) => {
  // ...
}
Enter fullscreen mode Exit fullscreen mode

Destructuring syntax are used also with arrays. Below, a quick example for swaping variables with array destructuring:

const myArray = [1,2];
let [a,b] = myArray;
console.log(a); // 1
console.log(b); // 2

[b,a] = [a,b]; // re-assigns a in b and b in a

console.log(a); // 2
console.log(b); // 1
Enter fullscreen mode Exit fullscreen mode

Spread operator

Another cool feature used with objects and arrays. As the name suggests (or not), it spreads the data from inside objects or arrays. For instance, it is very usefull for copying objects or arrays.

Ok, here is the code:

const personA = {
  name: "Doe",
  firstName: "John", 
  age: 25,
}

let personB = {}, personC = {};

// Say we have another person named John Doe but is 50 years old
// To copy some attributes from the already declared personA
// Normally, we write
Object.assign(personB, personA);
personB.age = 50;

// But with the spread operator, we can write something like this
personC = {...personA, age: 50};
Enter fullscreen mode Exit fullscreen mode

And for arrays:

const todos = ["cooking","laundry"];
const tomorrowTodos = ["grocery shopping",...todos, "homework"];
console.log(tomorrowTodos); // ["grocery shopping", "cooking","laundry", "homework"]
Enter fullscreen mode Exit fullscreen mode

And by combining it with the destructuring syntax, we can have elegant syntax like this:

const myArray = [1,2,3,4,5];
const [a, ...rest] = myArray;
console.log(a); // 1
console.log(rest); // [2,3,4,5]
Enter fullscreen mode Exit fullscreen mode

Map, Filter and Reduce

Ok, those 3 are not exclusive to Javascript only. But they are so useful that you have to know how to use them.

Map, Filter and Reduce are array methods and allows you to, respectively:

  • perform a computation on each element of an array and return a new array
  • filter an array whose elements respect some condition and return the new filtered array
  • executes a reducer function on each elements and return one output based on the computation done with the array elements

Each 3 methods takes a callback function, as one of its parameters, to apply to the elements inside the array.

Using those features are a way of doing what is called declarative programming.

It is a style of programming that focuses on the resolution of the problem at hand by declaring the "what to do" instead of the "how to do it" (in contrast with imperative programming.

// Map
// Pluralize words inside an array
const singular = ["pizza", "baggel", "hat"];
const plural = singular.map(word => word + "s");
console.log(plural); // ["pizzas", "baggels", "hats"]

// Filter
// Returns all the even number inside an array
const numbers = [14, 5, 23, 28, 105];
const evenNumbers = numbers.filter(number => number%2 === 0); // returns all the numbers that returns true for the condition number%2===0
console.log(evenNumbers); // [14, 28]

// Reduce
// 1. Simple sum of all the elements in an array
const myArray = [2,3,4,1];
console.log(myArray.reduce((acc, num) => acc + num, 0)) // 10
// acc is the accumulator value and num the current value of the element beign tested
// the second parameter 0 of the reduce is the initial value we want for the accumulator

// 2. Find the common elements accross multiple arrays
function intersection(arrays, ) {
  return [...arguments].reduce((acc,array,i)=>{
    if(i===0){
      acc = [...array];
    } else {
      acc = acc.filter(x=>array.includes(x));
    }
    return acc;
  },[])
}
console.log(intersection([5, 10, 15, 20], [15, 88, 1, 5, 7], [1, 10, 15, 5, 20]));
// [5, 15]
Enter fullscreen mode Exit fullscreen mode

Conclusion

There are far more nice features in Javascript but knowing and using correctly those three concepts will make you stand out from other developers.

That's it pal. I hope you liked the article (my first one). I'll write a lot more Javascript things in the future and more in depth too. For now, let me know what you think of this article.

PS: I'm sorry if I made some English mistakes. It is not my first nor my second language :)

Top comments (19)

Collapse
 
hangindev profile image
Jason Leung 🧗‍♂️👨‍💻

Besides its constantly evolving features, the thing I like most about JS is how easy I can build something and share it with the world. I guess I like JavaScript because I like the web. 🌐

Looking forward to your future articles. 🍻

Collapse
 
notaro14 profile image
Aro Andriamaro

I agree, the web is so fascinating.

Thank you :)

Collapse
 
jrogers8835 profile image
jrogers8835 • Edited

I've been a tried and true java dev most of my coding career and though loosely typed languages make me cringe a little, these are all features I love about javascript as well. Also, for tinkering around with an idea, spinning up a node server locally is 100x faster than java.

Collapse
 
notaro14 profile image
Aro Andriamaro

I too have been cringing on lossely typed language before. But now, I saw those language as a good choice for learning and trying algorithms.

I have just to focus on the algorithm and not on the data type nor the memory I forgot to deallocate (hello C and C++)

Collapse
 
itsjzt profile image
Saurabh Sharma

Try typescript

Collapse
 
miketalbot profile image
Mike Talbot ⭐

I understand typescript for big projects and wider teams to keep code self-described etc. I do think that there is an awful lot of extra typing writing TypeScript for small projects for minimal benefit. I could count on one hand the number of bugs I've had in my JS projects due to passing the wrong type to a function. I'm just not a fan of typing a bunch of stuff out twice when I don't need to.

Thread Thread
 
Sloan, the sloth mascot
Comment deleted
 
itsjzt profile image
Saurabh Sharma

I'm also not a very big fan of static typing, but the person is coming from Java so, Im expecting typescript would be easier transition for him

Thread Thread
 
miketalbot profile image
Mike Talbot ⭐

That's true... I come from a C# background so TypeScript looks very familiar to me. I just appreciate the flexibility and terseness of JS and I'm not sure there are always benefits to type-safety when weighed up against the cost of declaring it. Again it depends. In C# I feel it helps because the JIT or AOT compiler use it to make code, in TypeScript it has no benefit unless I abuse the underlying calls without understanding the implication (then we end up in a premature optimization argument).

I'm not seeking to be argumentative, I feel I learn something from the debate.

Thread Thread
 
itsjzt profile image
Saurabh Sharma

Actually types in typescript are just used to provide better tooling (better ide support kindof stuff)

Collapse
 
himujjal profile image
Himujjal Upadhyaya

Was about to say this too. Even beginner javascript programmers should not be taught JavaScript. TypeScript should be a first class citizen.

Thread Thread
 
merri profile image
Vesa Piittinen

I disagree. Not every codebase requires TypeScript. Strict typing is too often a waste of time with a negative ROI. Especially if you do your unit tests! They cover far more cases of bugs than TypeScript can ever catch.

I know I'm in the current minority of about 20% of JS devs who don't want to use TypeScript, but popularity alone shouldn't make you not think about things. Such as "does this thing really provide me value for this particular codebase?"

Thread Thread
 
himujjal profile image
Himujjal Upadhyaya

Yes. Its a matter of opinion and you might have a different one.

TypeScript saved me a lot of time when using React and Redux. Passing data around is not a child's play. Then again even in unit tests you are supposed to write tests for type checking. A lot of that is reduced because of you using TS.

In my opinion, I consider writing extra types is a tradeoff for maintainable and scalable code. Many a times we don't even have to refer to the documentation of a library. The types themselves give an idea about what you need to pass (I know JSDoc exists).

JSDoc is again messy code (it seems that way to me). TS is cleaner code.

TypeScript would have been a lot better again if it also included runtime type checking (hegelJS like).

Admit it. Typechecking saves time. It's a trade off

Thread Thread
 
merri profile image
Vesa Piittinen

You have a very bad attitude on this and due to that fail to be open to differing opinions. Instead you keep on pushing that you are right and I should change my opinion because of that. Why is that?

What if I'd end up with the same kind of style:

"Admit it. Being open to and respectful of different opinions makes you a better person and a better developer. There is no tradeoff to that."

Does that make you feel good? Or would you just get angry and defend your opinion no matter what?

Thread Thread
 
himujjal profile image
Himujjal Upadhyaya

I am sorry if my attitude was too pushy. Never intended it to be that way। Peace 😊✌️

Collapse
 
zzz404 profile image
zzz404

I am coming from java, kotlin, c#. Typescript is great for me.
Even through I write python code, I use typing everywhere if I can.

Collapse
 
asiros profile image
Chonbashev Artyk

try haskell =)

Collapse
 
leobm profile image
Felix Wittmann

I would use Purescript.

Collapse
 
donnisnoni profile image
Don Alfons Nisnoni

Yeah... because Javascript is easy, dynamic, multi-paradigm programming language.Its easy to get started, also very flexible. So make sense it's a lovely language, especially when it comes to web development. Typescript make it more easy with static-typing. Well, the remains is speed, security, etc. Now I'm looking to learn Go & V.