This page looks best with JavaScript enabled

Javascript - A Beginner Guide

 ·   ·  ☕ 30 min read

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.

  1. 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.
  2. Create the first few projects using just Javascript
  3. 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 ..

  1. 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>
    
  2. Create another file called style.css.

    1
    2
    3
    
    h1 {
      color: blue;
    }
    
  3. 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).

hello-world-javascript-html

Congratulations of your first line of Javascript!

The structure represents how today’s web works. When you visit a web page -

  1. Your browser downloads HTML, Javascript and CSS
  2. Renders HTML page and applies styles
  3. 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.

codepen-html-js-hello-world

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.

1
2
console.log("hello world");
console.log("you are awesome");

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).

1
2
3
4
5
console.log("sum: ", 1 + 2);
// sum: 3

console.log("The answer to all questions is ", 6 * 8);
// The answer to all questions is 42

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.

1
2
3
4
5
6
7
// single line comment

/*

    Multiple line comment
    ...
*/

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 -

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
a = 1;
console.log("a:", a);

// output
// a: 1

// reassign value
a = 2;
console.log("a next:", a);
// output
// a next: 2

Variables can be used to carry out operations similar to what we did earlier.

1
2
3
4
a = 1;
b = 2;

console.log("sum:", a + b);

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.

1
2
3
4
n = 3;
console.log("double:", n * 2);
// output
// double: 6

You can also do -

1
2
3
4
name = "Peter Parker";
console.log("My name is ", name);
// output
// My name is Peter Parker

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.

1
2
3
4
var num = 1;
console.log("num: ", num);
// output
// num: 1

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.

1
2
var var = 1;
// error

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
num1 = 1;
num2 = 3.14;
num3 = -10;
strWorld = "world";
strW = "w";

console.log(
  typeof num2,
  typeof num2,
  typeof num3,
  typeof strWorld,
  typeof strW
);
// "number" "number" "number" "string" "string"

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.

1
2
3
4
5
result = true; // there are no quotes around `true`
let nothing = null;

console.log(typeof result, typeof realResult, typeof nothing, nothing == null);
// "boolean" "undefined" "object" true

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.

1
2
3
4
5
6
7
8
9
let noNum;
let half = noNum / 2;
console.log(half); // NaN
console.log(typeof half); // number

console.log("abc" * 2); // NaN

console.log(2 / 0); // Infinity
console.log(typeof (2 / 0)); // number

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.,

1
2
3
let str1 = "hello";
console.log(str1 + 2);
// hello2

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.

1
2
3
4
5
const strA = "1";
console.log(strA, typeof strA); // "1" "string"

const numA = Number(strA); // 1
console.log(numA, typeof numA); // 1 "number"

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.

1
2
3
hello = "world"; // string
x = 1; // number
isAwesome = true; // boolean

