DEV Community

informathemusic
informathemusic

Posted on

Keep calm and Learn Javascript!

There are many reasons to know javascript:
-Make a discord bot
-Make your first executable
-Look cool with your matrix-like node.js script
-Create beautiful animations
-Etc,etc,etc...

And there is also a secret reason: I hate people that show me their dumb errors (Unexpected token "}" at line 5 character 11) and then says: "I don't understand this error, fix this for me". It's okay for the first time, but not the second.

We're using node js, see this for help

I'm going to start with the beginning,

0. The setup

Firstly, create a file called "script.js" in a folder newly created (I guess). Of course, you can change "script" to anything you want

Then, run this command in the folder:
npm init
and answer.

Note: Every change is applied to script.js

Done!

1. Script output

To output a string in a script, you can type: console.log("String");

Then run
node script.js
and you get your very first output!

2. Variables

I'm taking an example: hp in Minecraft
I get 20 hearts at the beginning
I'm falling from a mountain; I'm losing 4 hearts.
I'm drinking a healing potion; I'm getting 4 hearts more.
No! A skeleton! I lost 1 heart.

To initialize a variable, you can use var or let; I prefer let

Here's our code:

let hp=20;
//Hey! I'm a comment! NodeJS doesn't care about me but the code reader does!
/*Also this is
a multiline
comment!*/
console.log("I have "+hp+" hp!");
//OOF
hp=hp-4;
//hp=20-4
console.log("I now have "+hp+" hp!");
hp+=4;
//This is included in the js syntax
console.log("I now have "+hp+" hp!");
hp--;
//This is also an integrated syntax
console.log("I now have "+hp+" hp!")
Enter fullscreen mode Exit fullscreen mode

3. Functions

Do you remember our messy code?
Well, I'm gonna pimp that up!

let hp=20;
function addRemoveHp(val){
  hp+=val;
  console.log("I now have "+hp+" hp!")
}
addRemoveHp(-4);
addRemoveHp(4);
addRemoveHp(1);
Enter fullscreen mode Exit fullscreen mode

Gosh, it's working! But what the hell is "function addRemoveHp(val){[...]}"???

Welcome to the fabulous world of functions!

A function is formatted like this:
function NAME(ARG1, ARG2, ARG3, [...], ARG_N){/*You get your code here*/}

You can replace NAME, ARG1, ARG2, ARG3, ARG_N ant the multiline comment with whatever you want, like
function sayHp(hp){console.log("You now have"+hp+"hp!");}
or
function addHp(){hp++;}
or
function removeHp(){hp--;}

4. Conditions

It's coming...

Top comments (2)

Collapse
 
coolshaurya profile image
Shaurya

Instead of learning JavaScript you can learn Rust instead. Or Python or Ruby or Golang or Haskell or C++ or C or Java.

Collapse
 
informathemusic profile image
informathemusic

This is just a base for ppl who want to use tutorials :shrug: