The first document in this series, related to getting started with programming
Here are a few concepts that you should know before getting started with programming.
Most languages require a way to determine the end of a line of code. It's the ;
symbol mostly, called as a semi-colon. Although in JavaScript, statement terminators aren't mandatory, they are still suggested to be used. Since most popular languages require statement terminators, like C/C++, C#, PHP, Java, and a lot more, so it's a good habit to use them, so that you don't start forgetting to use them when you start programming in these languages later on.
I don't use them in JavaScript, and I regret it; it always wastes a lot of my time when I forget to put a semi-colon when programming in PHP or so.
Any sort of custom text value in programming is always refered to as a string. Strings are always enclosed in some form of quotes, so next time you hear the word string, you should know what to do there. You will learn more about handling strings later.
Comments are lines of code which are not executed. They are used to leave notes around parts of codes, for easy recognition. They are represented by a grey color in code editors, and are written using a //
:
// This is a comment, This will not be executed
If you want to add a comment that spans multiple lines, then that is possible by a pair of /*
and */
. Anything enclosed in them will be treated as a comment:
/*
This is a comment that
spans multiple lines on
the screen, and will not
be executed.
*/
First of all, you should know how you can print stuff to the user. Every language has some sort of printing function. For JavaScript, it's the console.log
function. Here's how to use it:
// Syntax:
console.log(text);
Where text
is a string, which represents your choice of text. Your text must be enclosed in quotes (""
or ''
):
console.log("I'm learning JavaScript :)");
console.log('Hello, "World"!'); // Using single quotes
You can try running the above lines and modify them however you want from the Console.
This may seem a bit complicated when you hear it, but it is in fact really simple:
// Syntax:
alert(text);
Where text
text is a string of the text you want to be displayed.
alert("I am in an alert box! :D");
This will display a popup box above the webpage, and gives an OK
option with it.
Use the alert
function to alert out the text: I love JavaScript (even if you don't).
Use the console to run your code.
The entities that hold data in a program are called variables. Variables can contain various kinds of data, like numbers, strings, arrays, objects, and more. Variables have lots of data types, and are the first concept that you learn in programming.
Variables are like math variables; a name which holds a value. Like x
contains a value of 2
. With variables your program can keep track of the current state of the program. Variables are a concept in every language. In JavaScript, variables are declared like this:
var x = 2;
// Now x holds a value of 2
When the above line is executed, a section in your memory is allocated for this variable to sit, and hold it's value. Different langauges have different methods of storing their variables, but you don't need to care about that at this stage.
The value of a variable can be changed by this:
var cars = 4; // Say you have 4 cars,
// But now you have another one,
// You can change its value
cars = 5 // Now the cars variable will have the value 5
Since variables are basically values, you can also use console.log
to print the value of a variable as well:
var greetings = "Welcome!";
console.log(greetings); // Will print "Welcome!"
alert(greetings); // Will show "Welcome!" in an alert box
The definition of a variable can have a number of variations, made by different requirements. They are explained below:
The very first word that you use when declaring a variable has a number of types. They can change the way a variable behaves.
var x = 2;
const name = "Thomas";
let favouriteFruit = "Apple";
var
keyword:It makes regular form of a variable. Nothing else to care about, it simply creates a variable. This is what you'll mostly need:
var age = 10; // not really tho :)
let
keyword:The let
keyword makes a variable, that can not be declared again. If they are declared again, you receive an error:
let fruits = 5; // fruits now contains value 5
let fruits = "None"; // Will throw an error:
// SyntaxError: Identifier 'fruits' has already been declared
const
keyword:The value of a variable declared with the const
keyword cannot be modified once it's declared (An error will be thrown upon an attempt). These variables are used to hold data that will stay constant throughout the working of an application. Like API Keys, name of the app, etc.
const appName = "Pizza App";
appName = "MyPizzaApp"; // Will throw an error:
// TypeError: Assignment to constant variable.
Because it's JavaScript, i's not required to use these prefixes to achieve a variable at all. You can simply do this;
name = "Thomas";
and the variable will be created. But it's deeply discouraged to do it this way, and it might cause problems, so it's better to use something like var
if you want to create a variable.
Declare a variable with the value being your name. Then use console.log
to print that value out.
Use the console to run your code.
There are a lot of different types of data you can store in a variable. In strict languages like C++, Java, C#, etc., a variable of one type is bound to it's own; such that it can't easily interact with other variables of varying data types.
Though, in JavaScript, the procedure is a lot less strict. Data types are not required to be specified. This may seem good news at first, but this sometimes causes headaches due to it. This is because of the clumsiness of JavaScript.
Anyway, here goes the list of data types of variables:
You have already read about strings in the upper topic:
''
), double quotes (""
) or backticks (``
).
var lipsum = `
Lorem ipsum dolor sit, amet consectetur adipisicing elit.
Necessitatibus nulla consequuntur vitae aperiam laboriosam
quo at molestias eum placeat error voluptas, labore magnam?
Modi ab sapiente et commodi, totam nihil.
`; // Works fine
var lipsumWithQuotes = "
Lorem ipsum dolor sit amet consectetur adipisicing elit.
Aut laudantium iure officia rem maxime minima eius!
Maxime corporis nobis ad, repellendus, similique quae
maiores eum amet beatae eaque illo nisi.
"; // SyntaxError: Invalid or unexpected token
Sometimes a combination of characters refer to an item, which is not easy to handle as itself, like new lines and tabs. In programming, these are written with a \n
and \t
respectively (\n
for a new line and \t
for a tab).
var indentedText = "\n\tThis is some text with an indent.\n";
console.log(indentedText); /*
This is some text with an indent.
*/
There are probably a lot more character combinations like this, but only these two are relevant.
But what if you want to, let's say, do something evil like printing a \n
as it's own. Like you want to see the symbol itself? Or, let's say you want to console.log
out all the three types of quotes, something like "'`
? Can you do that?
console.log(` "'` `);
// Uh it doesn't seem to look fine doesn't it?
Here comes escaping. Escaping means to "escape" the actual purpose of a symbol, and specify it as itself. It's not used much, but when it is, it becomes sort of a headache. Escaping is a common concept in most programming languages, and it's achieved by placing a \
(backslash) character before the character you want to escape. Once done, the escaped character will become part of the string:
console.log("\\n"); // Prints: \n
console.log("\"'`"); // Prints: "'`
// This one looks complicated, so you can look at a simpler example below:
console.log("\"\""); // Prints: ""
// The two slashes prevent the quotes after them from closing the string quotes, and make them the part of the string.
If this seems complicated to you, then you can easily skip it for now. Since at this level, you don't need to get into escaping yet, since you are not going to be playing with quotes at this level (even if you are, you can simply use a different pair of quotes).
Numbers are, um, numbers. They behave like math numbers, so detailed explaination is not required. Arithmatic operators work as usual too:
var apples = 6;
var bananas = 4;
var fruits = apples + bananas;
console.log(fruits); // Prints 10
var totalStudents = 60;
var boys = 40;
var girls = totalStudents - boys;
console.log(girls); // Prints 20
var a = 12;
var b = 4;
console.log(a * b); // Multiplication: Prints 48
console.log(a / b); // Division: Prints 3
Try it yourself and see what happens.
Increasing or decreasing the value of a number by one is easy, and it has shortcuts too.
+=
:
var x = 3;
x += 2; // 2 is added to 3, i.e., 2 + 3, and x is now 5
console.log(x); // Prints 5
// -= works in the same way too:
x -= 3; // 3 is subtracted from 5, i.e., 5 - 3, and x is now 2
console.log(x); // Prints 2
++
or --
operator respectively:
var x = 3;
x++; // 3 is increased by 1, i.e., 3 + 1, and x is now 4
console.log(x); // Prints 4
// -- works in the same way too:
x--; // 4 is decreased by 1, i.e., 4 - 1, and x is now 3
console.log(x); // Prints 3
Here's a table of how these shortcuts are working:
Shortcut | Same as |
---|---|
x += 2; |
x = x + 2; |
x -= 2; |
x = x - 2; |
x++; |
x = x + 1; |
x--; |
x = x - 1; |
Booleans are the simplest form of data types, which only have two possible values; true
or false
. It cannot contain any other quantity. Booleans are used to make decisions in if-else statements (you will learn about them later), loops, and a lot more.
var isJavaScriptFun = true;
var isDocumentGood = false; // :(
var areApplesSweet = true;
The definition of a boolean variable is described here. You will use booleans and learn more about them in a later document.
There are some values which are neither of the above, but they exist on their own, these are:
Type | Description |
---|---|
| Indicates that the variable is defined to be null, can be used to convey that no data is returned. |
| Indicates that the variable is not properly defined. undefined and null are similar in ways but undefined gets a bit harder to handle. |
| Stands for Not a Number. Forms when a number is moulded into weirder terms. E.g., when a pure string is converted to a number, NaN is returned. Use isNaN(value) function to check if a certain value is NaN , since simple comparisons on NaN simply don't work. |
| Seen less frequently. Forms when a number is divided by zero. |
Concatenation simply means to join values together. It's a really simple process, but sometimes gets a bit confusing. Here's a few combinations in practice:
String values can easily be concatenated by using the +
symbol:
var name = "Thomas";
console.log("Hello " + name); // Prints out "Hello Thomas"
The concatenated value can be stored into a variable as well:
var name = "Thomas";
var greetings = "Hello " + name; // Storing the joined value
console.log(greetings); // Prints out "Hello Thomas"
Multiple values can be concatenated too:
var name = "Thomas";
var age = 10;
var favouriteFruit = "Apple";
console.log("Hi, I am " + name + ", " + age + " years old, and my favourite fruit is " + favouriteFruit + ".");
// "Hi, I am Thomas, 10 years old, and my favourite fruit is Apple."
Concatenating numbers can be a little confusing, since the +
operator is used for adding numbers and concatenating. If you try to concatenate numbers like strings:
var num1 = 5;
var num2 = 7;
console.log(num1 + num2); // Prints 12
We get their sum. How do we concatenate them now?
An easy way that I use is this; First, convert each of them into a string, then do normal string concatenation. The conversion can be achieved in a number of ways:
var num1 = 5;
var num2 = 7;
console.log( (num1 + "") + (num2 + "") ); // Prints 57
What is happening here?
1 + ""
will be a string "1"
, which is friendly for concatenating.)
A shortcut for this will be:
var num1 = 5;
var num2 = 7;
console.log(num1 + "" + num2); // Also prints 57
There are 4 apples and 6 bananas in the bag. Such that var apples = 4;
and var bananas = 6;
.
Print a statement, which shows the total number of fruits using addition, somehting like "There are 10 fruits in the bag."
You learned:
//
or wrapping the desired code in a /* */
block.console.log
and alert
can be used to view output to the user. alert
shows an interactable alert box.\n
and \t
can be used to insert special characters like newlines and tabs.true
or a false
in a program.+
symbol between two values.Make sure that you understand most of the stuff in the document (if you don't, it's okay, you'll get it later) and try to practice these as much as you can. Try new things, like concatenating an undefiend
with a string and see what happens, or try to find the difference of using var
and declaring a variable without any prefix. Once done, you are welcome to move to the next document :)
Please try to do them yourself before consulting these answers :(
alert("I love JavaScript");
var name = "Thomas";
console.log(name);
var a = 12;
console.log(a / 0); // Prints Infinity
var apples = 4;
var bananas = 6;
var totalFruits = apples + bananas;
console.log("There are " + totalFruits + " fruits in the bag.");