Instead of quotes, we can also use ``` - these are called as string literals and are awesome.

Remember how we printed out the values earlier?

1
console.log("hello: ", hello);

We can do the same thing by using string literals -

1
console.log(`hello: ${hello}`);

You can also do simple calculations within the string literals with or without using string literals.

1
2
console.log(`sum: ${x + y}`);
console.log(`product: ${3 * 2}`);

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!

1
2
3
let a = null;

console.log(a); //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.

1
console.log(b); //undefined

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 -

  1. One or more variables
  2. One or more constants
  3. One or more operators

Arithmetic Operators

Simple arithmetic operations are supported out of the box in Javascript.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
let x = 2;
let y = 3;

// addition operation with `+` operator
console.log(x + y); // 5

// multiplication with `*` operator
console.log(x * y); // 6

// division with `/` operator
console.log(y / x); //1.5

// modulo operator
console.log(y % x); //1

You can use more than one operators in one go -

1
2
console.log(x + y - y); //2
console.log(x + y * y); //11

See this Codepen for working examples.

See more arithmetic operators here.

Comparison Operators

Comparison operators help you to compare between two values.

1
2
3
4
5
6
7
8
9
let a = 3,
  b = 5;

console.log(a == b); // is `a` equal to `b` - false
console.log(a < b); // true
console.log(a <= b); // is `a` less than or equal to `b` - true
console.log(a > b); // true
console.log(a >= b); // true
console.log(a != b); // is `a` not equal to `b` - true

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.:

1
2
3
4
5
if (a == b) {
  console.log("a and b are equal");
} else {
  console.log("a and b are NOT equal");
}

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”.

1
console.log(3 == "3"); // true

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.

1
2
3
4
5
const x = "1";

if (x == 1) {
  console.log(x.toFixed(2)); // error since x is not a number and toFixed can only work on numbers
}

.. or in situations like this..

1
2
3
4
5
6
7
8
let result = 0;

if (!result) {
  // check if you did not receive result
  // result is implicitly converted to boolean condition.
  // Since the number `0` is false, this condition evaluates to not(`false`) = `true`
  console.log("Did not receive result");
}

We can use strict comparison operators to force Javascript to consider types as well as values.

1
2
console.log(3 === "3"); // strictly equal. values and types should be equal - false
console.log(a !== b);

Logical Operators

So far we have seen one comparison being made at a time.

1
2
3
4
5
let a = 1;

console.log(a == 0); // false
console.log(a > 0); // true
console.log(a < 5); // true

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.

1
2
console.log(a > 0 && a < 5); // true. check if `a > 0` and also `a < 5`
console.log(a > 5 && a < 10); // false

&& represents the AND operator. It results in true only if all expressions used in AND expression are true.

Other logical operators :

  1. OR - ||: results in true if any value is true
  2. NOT - !: unary operator. Just reverses the result - true to false or otherwise.

You can mix and match logical operators and any other operators in an expression.

1
2
3
let a = 9;
console.log(a > 0 && a < 10 && a != 1); // true
console.log(a < 1 || (a > 1 && a % 2 == 0)); // false - a < 1 AND a should be fully divisible by `2`

Consider one more example using simple conditional statements.

1
2
3
4
5
6
7
let color = "white";
let animal = "tiger";

if ((color == "white" && animal = "tiger")) console.log("ok"); // "ok"
if ((color == "white" && animal = "elephant")) console.log("whoa"); // will not print
if (color == "white" && animal != "tiger" && animal != "elephant")
  console.log("white something"); // will not print

Read up more on operators.

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.

1
2
// a simple number array
let nums = [1, 2, 3, 4, 5];

You can access any or all elements of an array.

1
2
3
4
5
console.log(nums); // [1,2,3,4,5]

console.log(nums[0]); // 1
console.log(nums[1]); // 2
console.log(nums[4]); // 5

An array can be -

  1. Artists in an album const wow=["Kula Shaker", "Deep Purple"]
  2. List of students in a class const class = ["Kent", "Parker"]
  3. 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.

1
2
3
4
5
const mix1 = ['a', 1, ['x', 'y']]] // array within an array

console.log(mix1[0]); // a
console.log(mix1[2]); // ['x', 'y']
console.log('array length = total number of elements in array = ', mix1.length); // 3

We discussed methods and how they are applicable to specific objects. Arrays have their own special methods too.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
let nums2 = [1, 2, 3, 4, 5, 6];

console.log(nums2); //[1,2,3,4,5,6]
console.log(nums2.length); // array length = 6

nums2 = nums2.push(7); // add 7 to array - at the end
console.log(nums2); //[1,2,3,4,5,6,7]

nums2 = nums2.pop(); // remove the last element of array
console.log(nums2); //[1,2,3,4,5,6]

console.log(nums2.sort()); //[1,2,3,4,5,6] - already sorted
console.log(nums2.includes(1)); //true. Does the array include `1`?
console.log(nums2.indexOf(2)); //1. Index of `2`. Array starts at zero and counts up

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.

1
2
3
4
name = "Parker";
console.log(name[0]); // P
console.log(name[2]); // r
console.log(name.length); // 6

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 -

1
const student = { name: "Ram", age: "9", class: "4" };

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 -

1
console.log("name: ", student["name"]); // Ram

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 -

1
2
3
4
5
const students = [
  { name: "Ram", age: "9", class: "4" },
  { name: "Chris", age: "9", class: "4" },
  { name: "Adi", age: "8", class: "3" },
];

How do you refer individual student? Follow the pattern followed for an array and for an object.

1
2
3
console.log(students[0]); // { name: "Ram", age: "9", class: "4" }
console.log(students[0]["name"]); // Ram
console.log(students[students.length - 1]["class"]); // 3

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 -

1
2
3
4
let a = 1;
if (a == 1) {
  console.log("a is one");
}

console.log("a is one"); is executed only if a == 1.

You can pair if with else, and also use more than one if.

1
2
3
4
5
6
7
8
let a = 1;
if (a == 1) {
  console.log("a is one");
} else if (a == 0) {
  console.log("a is zero");
} else {
  console.log("a is neither one nor zero");
}
  • Execute first block of code if a is 1
  • Execute second block of code if a is 0.
  • 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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
let a = 1;
if (a > 0) {
  // will be executed only if a > 0
  if (a == 1) {
    console.log("a is one");
  } else console.log("a is something else");
} else {
  // a <= 0
  console.log("a is NOT greater than zero");
}

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
let age = 9;
let cost;
let hasPass = false;

if (age <= 8) cost = 0;
else if (age > 8) {
  if (age < 70) cost = 0;
  else if (hasPass == true) cost = 0;
} else if (age >= 70) cost = 0;
else cost = 10;

Since we already know the logical operators can be combined, we can simplify it to -

1
2
3
4
5
6
7
let age = 9;
let cost;
let hasPass = false;

if (age <= 8 || age >= 70 || hasPass) cost = 0;
// using just `hasPass` is equivalent to a boolean expression - `hasPass == true`
else cost = 10;

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 -

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
let a = 1;

switch (a) {
  // compare `a` to values provided in `case`
  case 1: // if a == 1
    console.log("a is one");
    break;
  case 0:
    console.log("a is zero");
    break;
  default:
    console.log("a is neither one nor zero");
}

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..

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
let a = 1;

switch (true) {
  // compare `true` to case variables or expressions
  case a > 0: // if a > 0
    console.log("a is greater than zero");
  case a < 10:
    console.log("a is less than 10");
    break;
  default:
    console.log("a is something else");
}

// output
// a is greater than zero
// a is less than 10

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
let i = 0;
while (i < 5) {
  console.log("i am", i);
  i = i + 1;
}

// output
// "i am" 1
// "i am" 2
// "i am" 3
// "i am" 4

In the loop -

  1. create a variable called i, initialise it to 0
  2. start while loop to repeat code within brackets until i is less than 5
  3. 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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
let i = 0;
do {
  console.log("i am", i);
  i = i + 1;
} while (i < 5);

// output
// "i am" 1
// "i am" 2
// "i am" 3
// "i am" 4

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).

1
2
3
4
5
6
7
8
let j = 10;
do {
  console.log("i am do while", j);
  j = j + 1;
} while (j < 5);

// output
// "i am do while" 10

for

A for loop allows limited execution of a block of code until a specific count is reached.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
for (let i = 0; i < 5; i = i++) {
  console.log("hello", i);
}

// output

// hello 0
// hello 1
// hello 2
// hello 3
// hello 4

While the for loop does a similar job as a while loop, it functions a tad differently.

  1. initiate a for loop

    • a variable and a value from where we need to start the loop. We declared i in for while initiating loop itself, but it can be declared earlier in the code as well. i was initiated to 0
    • specify when to stop. Thiscify the condition to be true for the loop to continue. i < 5 specified that the loop code should execute until i was less than 5
    • what should we do after each iteration of loop. Here we increment i. We have used a unary operator i++ instead of writing i=i+1. You can count up or count down with any number (for e.g. i=i+10 will increment i by 10 after each iteration)
  2. for loop will also feature a block of code that needs to be executed until the specified condition holds true. 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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
let colors = ["green", "red", "blue"];

for (let i = 0; i < colors.length; i++) {
  console.log(colors[i]); // get the element at position i
}

// output
// green
// red
// blue

There is also a variation of for loop to iterate through arrays - for/of loop.

1
2
3
for (const color of colors) {
  console.log(color);
}

One of the popular ways of iterating objects is by using a variation of for loop - for / in.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
const student1 = { name: "Ram", age: "9", class: "4" };

for (const property in student1) {
  console.log(`${property}: ${student1[property]}`);
}

// output
// "name: Ram"
// "age: 9"
// "class: 4"

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.

1
2
3
let a, b;
let sum = a + b;
console.log("sum: ", sum);

Now, what happens if you also want the multiplication result?

1
2
3
4
5
6
let a = 2,
  b = 3;
let sum = a + b;
let sum = a * b;
console.log("sum: ", sum);
console.log("product: ", product);

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
let a = 2,
  b = 3;

console.log(sum(a, b)); // 5
console.log(product(a, b)); // 6

function sum(x, y) {
  return x + y;
}

function product(x, y) {
  return x * y;
}

The block of code starting with function keyword is called the function definition. You define a function like so -

1
2
3
function sum(x, y) {
  return x + y;
}

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) -

1
const total = sum(1, 3);

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.

1
2
let message = "hello world";
console.log(message.toUpperCase()); // HELLO WORLD

Similarly, we can have a rounding-off method to display a formatted number.

1
2
3
let numPrice = 123.34567;
console.log("numPrice:", numPrice); // 123.34567
console.log("Converted to string + rounded:", numPrice.toFixed(2)); // 123.35

Note that the method does not change the original value unless explicitly instructed to do so.

1
2
3
4
5
let announce = "the name is kent";
console.log("announce: ", announce); // the name is kent

announce = announce.replace("kent", "parker");
console.log("announce: ", announce); // the name is parker

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 -

  1. Code editors - we live by VS Code
  2. 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 -

1
console.log("hello");

You can execute this Javascript using Node. Go to Terminal > New Terminal in VSCode to open a new terminal.

Type -

1
2
node hello.js

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”..

1
console.log("hello world");

Open a command prompt (within VSCode or otherwise), go to directory of the file, and execute it to see the output.

1
node hello.js

Now, you can create and execute any Javascript!

Projects

You can create these projects using Codepen or on your local computer.

As the title says - just use console.log to print numbers.

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.

  1. Method will take a valid string input
  2. Check palindrome
  3. Return true or false

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.

  1. Enable user to select numbers, brackets and arithmetic operators - use HTML
  2. Optionally use a simple to use library like MVP.css. Just include the stylesheet in your HTML - you don’t need to learn CSS
  3. Display results
  4. 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 -

Stay in touch!
Share on

What's on this Page