EDIT: This goes as an extension to this other post: http://forums.rpgmakerweb.com/index.php?/topic/43954-javascript-programming-for-absolute-beginners/
While it has some early concepts it lacks presentation and defining the basic concepts of variables, loops, and cicles.
After reading this you may want to go to the other one.
Well, people would actually need to start from the ground, so while there was already a "warm up" with more like a "cookbook" with recipes to do some usefull things, that was not how to start if you, for some strange reason, decided to start programming in MV just because it is javascript and not ruby.
If you still don't get much about what something is in programming languages here I will give you some basic concepts while we go.
Remember, practice transforms you in a master (This is how you say this on english, oh never mind...) so always, try to practice and learn at great places like Code Academy, and ask the experts.
Yes, experts usually like to help people if they ask for help (no if they ask for do this for me but people usually helps, don't be afraid of them)
Hope this helps people who really know anything about javascript to learn it, probably I can't do better than code academy, this is like a really short version, but I have the (bad) humor code academy doesn't so it's your choice.
Lesson 1 The variables
What are variables?
Variables are, by definition a region in your RAM (you know the memory you need to run programs fast) wich has some data, because that is boring and we are not trying to look to deep, we can call variables as this:
Variables are boxes, they contain information, you can store things in that boxes, but those boxes are special of course, they may contain numbers, or letters, or words, or... you, but they can't contain more than just one thing at a time (wait.. that is not true at all, but for now, you just take my word and it works to understand them).
variables of course, always have a label or a name, because you want to know where you saved your precious gold, for example.
Another languages variables must contain another label, called a type. Like marking "on this box I can only put numbers"
On the javascript case, variables does not contain types, you can store our gold or a cat on the same box wich while you can, it doesn't mean than you have to.
Actually, don't do it please, I don't want to find a cat on a chest labeled as "I have gold"
Well, now to the javascript world, how do we create a variable ?
well, do you remember ? A variable starts with an special keyword 'var' followed by its label and finally you can put a value for it.
var myVariable = 5;means I create a variable called myVariable and start it with the number 5 inside.
how to name your variables? why I call it myVariable and not MyVariable or my-variable or my_variable ?
Well, javascript, as a language have some common practics you may follow, one of them is how to name a variables, this is called camel case, because it looks like camels, don't you think?
oh, what things are valid as a name ?
sorry I almost forgot that, you can only start it with a letter (any letter from any language, but please, for your code if you plan to share write it on english) or a symbol counted as letter, like _ or $, (sadly, @ or : are not valid)
While you can't start with a letter, you can then put numbers aside from the other symbols.
So something23 is valid.
lets see then,
awesome23 is valid, i_have_underscores is valid, año (year in english, please, for spanish's sake, don't change the ñ to n...) is valid, $myMoney is valid, but 23dollars isn't.
Well, you learned what is a variable now... (or at least, you know you can put things there I hope)
Let's go to our next subject.
What can I put there?
Well, javascript have many things you can store on a variable, we can store numbers (even decimal ones) pieces of text (called strings) a list of other things where the order is important (called array), some orders we can put together tou facilitate the use of them (functions) and something almost unique in javascript called object (no, not object as concept, but javascript's objects are almost unique) and something called a boolean, wich means a value being only yes and no. (or true and false)
Let's see, how do you write that, easy:
var myNumber = 23; //Now I have a number, oh, everything after // is a comment and ignored on this line
Hmmm, let's stop here for a moment, you don't know what a function or object are still, so let's take a brek here.
Well, now, it seems pretty easy right, even when you look at the code and say:
- myArray is equal to..
- stop
This is when things start to look different, in javascript (and many other languages) the = is used as assignment, so you mean
"I put inside myNumber the number 23" (if you want to sound cool, and you sure want, you can say "I initialize myNumber as 23")
initialize is "I declare a variable and assign it to the starting value of ..."
declare is "hey, I use this name to put something program."
Why is this important ?
Well because you can change the values after, this is useful sometimes (or most of the time) you know, they are called variables because the usually change over time.. variable, variation, change, got it?
How do you do that?
Well, just take out 'var' and you are done:
myNumber = 323; // because I want it to be bigger now... oops this might sound bad...Hey, but sometimes is usefull to have a value you can only read, but not change... right, put the number π it will never change, but its good to note than is good to have it inside a variable, it's easier to read and has more meaning than 3.1415...
Remember kids, always write code in order to make your life easier first, because you may want to edit it somehow and you won't be able to know how...
(Bonus points if you thought here, hey, can I name my variable like that, and the answer is... in javascript yes, you can)
Hey, this won't be any help if you can only store things... right, so why not do some math with them:
var myResult = 23 + 5; // because I'm lazy to write 28...hey but you can operate with variables here:
myResult = 23 * myMagicNumber;Oh, *, means multiplication...
Do you remember math from school? (ugh, school, yikes - throws a chalk at that student) wel, remmeber how some symbos go before ? here you do the same, so
var result = 5 + 7 * 2 - 4;is 15, oh you can use parenthesis to avoid confusion or to change the precedence.
var result = 5 + (7 * 2) - 4; // this will work like the other exampleThis won't:
var result = (5 + 7) * 2 - 4; // this will work like the other exampleThere is another kind of variable, wich you can only read but not change, it's called a constant (guess why...) but hey, this are easy too, just when ou make a variable, call change var for const.
const numberYouCantChange = 35;They don't have anything special except that, so they are usfeull only when you want to keep forever a value somewhere.
Now, you know what are variables and how to do some work, so you can call it a day. so rest.
Conditions and (not fruit) Loops
You know, programming languages allows you to do more magic work, like checking if a variable is true, or if a number is less than, if you used the maker probably you had to use a conditional branch.
Well javascript have conditional branches, in more flavors than the events of the rpg maker, and in "text mode".
The first and easier to understand is the if, you know like the sentence if its rainining, my plants are going to get wet.
Let's translate this into javascript, shall we:
if (isRaining) plantsAreWet = true;Isn't it nice ?
Hey, you can also do more than one thing:
if (isRaining) { plantsAreWet = true; // yes plants are wet but... dogIsOutside = false; // no, the dog shouldn't be outside anymore.}See the "{" ? well, they are used to limit a block, a block is a bunch of sentences, a sentence is an order you do and it ends with ';'
var x = 3; // This is a sentencevar y = 2; // This is another sentenceUsually omitting ; nowdays doesn't cause much trouble, for some modernizations on the javascript language, but it is good practices to write them here, just because it may lead to some unexpected problems if you don't.
Well, going back to the if, you can also do somethign when the condition is not true:
var theSunIs; // yes, you can also start them without a value, this may be usefull too...if (isRaining) { theSunIs = 'Over the clouds';} else { theSunIs = 'Shining over my head';}If you are thinking what is true or false on isRaining, javascript is... a bit complex about that, for now, we assume you are using always true or false, true will run the code inside the if part, false the code inside the else part.
You can omit the '{' '}' if the if it has one sentence, but it's not a good practice, so avoid it always use '{' '}'
There is a short version wich is probably better:
var theSunIs = isRaining ? 'Over the clouds' : 'Shining over my head';I'll give you a tip, sometimes yo need to do something multiple times, with a collection of things (or an array) or do something while certain conditions are met.
If you remember the rpg maker event commands, you can use tags and jump to them.
This are an older version of something called 'iteration' (wich is basically says, this code will run from zero to any number of times while certain conditions are met)
This is when 'while' and 'for' loops are usefull, because for is basically a powered up version of while, we will see while first.
while, runs the code inside itself from 0 to any number of times, while the condition is "true"
for example, let's count from one to 10:
var count = 1;// wich if you remember your math classes < is 'less than', as you may guess, <= (less or equal than) 10 also works herewhile (count < 11) { count = count + 1;};Hmmm, that count = count + 1; feels a bit strange right?
Rememeber = means 'I put a new value inside the box' so this means 'inside count I'll put count+1'
This way of changing a value of a variable, like adding or substracting is so common in wich you can short it as:
count += 1; // Yes, this means count = count + 1Usually if you have a way to operate, like * you also have its corresponding version with =
so for *= you have *=, for -, you have -=, etc.
Adding or removing 1 is also even so common it has it's own special way to do:
++count; // yes, this means count + 1 count++; // this too, but it has a difference on some cases, usually it's better if you use the uuper one.Now in theory, you can solve any problem you have using this constructions only isn't that awesaome?
In real life of course, you use more things because it's esier to manage, like functions.
There is a variation of while, remember, while only runs once if the condition is met:
var runWhile = false;while (runWhile) { // never runs // blah blah blah}Well, if you always need to run that piece of code first, you have a variation called do-loop
do { // insert your code here} while ( runWhile);This will run not from zero to any numberr of times, but from 1 to any number of times.
Less used, but it exists and it has its differences...
The 'for' loops are an extension to the while, but with some meaning.
We use for, when we want to repeat a process with a number, while as you could see you can do it with while and it will work, for convenience we use a for:
for ( var count = 1; count < 11; ++count) { / huh? why? whyyyyyyyyyyyyyyyyyy? // code with the number you are counting}Yes, this code will do the same as the other one,
the for works like this:
for ( A ; B ; C )
in wich :
A: 'when you star the loop do this, just the first time'
B: 'the condition for executing the loop'
C: 'what you do after you do one 'iteration of the loop'
If you are asking why I don't write it like this:
for ( <variable initialization> ; <boolean expression>; <post loop conditions> ) { It is because I am trying to show you this in a more friendly manner, not on a encyclopedia driven mode.
For that, you have Code Academy.
Now, there are two more 'special versions' of for I will teach, but when we get into objects.
If you want to dig in, feel free to check the variations of 'for..of' and 'for..in'
Functions: Now we are going somewhere...
Well, I'll tell you a secret, us, programmers are lazy and don't really want to write the same pieces of code over and over and over (we may have to do this if we are fixing bugs, but you know, we dream with not doing that) so we decided:
"well, we can do this, but if I change x from 23 to 32 it should work too, is even better, it should work with any number I decide to put there" and... this is how functions are born (well, no, the concept of function comes from math, do you remember those fancy lines you draw inside a graph? yes, that, here they are a bit more complex... but it is almost the same)
How do you say "I want to create a function" ?
Lets start with a function than does nothing:
function myFunction() { // this does nothing 100% of the time.}Oh, so if you want to create a function, you just use "function myFunction" it sound like... well, that is "normal"
Why I put there a pair of () with nothing inside? well, functions like math, can have parameters, when there are no parameters you just put it as an empty list.
Oh, parameters are written just like math:
function myFunction(x, y) { // this function also does nothing, but at least you can pass x and y to it}now, functions have another special feature, like math, they can 'return a value', wich means, 'I will generate something than you can use later', how do you return something ?
I'll give you 3 seconds to try and guess it...
Yes, its doing using the keyword return:
function myFunction(x, y) { return x + y;}Yep, now if you use my function calling it, you can get the value of 'x + y'
Oh, rmemeber how inside if you put {} to define "a bunch of sentences" (called a block) well here it's the same, inside those {} you can put as many sentences af you want
Hey, how do you use them you ask?
That is easy, you 'call them' in your code like this:
var result = myFunction(2, 3); //see, I put the name followed by the arguments in the order I want them (2, 3)Well, if you have an empty list you can always use:
var result = myFunction();Oh, remember too, order is important when you use a function so no matter what x will always contain the first argument (or thing you pass on to the variable)
Now, there are some things like "variable number of arguments" (wich if you want to sound cool, call it 'variadic functions') or "optional arguments" (wich we programmers cound't find a cool name for it still)
This is out of the scope of this tutorial, first use the functions on "easy" then you can improve yourself.
Oh, and if you ask, yes functions can be chained or combined on your sentences:
var result = myFunction(2, 3) + myFunction( myFunction(4, 5), 32 );Yay! function madness! YOU HAVE NO IDEA ...
Functions have more ins and outs, like what does 'this' means? Wich I'll cover when we see what objects are.
Still you can solve pretty much anything and you don't even have to reppeat your code over and over, because you can loop something or make it as a function.
Do you want an excersise? well, this one is easy and will use all you learned so far:
Write a function called fizzBuzz when I pass as an argument a number. Your function must count from 1 to the number I give (inclusive) and show each number, except on some cases:
if you can divide a number by 3, you should print Fizz.
if you can divide a number by 5, you should print Buzz.
if you can divide a number by 3 and 5, you should print FizzBuzz.
if none of the conditions are met remeber, just print the number.
"you can divide a number by other" if the remainder of the operation is 0, wich means, 2 is not divisible by 3, nor 5 is divisible by 3, 6 is because 6 / 3 is 2 and you have no remainder.
Here are some tips to help you:
You can print a number with a pop up window using 'alert( something )' (wich is annoying) or with 'console.log( something )'
(hey, what does the console.log means... ? shh, this is going to a future lesson, so please, let's avoid this by now and write it like that)
You can divide numbers using '/' a / b means "a divided by b".
You can also get the remainder with '%'
a % b means "I want to get the remainder of a / b", so "7 % 2" is 1 because:
7 / 2 is 3 (as integers, so ignore decimals here) and "(3 * 2) + 1 = 7"...
Try to do it in a way in wich if I call "fizzBuzz(37)" will print 1, 2, Fizz, 4, Buzz, Fizz, etc, etc...
Lesson 4: Arrays
What are arrays ?, well as I said, arrays are just a bunch of things on an specific order.
You can use them as sets or collections, wich is how you usually use them.
Arrays are easy to create in javascript, you just need to write a list of things inside a pair of brackets:
var myArray = [ 1, 2, 3, 4 ]; // we already did this...Now, you know, you may want to get a value from an array, like many languages, getting an array or setting it is done via something people call subscripting:
var result = myArray[0]; // This will give you the first element on the array (1 in the other array)myArray[0] = 2; // This will put inside the array at index 0 (the first one) the value 2Notice how to get or set something you use a pair of brackets too.
Arrays are one of the reasons (wait, yes, there is more) why I said "It's not true than variables can only contain 1 thing" they can contain arrays, so they can contain an array with many things inside.
Arrays can also be inside another arrays, so you can have:
[ [1, 3], [2, 4], [7, 9] ]At the moment, lets imagine we are using fixed size arrays (yes, you can add or remove a value), but this is for a good reason, because we didn't talk about objects, and arrays are a special type of object.
Also remember this, arrays count its first element as 0, not 1, so you start counting from 0 to the size - 1,
In other words, an array with 10 items has values from 0 upto 9 (inclusive).
Why I decided to teach you array first, well that is because on many languages this is not true, and objects are more complex than arrays to understand.
So, there you are, you can now sotre a bunch of something, check if something is equal to other things, repeat a bunch of code, call functions, you are practically done.
Yes javascript doesn't have that complexity if you just cut the bases appart from each other.
Lesson 5: A world of Objects
Now its the time to talk about what objects are.
Of course, objects are the main reason this language is called an 'object oriented language', so they must be important right?
Well yes, and I have to say to you, you already worked with some already.
While the "type" of a number is not an object, not an array, or even a boolean, they are all objects in the terms of the language.
(yes, yes, they are wrapped and blah blah blah blah, but for the sake of simplicity, lets think they are please)
So, what are objects you ask?
Well you can think an object is something you can represent as an entity, as something or someone in your code. For example, a function, a person, an animal, a type, etc.
So if you want to think objects easy, think of them as dictionaries, they contain words, associated with a definition.
Here our definitions are other objects (or, as you may think, numbers, functions, etc)
They work really, really similar to arrays in that sense, but think than it can work with more than just numbers.
var anObject = {}; // note the {}, this is an empty objectanObject.value = 23; // yes, you can put things inside this wayalert(anObject.value) // you also can get the values the same wayanObject['value']; // you can also get the value this wayvar name = 'value';anObject[name]; // you can even use any type of expression inside.Do you notice something ?, yes, they work like arrays too, but with strings or words... so yes, as you may discovered, Arrays were just objects with numbers as keys.
This, of coursewqorks on many ways, imagine if you have a character:
var myCharacter = {};myCharacter.name = 'Frederic';myCharacter.hp = 30;myCharacter.atk = 5;Why not?
But you can also create objects with properties already inside, this will do the same as above:
var myCharacter = { name: 'Frederic', hp: 30, atk: 5};Objects also have 'behaviour' or in another way to say it, methods.
Methods represents what an object can do.
var myObject { jump: function () { /* a bit of code here... */ } };myObject.jump(); // just like normal functions, you call it the same way.And this is where the tricky part comes, sometimes you may want to have a reference to the object itself, so there is an easy way to do this, with a keyword called 'this'
var hero = { isJumping: false};hero.jump = function () { this.isJumping = true;};hero.land = function () { this.isJumping = false;};so then, 'this' is more complicated than just this tutorial, it has some js thingies than you may want to ignore for now...
But for the moment consider it as a "reference" to the object you are working with.
Now you have learned what are objects, and how you can create them, now there is no limit you can do.
But hey, did I mension programmers are lazy ? Do you want to know what are the advantages of using objects ?
Do you want to think a way to not do again and again and again the same objects?
Well, the next lesson will teach you just that, something called prototyping wich is like the reason why javascript is so popular.
Lesson 6: "Prototyping and classes"
Here goes
Lesson 7: Final exam
Here goes
See ya!
While it has some early concepts it lacks presentation and defining the basic concepts of variables, loops, and cicles.
After reading this you may want to go to the other one.
Well, people would actually need to start from the ground, so while there was already a "warm up" with more like a "cookbook" with recipes to do some usefull things, that was not how to start if you, for some strange reason, decided to start programming in MV just because it is javascript and not ruby.
If you still don't get much about what something is in programming languages here I will give you some basic concepts while we go.
Remember, practice transforms you in a master (This is how you say this on english, oh never mind...) so always, try to practice and learn at great places like Code Academy, and ask the experts.
Yes, experts usually like to help people if they ask for help (no if they ask for do this for me but people usually helps, don't be afraid of them)
Hope this helps people who really know anything about javascript to learn it, probably I can't do better than code academy, this is like a really short version, but I have the (bad) humor code academy doesn't so it's your choice.
Lesson 1 The variables
What are variables?
Variables are, by definition a region in your RAM (you know the memory you need to run programs fast) wich has some data, because that is boring and we are not trying to look to deep, we can call variables as this:
Variables are boxes, they contain information, you can store things in that boxes, but those boxes are special of course, they may contain numbers, or letters, or words, or... you, but they can't contain more than just one thing at a time (wait.. that is not true at all, but for now, you just take my word and it works to understand them).
variables of course, always have a label or a name, because you want to know where you saved your precious gold, for example.
Another languages variables must contain another label, called a type. Like marking "on this box I can only put numbers"
On the javascript case, variables does not contain types, you can store our gold or a cat on the same box wich while you can, it doesn't mean than you have to.
Actually, don't do it please, I don't want to find a cat on a chest labeled as "I have gold"
Well, now to the javascript world, how do we create a variable ?
well, do you remember ? A variable starts with an special keyword 'var' followed by its label and finally you can put a value for it.
var myVariable = 5;means I create a variable called myVariable and start it with the number 5 inside.
how to name your variables? why I call it myVariable and not MyVariable or my-variable or my_variable ?
Well, javascript, as a language have some common practics you may follow, one of them is how to name a variables, this is called camel case, because it looks like camels, don't you think?
oh, what things are valid as a name ?
sorry I almost forgot that, you can only start it with a letter (any letter from any language, but please, for your code if you plan to share write it on english) or a symbol counted as letter, like _ or $, (sadly, @ or : are not valid)
While you can't start with a letter, you can then put numbers aside from the other symbols.
So something23 is valid.
lets see then,
awesome23 is valid, i_have_underscores is valid, año (year in english, please, for spanish's sake, don't change the ñ to n...) is valid, $myMoney is valid, but 23dollars isn't.
Well, you learned what is a variable now... (or at least, you know you can put things there I hope)
Let's go to our next subject.
What can I put there?
Well, javascript have many things you can store on a variable, we can store numbers (even decimal ones) pieces of text (called strings) a list of other things where the order is important (called array), some orders we can put together tou facilitate the use of them (functions) and something almost unique in javascript called object (no, not object as concept, but javascript's objects are almost unique) and something called a boolean, wich means a value being only yes and no. (or true and false)
Let's see, how do you write that, easy:
var myNumber = 23; //Now I have a number, oh, everything after // is a comment and ignored on this line
Code:
var myString = 'This is some text for you... err I mean Hello world!';
Code:
var myArray = ['Hey, can you see?', 'I have two texts :D'];
Code:
var isThisTrue = false; // of course not
Well, now, it seems pretty easy right, even when you look at the code and say:
- myArray is equal to..
- stop
This is when things start to look different, in javascript (and many other languages) the = is used as assignment, so you mean
"I put inside myNumber the number 23" (if you want to sound cool, and you sure want, you can say "I initialize myNumber as 23")
initialize is "I declare a variable and assign it to the starting value of ..."
declare is "hey, I use this name to put something program."
Why is this important ?
Well because you can change the values after, this is useful sometimes (or most of the time) you know, they are called variables because the usually change over time.. variable, variation, change, got it?
How do you do that?
Well, just take out 'var' and you are done:
myNumber = 323; // because I want it to be bigger now... oops this might sound bad...Hey, but sometimes is usefull to have a value you can only read, but not change... right, put the number π it will never change, but its good to note than is good to have it inside a variable, it's easier to read and has more meaning than 3.1415...
Remember kids, always write code in order to make your life easier first, because you may want to edit it somehow and you won't be able to know how...
(Bonus points if you thought here, hey, can I name my variable like that, and the answer is... in javascript yes, you can)
Hey, this won't be any help if you can only store things... right, so why not do some math with them:
var myResult = 23 + 5; // because I'm lazy to write 28...hey but you can operate with variables here:
myResult = 23 * myMagicNumber;Oh, *, means multiplication...
Do you remember math from school? (ugh, school, yikes - throws a chalk at that student) wel, remmeber how some symbos go before ? here you do the same, so
var result = 5 + 7 * 2 - 4;is 15, oh you can use parenthesis to avoid confusion or to change the precedence.
var result = 5 + (7 * 2) - 4; // this will work like the other exampleThis won't:
var result = (5 + 7) * 2 - 4; // this will work like the other exampleThere is another kind of variable, wich you can only read but not change, it's called a constant (guess why...) but hey, this are easy too, just when ou make a variable, call change var for const.
const numberYouCantChange = 35;They don't have anything special except that, so they are usfeull only when you want to keep forever a value somewhere.
Now, you know what are variables and how to do some work, so you can call it a day. so rest.
Conditions and (not fruit) Loops
You know, programming languages allows you to do more magic work, like checking if a variable is true, or if a number is less than, if you used the maker probably you had to use a conditional branch.
Well javascript have conditional branches, in more flavors than the events of the rpg maker, and in "text mode".
The first and easier to understand is the if, you know like the sentence if its rainining, my plants are going to get wet.
Let's translate this into javascript, shall we:
if (isRaining) plantsAreWet = true;Isn't it nice ?
Hey, you can also do more than one thing:
if (isRaining) { plantsAreWet = true; // yes plants are wet but... dogIsOutside = false; // no, the dog shouldn't be outside anymore.}See the "{" ? well, they are used to limit a block, a block is a bunch of sentences, a sentence is an order you do and it ends with ';'
var x = 3; // This is a sentencevar y = 2; // This is another sentenceUsually omitting ; nowdays doesn't cause much trouble, for some modernizations on the javascript language, but it is good practices to write them here, just because it may lead to some unexpected problems if you don't.
Well, going back to the if, you can also do somethign when the condition is not true:
var theSunIs; // yes, you can also start them without a value, this may be usefull too...if (isRaining) { theSunIs = 'Over the clouds';} else { theSunIs = 'Shining over my head';}If you are thinking what is true or false on isRaining, javascript is... a bit complex about that, for now, we assume you are using always true or false, true will run the code inside the if part, false the code inside the else part.
You can omit the '{' '}' if the if it has one sentence, but it's not a good practice, so avoid it always use '{' '}'
There is a short version wich is probably better:
var theSunIs = isRaining ? 'Over the clouds' : 'Shining over my head';I'll give you a tip, sometimes yo need to do something multiple times, with a collection of things (or an array) or do something while certain conditions are met.
If you remember the rpg maker event commands, you can use tags and jump to them.
This are an older version of something called 'iteration' (wich is basically says, this code will run from zero to any number of times while certain conditions are met)
This is when 'while' and 'for' loops are usefull, because for is basically a powered up version of while, we will see while first.
while, runs the code inside itself from 0 to any number of times, while the condition is "true"
for example, let's count from one to 10:
var count = 1;// wich if you remember your math classes < is 'less than', as you may guess, <= (less or equal than) 10 also works herewhile (count < 11) { count = count + 1;};Hmmm, that count = count + 1; feels a bit strange right?
Rememeber = means 'I put a new value inside the box' so this means 'inside count I'll put count+1'
This way of changing a value of a variable, like adding or substracting is so common in wich you can short it as:
count += 1; // Yes, this means count = count + 1Usually if you have a way to operate, like * you also have its corresponding version with =
so for *= you have *=, for -, you have -=, etc.
Adding or removing 1 is also even so common it has it's own special way to do:
++count; // yes, this means count + 1 count++; // this too, but it has a difference on some cases, usually it's better if you use the uuper one.Now in theory, you can solve any problem you have using this constructions only isn't that awesaome?
In real life of course, you use more things because it's esier to manage, like functions.
There is a variation of while, remember, while only runs once if the condition is met:
var runWhile = false;while (runWhile) { // never runs // blah blah blah}Well, if you always need to run that piece of code first, you have a variation called do-loop
do { // insert your code here} while ( runWhile);This will run not from zero to any numberr of times, but from 1 to any number of times.
Less used, but it exists and it has its differences...
The 'for' loops are an extension to the while, but with some meaning.
We use for, when we want to repeat a process with a number, while as you could see you can do it with while and it will work, for convenience we use a for:
for ( var count = 1; count < 11; ++count) { / huh? why? whyyyyyyyyyyyyyyyyyy? // code with the number you are counting}Yes, this code will do the same as the other one,
the for works like this:
for ( A ; B ; C )
in wich :
A: 'when you star the loop do this, just the first time'
B: 'the condition for executing the loop'
C: 'what you do after you do one 'iteration of the loop'
If you are asking why I don't write it like this:
for ( <variable initialization> ; <boolean expression>; <post loop conditions> ) { It is because I am trying to show you this in a more friendly manner, not on a encyclopedia driven mode.
For that, you have Code Academy.
Now, there are two more 'special versions' of for I will teach, but when we get into objects.
If you want to dig in, feel free to check the variations of 'for..of' and 'for..in'
Functions: Now we are going somewhere...
Well, I'll tell you a secret, us, programmers are lazy and don't really want to write the same pieces of code over and over and over (we may have to do this if we are fixing bugs, but you know, we dream with not doing that) so we decided:
"well, we can do this, but if I change x from 23 to 32 it should work too, is even better, it should work with any number I decide to put there" and... this is how functions are born (well, no, the concept of function comes from math, do you remember those fancy lines you draw inside a graph? yes, that, here they are a bit more complex... but it is almost the same)
How do you say "I want to create a function" ?
Lets start with a function than does nothing:
function myFunction() { // this does nothing 100% of the time.}Oh, so if you want to create a function, you just use "function myFunction" it sound like... well, that is "normal"
Why I put there a pair of () with nothing inside? well, functions like math, can have parameters, when there are no parameters you just put it as an empty list.
Oh, parameters are written just like math:
function myFunction(x, y) { // this function also does nothing, but at least you can pass x and y to it}now, functions have another special feature, like math, they can 'return a value', wich means, 'I will generate something than you can use later', how do you return something ?
I'll give you 3 seconds to try and guess it...
Yes, its doing using the keyword return:
function myFunction(x, y) { return x + y;}Yep, now if you use my function calling it, you can get the value of 'x + y'
Oh, rmemeber how inside if you put {} to define "a bunch of sentences" (called a block) well here it's the same, inside those {} you can put as many sentences af you want
Hey, how do you use them you ask?
That is easy, you 'call them' in your code like this:
var result = myFunction(2, 3); //see, I put the name followed by the arguments in the order I want them (2, 3)Well, if you have an empty list you can always use:
var result = myFunction();Oh, remember too, order is important when you use a function so no matter what x will always contain the first argument (or thing you pass on to the variable)
Now, there are some things like "variable number of arguments" (wich if you want to sound cool, call it 'variadic functions') or "optional arguments" (wich we programmers cound't find a cool name for it still)
This is out of the scope of this tutorial, first use the functions on "easy" then you can improve yourself.
Oh, and if you ask, yes functions can be chained or combined on your sentences:
var result = myFunction(2, 3) + myFunction( myFunction(4, 5), 32 );Yay! function madness! YOU HAVE NO IDEA ...
Functions have more ins and outs, like what does 'this' means? Wich I'll cover when we see what objects are.
Still you can solve pretty much anything and you don't even have to reppeat your code over and over, because you can loop something or make it as a function.
Do you want an excersise? well, this one is easy and will use all you learned so far:
Write a function called fizzBuzz when I pass as an argument a number. Your function must count from 1 to the number I give (inclusive) and show each number, except on some cases:
if you can divide a number by 3, you should print Fizz.
if you can divide a number by 5, you should print Buzz.
if you can divide a number by 3 and 5, you should print FizzBuzz.
if none of the conditions are met remeber, just print the number.
"you can divide a number by other" if the remainder of the operation is 0, wich means, 2 is not divisible by 3, nor 5 is divisible by 3, 6 is because 6 / 3 is 2 and you have no remainder.
Here are some tips to help you:
You can print a number with a pop up window using 'alert( something )' (wich is annoying) or with 'console.log( something )'
(hey, what does the console.log means... ? shh, this is going to a future lesson, so please, let's avoid this by now and write it like that)
You can divide numbers using '/' a / b means "a divided by b".
You can also get the remainder with '%'
a % b means "I want to get the remainder of a / b", so "7 % 2" is 1 because:
7 / 2 is 3 (as integers, so ignore decimals here) and "(3 * 2) + 1 = 7"...
Try to do it in a way in wich if I call "fizzBuzz(37)" will print 1, 2, Fizz, 4, Buzz, Fizz, etc, etc...
Lesson 4: Arrays
What are arrays ?, well as I said, arrays are just a bunch of things on an specific order.
You can use them as sets or collections, wich is how you usually use them.
Arrays are easy to create in javascript, you just need to write a list of things inside a pair of brackets:
var myArray = [ 1, 2, 3, 4 ]; // we already did this...Now, you know, you may want to get a value from an array, like many languages, getting an array or setting it is done via something people call subscripting:
var result = myArray[0]; // This will give you the first element on the array (1 in the other array)myArray[0] = 2; // This will put inside the array at index 0 (the first one) the value 2Notice how to get or set something you use a pair of brackets too.
Arrays are one of the reasons (wait, yes, there is more) why I said "It's not true than variables can only contain 1 thing" they can contain arrays, so they can contain an array with many things inside.
Arrays can also be inside another arrays, so you can have:
[ [1, 3], [2, 4], [7, 9] ]At the moment, lets imagine we are using fixed size arrays (yes, you can add or remove a value), but this is for a good reason, because we didn't talk about objects, and arrays are a special type of object.
Also remember this, arrays count its first element as 0, not 1, so you start counting from 0 to the size - 1,
In other words, an array with 10 items has values from 0 upto 9 (inclusive).
Why I decided to teach you array first, well that is because on many languages this is not true, and objects are more complex than arrays to understand.
So, there you are, you can now sotre a bunch of something, check if something is equal to other things, repeat a bunch of code, call functions, you are practically done.
Yes javascript doesn't have that complexity if you just cut the bases appart from each other.
Lesson 5: A world of Objects
Now its the time to talk about what objects are.
Of course, objects are the main reason this language is called an 'object oriented language', so they must be important right?
Well yes, and I have to say to you, you already worked with some already.
While the "type" of a number is not an object, not an array, or even a boolean, they are all objects in the terms of the language.
(yes, yes, they are wrapped and blah blah blah blah, but for the sake of simplicity, lets think they are please)
So, what are objects you ask?
Well you can think an object is something you can represent as an entity, as something or someone in your code. For example, a function, a person, an animal, a type, etc.
So if you want to think objects easy, think of them as dictionaries, they contain words, associated with a definition.
Here our definitions are other objects (or, as you may think, numbers, functions, etc)
They work really, really similar to arrays in that sense, but think than it can work with more than just numbers.
var anObject = {}; // note the {}, this is an empty objectanObject.value = 23; // yes, you can put things inside this wayalert(anObject.value) // you also can get the values the same wayanObject['value']; // you can also get the value this wayvar name = 'value';anObject[name]; // you can even use any type of expression inside.Do you notice something ?, yes, they work like arrays too, but with strings or words... so yes, as you may discovered, Arrays were just objects with numbers as keys.
This, of coursewqorks on many ways, imagine if you have a character:
var myCharacter = {};myCharacter.name = 'Frederic';myCharacter.hp = 30;myCharacter.atk = 5;Why not?
But you can also create objects with properties already inside, this will do the same as above:
var myCharacter = { name: 'Frederic', hp: 30, atk: 5};Objects also have 'behaviour' or in another way to say it, methods.
Methods represents what an object can do.
var myObject { jump: function () { /* a bit of code here... */ } };myObject.jump(); // just like normal functions, you call it the same way.And this is where the tricky part comes, sometimes you may want to have a reference to the object itself, so there is an easy way to do this, with a keyword called 'this'
var hero = { isJumping: false};hero.jump = function () { this.isJumping = true;};hero.land = function () { this.isJumping = false;};so then, 'this' is more complicated than just this tutorial, it has some js thingies than you may want to ignore for now...
But for the moment consider it as a "reference" to the object you are working with.
Now you have learned what are objects, and how you can create them, now there is no limit you can do.
But hey, did I mension programmers are lazy ? Do you want to know what are the advantages of using objects ?
Do you want to think a way to not do again and again and again the same objects?
Well, the next lesson will teach you just that, something called prototyping wich is like the reason why javascript is so popular.
Lesson 6: "Prototyping and classes"
Here goes
Lesson 7: Final exam
Here goes
See ya!