Here’s a good guide to get you started on Javascript in a practical way.
Why another guide?
- Practical - don’t learn for the sake of learning, learn for the sake of doing!
- Tactical - learn what matters, fast (yes, that’s what everyone says)
- Strategic - see the big picture
This guide will get you started from the beginning, graduate you to using industry standard tools, and point you towards the right direction for learning even more than what can be offered in one guide or course.
What makes me qualified?
I have been using Javascript since late 90’s, and am absolutely in love with the language. I was an avid hobbyist developer using JS in packaged products, and after 15 years of doing that changed into a full-stack developer and consultant creating web-based technology products and services.
In summary - nothing that qualifies me to an epic level, but I do have a thing or two to share.
Who is this guide for?
This guide is intended for folks who want a practical introduction to Javascript.
If you are a developer in any language, it is highly likely that you have used Javascript in some shape and form, and may not find it super interesting to start from the beginning.
The Many Faces of Javascript
Javascript started as the language for the web - automating web pages and bringing interactivity to clients using a browser. It is the only language that does that to this day at the browser level (though things are changing fast). But, JS has grown much much more - for everything from pushing boundaries on interactivity over web to making animations, drawing charts, and creating desktop and mobile apps.
Javascript can today run on web, desktop and such typical computing devices, mobile phones, on embedded devices. The evolving standards have made it easier to learn and scale the language to newer heights.
Get Started
Why, in the web of course.
- Take the first steps by learning how Javascript can be used today and how you can create your own magic with a few lines of code.
- Create the first few projects using just Javascript
- Graduate to using a full-fledged development environment and create more projects
My goal is to make this guide as practical as possible - hence the focus on projects. You may enjoy the guide more if you follow along.
Tools of Trade
Before delving further, let’s set everything up for our journey.
We will begin our journey with a simple tool - no installation required. Just start using one of the below tools -
You may optionally sign up for a free account in either (or both?) of the services.
Later on we will start using a code editor - VSCode. Code along and see working examples hosted on Github.
Start Coding
Javascript works beautifully in web - it plays along well with HTML (Hyper Text Markup Language - the language to create the user interface of web pages) and CSS (cascading style sheets - style the webpage).
A typical example will look like this ..
-
Create a file called
index.html
.1 2 3 4 5 6 7 8 9
<html> <head> <link rel="stylesheet" href="style.css" /> <script type="text/javascript" src="./script.js"></script> </head> <body> <h1>Hello World</h1> </body> </html>
-
Create another file called
style.css
.1 2 3
h1 { color: blue; }
-
Create yet another file called
script.js
.1
alert("hello world");
Open the HTML page to see a page with the hello world
message that shows dialog box when it is loaded (or refreshed).
Congratulations of your first line of Javascript!
The structure represents how today’s web works. When you visit a web page -
- Your browser downloads HTML, Javascript and CSS
- Renders HTML page and applies styles
- Applies Javascript logic to change content, add/change styles or respond to user actions
Since everything described above is user-facing and “front-ends” the application, Javascript is associated with “frontend” languages that deals with user interfaces and interaction.
But, when you run Javascript in other modes (for e.g. in desktop or mobile phones), it is executed by some form of NodeJS. Node is a Javascript runtime engine that will execute Javascript on the device and can function without any interaction with HTML/CSS layers. This execution can happen on your machine (hence executing any code that you type), on web servers that serve websites, on desktop or mobiles using frameworks that encapsulate Node. Node enables Javascript execution in the backend.
Executing Javascript in frontend is optional - but you have to deal with limited user interactivity. You can just have styled static pages without supporting any dynamic interactions. Similarly, you can have all the frontend functions without using any Javascript in the backend (e.g. you could use PHP, Go or some other language for servers).
Let’s get back to our project at hand. Instead of creating all the required files locally we can make our life easier for now and use one of the online tools - e.g. Webmaker. Just go to the site, click on New
> Start Blank
. Add the content of the html
, js
and css
in the various panes - you don’t need to reference the files since they are already tied together. Double click on the Console
pane to see the console output - this is where you can see output from Javascript execution regardless of what is on the HTML page.
If you are using codepen
- choose Create Pen
from the left sidebar. Replace the content of the panes with what you used earlier to see the same beautiful page! You can see the console by clicking on the Console
button at the bottom of the page.
Find Codepen for the above example here. Just open code pen to execute the code.
Webmaker app and Codepen execute your code as you type the lines - so don’t get surprised with errors when you stop typing for any reason.
Since we will not be using HTML and CSS as much, you will refer the JS pane and console for the most part.
I will use Codepen specific references here on, but the actions are similar in any other tool incl. Webmaker.
You can start creating new pens for trying out the examples. You can find all the examples from this guide in a Codepen collection.
Viewing Output
We previously had a single line of code. We will start building up on top of that.
|
|
console
is an easy way to print a message during code execution. In a browser you can see console output in web developer tools (e.g. Ctrl + Shift + I to developer tools > head over to Console
tab). In Codepen, you simply click the Console
button to show console - this is hidden by default.
When the browser (or runtime) executes Javascript, it just executes statements one line after the another. Javascript is an “interpreted” language since the code is not compiled to any intermittent state before execution. The tool ecosystem is quite powerful to make you forget that to an extent - but keep that in mind.
You can also do simple (or complex operations when you print output).
|
|
See the //
? That is a comment. Comments are ways for other humans (and future you) to understand code. Comments are ignored by the runtime - they are not executed, but just sit there in the code.
Comments can be single or multiple line.
|
|
Variables and Types
A variable is a temporary storage location for your program. You can assign a “value” to a variable, recall the value at a later time, and process the variable like you would process the data.
Creating a variable (“declaring variable”) and assigning a value is as simple as -
|
|
Variables can be used to carry out operations similar to what we did earlier.
|
|
The values that remain constant (e.g. 1, 2) are called “constants”. Constants can be assigned to variables and used in any calculations along with variables.
|
|
You can also do -
|
|
While Javascript allows you to assign variables as and when you please, modern build tools may not always agree with you. It is a good idea to “declare” a variable explicitly by using var
, const
or let
keywords.
|
|
Keywords in a programming language are words that denote special meaning. In the above e.g. var
declares a variable called num
. You cannot use keywords as variable names.
The below code will not work.
|
|
Other keywords include words to check conditions (e.g. if
, else
), specify conditions to run code “in a loop”, i.e., execute code repeatedly until a condition is satisfied (e.g. while
, for
), and more. See the complete list of Javascript keywords on MDN.
When you declare a variable using const
you cannot reassign values to that variable. Other than that the different declarations differ in how variable values are made available at different locations within the code. We will revisit this later.
You may have also observed that we did not specify if a given variable stores
- a number (for e.g. 1, 2, or 33)
- a string (e.g. “Peter Parker”)
- or something else.
number
, string
etc. are called variable “types”.
You cannot specify types in your code. Javascript provides “implicit types”, which is just a fancy way of saying that the Javascript runtime looks at the variable value and assumes a type for the variable.
You can see the “deduced type” using typeof
keyword.
|
|
As you can see there are no specific types for decimals, whole numbers or negative integers - all of them are simply number
. Similarly any number of characters will denote a string
type.
Let us see more types.
|
|
The last statement is just an equality check to ask runtime to check whether nothing
is null
, and therefore the result is true.
There are two more types - bigint
(for handling large integers) and symbol
(for handling symbols).
There are also special values called NaN
and Infinity
which are of number types but not really numbers.
|
|
While one may initially think that using no types in a programming language is easier (it is indeed..), no explicit types may lead to unexpected results and hard-to-debug issues. More over, invalid operations like dividing a string by number cannot be caught during development (during “compilation”) since types are not deduced until runtime.
For e.g.,
|
|
When you add a string to a number, Javascript automatically converts the integer to a “more complex” string type and combines the two (“+” operator can work on numbers as well as strings).
Conversion of types is supported across the board in Javascript. There are so many use cases that there are even shortcuts for type conversion.
Consider below examples.
|
|
In fact, I used different variables for strA
and numA
for demonstration purposes. Nothing prevents me from using the same variable name. During program execution Javascript points the variable to a new storage location with number type in the background.
Also, did you also observe that we used string variables using a double quote ("
), but assigned a number without quotes? Strings can be quoted with single or double quotes, rest of the types (or objects) are not.
|
|
Instead of quotes, we can also use ``` - these are called as string literals and are awesome.
Remember how we printed out the values earlier?
|
|
We can do the same thing by using string literals -
|
|
You can also do simple calculations within the string literals with or without using string literals.
|
|
The final variable types we will talk about is null
and undefined
.
null
assigns a null value to a variable - it does exactly what it sounds like. Variable is assigned a value null
!
|
|
Null can be assigned to any types and is commonly used in checking for a valid value in the variable.
Undefined, on the other hand, just tells us that a variable is not defined.
|
|
null
= no value in variable
undefined
= variable has not been defined
See this Codepen for working examples..
Operations and Operators
An operation is just a term to process data and obtain an end result. An operation can include -
- One or more variables
- One or more constants
- One or more operators
Arithmetic Operators
Simple arithmetic operations are supported out of the box in Javascript.
|
|
You can use more than one operators in one go -
|
|
See this Codepen for working examples.
See more arithmetic operators here.
Comparison Operators
Comparison operators help you to compare between two values.
|
|
Comparison operators always return a boolean.
Common use cases for comparison operators is are in conditional statements that are used to execute specific code blocks.
A simple e.g.:
|
|
The implicit type deductions in Javascript may not always be intuitive for people from other languages. For e.g. you can compare a 3
(number) with "3"
(string), and the results will be “equal”.
|
|
Javascript converts the types and keeps you happily chugging along. But, there can be places where you want to avoid this type of comparison.
For e.g.
|
|
.. or in situations like this..
|
|
We can use strict comparison operators to force Javascript to consider types as well as values.
|
|
Logical Operators
So far we have seen one comparison being made at a time.
|
|
Real-world problems can have more than one condition to check. What if you want to check if a
is greater than 0
and also less than 5
? You can do that using logical operators.
|
|
&&
represents the AND
operator. It results in true
only if all expressions used in AND
expression are true.
Other logical operators :
OR
-||
: results intrue
if any value istrue
NOT
-!
: unary operator. Just reverses the result -true
tofalse
or otherwise.
You can mix and match logical operators and any other operators in an expression.
|
|
Consider one more example using simple conditional statements.
|
|
Collections
Collections are just bringing variables and values together in one group.
Arrays
The most common collection is an array
. We can create arrays with same type of variables, constants, other arrays, or any objects.
|
|
You can access any or all elements of an array.
|
|
An array can be -
- Artists in an album
const wow=["Kula Shaker", "Deep Purple"]
- List of students in a class
const class = ["Kent", "Parker"]
- Or any collection, really. We keep related elements since we want to group things and process them with code.
Below is an example of an array with seemingly unrelated stuff.
|
|
We discussed methods and how they are applicable to specific objects. Arrays have their own special methods too.
|
|
There are also shift
and unshift
methods that work similar to pop
and push
but do that at the beginning of the array.
Strings are nothing but arrays of characters. You could apply arrays-specific methods like length
to strings as well.
|
|
See this MDN page to read more on arrays.
Objects
An object is a collection of one or more key-value pairs called “properties”.
Example -
|
|
Here name
, age
and class
are props of student
object. Note that property name (the key) is unique.
Do you remember that we saw earlier that almost everything is an object? This was the “object” we were referring to all along. Every primitive, function or any other Javascript entity is an object and has its properties.
You can get an individual property value by -
|
|
You would have seen by now that objects are similar to arrays in that they group stuff together. The keys are ordered in arrays, and they are not controlled by you. Objects enable you to have your own keys and use it too, but the order of key/value pairs is not maintained or guaranteed.
You can have collection of collections. For e.g. an array of objects can be declared with following code -
|
|
How do you refer individual student? Follow the pattern followed for an array and for an object.
|
|
Examples for collections are in this Codepen.
There are other types of collections too - namely sets and maps. But, we will not go into that right now.
Conditional Statements
A conditional statement enables execution of different code based on given set of conditions.
if-else
We have already seen a simple if
example -
|
|
console.log("a is one");
is executed only if a
== 1.
You can pair if
with else
, and also use more than one if
.
|
|
- Execute first block of code if
a
is1
- Execute second block of code if
a
is0
. - Execute third block of code for all other conditions
Only one block is executed at any time with an if/else-if/else
block.
You can also “nest” if
statements.
|
|
Did you also observe that I left out {}
for else
. This is perfectly valid if you have only one statement in the if
or else
blocks.
Consider another example where you want to provide free admittance to kids and seniors > 70 years.
|
|
Since we already know the logical operators can be combined, we can simplify it to -
|
|
switch
You can use switch
to provide a readable conditional block. It functions similar to an if
/else if
block.
We can rewrite the earlier if
example as -
|
|
default
block is executed if none of the case
statements get satisfied, and hence is at the very end of switch
.
You also observe break
in all case
blocks. This is by design. If you don’t use break
the control starts going through the next case
block and executes the block if it satisfies the condition.
For e.g..
|
|
A lot of people argue that using switch
is more readable than a series of if
/else if
statements, and faster to execute. I tend to agree with them on the former.
Loops
Loops enable us to repeat “stuff”.
So far we have seen trying to add numbers, printing messages and doing other great things. But, what if we have 10s or 100s of numbers to add, print dozens of messages, or do greater things?
Enter loops. There are different types of loops available in Javascript.
while
A while
executes a block of code until a given condition is satisfied.
|
|
In the loop -
- create a variable called
i
, initialise it to0
- start
while
loop to repeat code within brackets untili
is less than5
- within the loop, print a message and increment
i
(else the loop will run indefinitely)
do-while
There is an alternative to while
to execute the code block at least once and repeat till the given condition is not satisfied.
|
|
While the above code has similar output as the earlier while
loop, the following block of code is repeated once and only once (even though the while
loop condition was not satisfied).
|
|
for
A for
loop allows limited execution of a block of code until a specific count is reached.
|
|
While the for
loop does a similar job as a while
loop, it functions a tad differently.
-
initiate a
for
loop- a variable and a value from where we need to start the loop. We declared
i
infor
while initiating loop itself, but it can be declared earlier in the code as well.i
was initiated to0
- specify when to stop. Thiscify the condition to be true for the loop to continue.
i < 5
specified that the loop code should execute untili
was less than5
- what should we do after each iteration of loop. Here we increment
i
. We have used a unary operatori++
instead of writingi=i+1
. You can count up or count down with any number (for e.g.i=i+10
will incrementi
by10
after each iteration)
- a variable and a value from where we need to start the loop. We declared
-
for
loop will also feature a block of code that needs to be executed until the specified condition holdstrue
. We just print a message
Loops for Collections
We have seen about collections earlier. We can combine that knowledge with loops to iterate through every element in a collection.
for
is quite a common sight to work with arrays.
|
|
There is also a variation of for
loop to iterate through arrays - for
/of
loop.
|
|
One of the popular ways of iterating objects is by using a variation of for
loop - for
/ in
.
|
|
Functions
Function is a block of code that performs a task. A function allows us to write reusable code.
Take our earlier example of getting a sum of two numbers.
|
|
Now, what happens if you also want the multiplication result?
|
|
You could go on and on with the calculations and make your code hard to understand. Or, you could keep it simple by organizing code into functions.
Let us rewrite the code using functions to get sum, get product or do something else.
|
|
The block of code starting with function
keyword is called the function definition. You define a function like so -
|
|
A function can have zero or more “arguments” - these are values passed to the function (like x
, y
). A function may “return” a value or just execute some logic and not return anything.
You can then call this function from anywhere (provided the function is accessible from that place) -
|
|
While the function existed all this time, we execute the code only when we call that function. The function will take the arguments, total them and return the sum
. We store the returned value in total
.
You also see that we have used x
and y
in more than one function. The variables passed as arguments or those created within the function are available only in that function. There will be a larger discussion about “scopes” or when you are able to access a variable within functions soon.
Methods
Methods are just functions that belong to a “object”. Javascript treats (almost) everything (variables, constants, functions, etc.) as an object. So, it follows that there are specific methods available against objects.
Consider this example to change case of a string.
|
|
Similarly, we can have a rounding-off method to display a formatted number.
|
|
Note that the method does not change the original value unless explicitly instructed to do so.
|
|
Examples for functions and methods are available in this Codepen.
See complete reference for string methods, number methods and more on MDN.
Graduating to Next Level: Set up
So far we have executed projects by using online editors and had fun doing that. But, real-world projects can get complex with a lot of files, need a lot of space, or you may simply want to work on projects offline without typing in the browser.
We code Javascript using -
- Code editors - we live by VS Code
- NodeJS - executes Javascript locally on your computer and makes it easier to debug. Further, tools are built on top of Node to build and deploy projects over web, or for various devices
Download both tools and install them on your computer by following the instructions on the respective websites.
Create a new folder on your computer and open that folder in VSCode (File
> Open Folder
).
You can now start creating Javascript files (with suffix .js
). Right click on the folder name in the left pane, click New File
and name the file as hello.js
. Enter this line in the file -
|
|
You can execute this Javascript using Node. Go to Terminal
> New Terminal
in VSCode to open a new terminal.
Type -
|
|
The command outputs hello
.
Subsequent examples assume that you are using Node. Each time -
- You will create a file (or change existing file)
- Execute Javascript with
node <file_name>
in Terminal - See result in Terminal
Most of these examples are simple enough to work on Codepen too - so you can continue that. But, as you get more into Node you will find it faster and easier to type stuff local to your computer and execute them.
If you are using a browser, the browser itself executes the Javascript and there is no Node involved. Node facilitates execution of Javascript on your computer without a browser. There are other ways to execute Javascript on your computer - including Deno but we will use Node for now.
Now, you can just created a Javascript file - say “hello.js”..
|
|
Open a command prompt (within VSCode or otherwise), go to directory of the file, and execute it to see the output.
|
|
Now, you can create and execute any Javascript!
Projects
You can create these projects using Codepen or on your local computer.
Print numbers from 10 to 20
As the title says - just use console.log
to print numbers.
Print numbers between 100 to 200 that are fully divisible by 7.
Explore options to get numbers in multiples of 7.
- Get the first number after a given number (100 in our case) that is fully divisible by 7. Print the numbers by adding 7 in a loop until the max number is reached (200 in our case)
- Use modulo operator to get the first number divisible by 7 - then use logic similar to above
Calculate sum of numbers between 10 and 25
Calculate sum of numbers - 10 + 11 + 12 + 13 + … + 25
Find average and maximum with a given array
Assume the input array to be [10, 12, 15, 17, 5, 19]
.
- Calculate sum of all numbers
- Calculate average (sum of all numbers divided by the count of numbers)
Reverse numbers
Assume the input array to be [10, 12, 15, 17, 5, 19]
.
- Reverse the array -
[19, 5, 17...,10]
- Sort array in descending order
Array comparison
Take two arrays as input.
- assume
[1,5,7,11,23,19]
,[8,11,23,1,21,25]
- output numbers that are in one array or the other, but not both
- output numbers that are in both arrays
Create a palindrome checker
Create a palindrome checker and output whether a given word is a palindrome.
- Method will take a valid string input
- Check palindrome
- Return
true
orfalse
Create a ROT13 encryption encoder and decoder
ROT13 replaces a letter with the letter 13 letters after it in the alphabet. See this (example](https://rot13.com/).
- Accept an input string and encrypt with ROT13 encryption
- Decode a string using similar algorithm
Object to array printer
Given an object -
- print in the format [
key1:val1
,key2:val2
…] for all keys - print all keys and all values in two separate arrays
Create a simple calculator
This uses both HTML and Javascript. Skip this project if you are not familiar with HTML.
- Enable user to select numbers, brackets and arithmetic operators - use HTML
- Optionally use a simple to use library like MVP.css. Just include the stylesheet in your HTML - you don’t need to learn CSS
- Display results
- User should be able to continue calculations with the result or clear it to perform new calculations
Next Steps
So far you have seen the basics of Javascript -
- get to know how to start writing Javascript
- variables and types
- conditional statements
- loops
We have not coded frontend or written any apps, but we will get there. A few resources to help you on your journey -