JS By Example

JavaScript by Example (JSBE) is a collection of runnable examples that illustrate various JavaScript concepts.

Based on your coding experience, we'll be taking different approach on getting started with the learning process.

JS By Example For Noob

If you're new to programming and JavaScript is your first programming language. Then opt for this path, as it will not load you with jargons. Instead it will focus on getting you started and slowly explaining how everything works.

JS By Example For Coder

Here I will be assuming that you already know that fundamentals on programing. So we'll focus more on, how JS behaves and why it does, what it does.

JS By Example For WebDev

Here I will be assuming that you understand JS as a language. And we focus on how to use JS on Web, learn about DevTools, Debugging and more.

JS by Example For Noob

Congratulation!! You have made the right choice for starting with the JavaScript.

Now let's begin!

Hello World

In a programing world, their is ritual which every new programer does. And i.e., write their very first Hello World program. So, lets get into it.

// This is a comment, and is ignored by the compiler
// You can test this code by clicking the "Run" button over there ->

console.log("Hello World");

NOTE: You can also edit the examples. Let see what happens when you change Hello World to your name and re-run the example.

Let's understand what is happening. The above code can be broken down into 3 parts.

console

It is one of the Global object, which provides us with methods to interact with console.

To open console just press Option + ⌘ + J (on macOS), or Shift + CTRL + J (on Windows/Linux). And re-run the code. You'll see Hello World there as well.

We'll look this in detail when we start with object.

log

It is one the methods in the console object, which let's write on console.

"Hello World"

It is called argument. An argument is a way for you to provide more information to a function.

And this argument of type string, one of the Primitive. Let's learn more about it.


Where else I can run JavaScript?

To run JavaScript, you need JavaScript Engine and every browsers have one.

I will tell you 3 places where you can run this code.

Browser

Well any JavaScript code only need a JavaScript Engine to run and every browser have one.

Simply open any browser and press Option + ⌘ + J (on macOS), or Shift + CTRL + J (on Windows/Linux).

And you'll see console has opened.

Now paste (or write) the code and press Return (on macOS), or Enter (on Windows/Linux).

NOTE: Only recommended for quick and small code snippets.

Online playground

There are many online playgrounds where you can run you JavaScript code. Some of them are

They are ordered in the increasing level of complexity (features).

Terminal

Open a terminal, and write

node -v
// v16.13.12

if you don't get a version, the go through Node website and get it done.

Once you have node in your system. Create a file name hello.js and write the hello-world code previously mentioned. The file should looks somewhat like below

// hello.js
console.log("hello world")

Open terminal on the same directory. And write node hello

node hello
// hello world

Voila! You have created your very first node based hello world program.

NOTE: Read about nodemon. If you want run the program anytime you do a change.

Types and Values

JavaScript is Dynamically-typed language meaning the interpreter assigns variables a type at runtime based on the variable's value at the time.

Thus, JavaScript provide special keyword called typeof to get the type of the value.

console.log(typeof undefined)
// undefined

console.log(typeof "hello")
// string

console.log(typeof 11)
// number

console.log(typeof true)
// boolean

console.log(typeof {})
// object

Primitives

Every programing language support different type of values, for different purpose. The most fundamental of them are called Primitives.

Let's look at the most popular one.

Strings

In JavaScript, Strings are values made up of text and can contain letters, numbers, symbols, punctuation, and even emojis!

Let's look at different type of strings.

console.log(typeof "hello!!")
console.log(typeof "7")
console.log(typeof "")
console.log(typeof " ")
console.log(typeof new Date())

Numbers

Numbers are values that can be used in mathematical operations. You don’t need any special syntax for numbers — just write them straight into JavaScript.

console.log(7)
// number
console.log(3.14159265359)
// number
// But what's the limit, well you can check like this
console.log(Number.MAX_SAFE_INTEGER)
// 9007199254740991
console.log(Number.MIN_SAFE_INTEGER)
// -9007199254740991

NOTE: More on Number later. But if you're curious, then read the source.

Booleans

They are rather simple, they can only be true and false.

console.log(typeof true)

console.log(typeof false)

Objects

Objects are variables that contain multiple data values. The values within a JS object are known as properties. Objects use keys to name values, much like how is done with variables.

Objects are first Reference value/type we have encountered so far. Just keep that in mind we'll discuss it later.

// Objects are defined using `{}`, and between those parenthesis lies key-value pairs.
console.log(typeof {key1: "value1", key2: "value2"})

// Well Arrays are also objects
console.log(typeof [])

// And so is null
console.log(typeof null)

Undefined & Null

undefined is default value for every variable till, it is defined. And undefined indicates the absence of a value.

While null indicates the absence of an object

Array

Array are special type of object. That hold other values in order.

The values inside an array are called elements.

Array elements don’t all have to be the same type of value. Elements can be any kind of JavaScript value — even other arrays or objects.

// Arrays are defined using `[]`, and between those brackets lies values.
console.log(typeof [1,2,3,4,5])
// object

console.log(typeof ["Naruto", "Sasuke", "Kakashi"])
// object

console.log(typeof ["Naruto", 1, true, {}, null, undefined])
// object

NOTE: You can also read about Map, Set, BigInt and Symbol. But we don't have to worry about them right now.

Variable Declaration and Scope

JavaScript provide 3 ways to declare variables using var, let and const. And based on the the way you declared it, it'll affect its scope and properties.

And to declare a variable you simple use any of 3 keyword and give a name. Just like shown below.

To understand the difference between all 3, we will take a look at 3 identical examples. Only changing the way we declare the variables.

var

It is an ancient way for declaring variable, and before ES6, the only way. But it use to cause lot of confusion because of its functional scope (lexical scoping).

And that is how it different form let and const, because of its scope.

A general thumb rule, use let over var.

console.log(message);
var message = "hello world";
console.log(message);
message = "new world";
console.log(message);

let & const

Both let & const were introduced with ES6, and introduced block scoping in JavaScript. And they work very similar, except for the fact that variable declared using const cannot be reassigned.

let

// console.log(message);  <-- uncomment and you'll start seeing error.
let message = "hello world";
console.log(message);
message = "new world";
console.log(message);

const

// console.log(message);  <-- uncomment and you'll start seeing error.
const message = "hello world";
console.log(message);
// message = "new world";  <-- uncomment and you'll start seeing error.
console.log(message);

By comparing all the 3 examples you can see that let is more restricting than var and const and more restricting than let

A general thumb rule, use const over let over var.

The name you define here are called Identifiers and there are certain rules on how to name them. Let's look at them next.

Identifiers

The names you assign to these variables are called Identifiers.

The general rules for constructing names for variables (unique identifiers) are:

  • Names can contain letters, digits, underscores, and dollar signs.
  • Names must begin with a letter, $ or _.
  • Names are case sensitive (y and Y are different variables).
  • Reserved words (like var, let, for, typeof and more) cannot be used as names.
const dialogue = "How you doin!!";
// Identifier should be unique.
const dialogue = "We were on a break";
// And case sensitive
const Dialogue = "hello world";

console.log(dialogue)
console.log(Dialogue)

This is good time edit the example and try using let and var instead of const.

Operators

Operators are symbols that are used to perform operations on operands like addition, subtraction, multiplication, and more. JavaScript has dozens of operators, so let’s focus on the ones you’re likely to see most often.

Assignment

Operators like =.

We have already seen this operator in variable section, and this operator assigns values.

// Here we assigned the value `hello` to the variable named `message`.
let message = "hello"
console.log(message)

There are also different types of assignments operators like &&=, ||=, +=, -=, *=, /=, %=, ??= and more. But we learn about them later.

Arithmetic

Operators like +, -, *, / and %.

// Division
console.log(11/3)
// Multiplication
console.log(5*2)
// Subtraction
console.log(101-1)
// Addition
console.log(10+1)
// Addition can also be use to concatenate (combine) strings
console.log("Hello " + "World ")
// Modulus (Remainder)
console.log(10%3)

// Combination
console.log(1/2*3-4+5)
console.log(5-4+3*1/2)

Arithmetic operators follows the BODMAS rule, thus the order in which you write them is ir-relevant. You can use small brackets () to priorities certain operation.

Increment & Decrement

let count = 1;
console.log("Init count value: ", count);

// Increment
// `++count` is equal to `count = count + 1`
console.log("count value after increment: ", ++count);

// Decrement
// `--count` is equal to `count = count - 1`
console.log("count value after decrement: ", --count);

console.log("Final count value: ", count);

Increment & Decrement operator can also be used after the operand (like count++). The difference it will return the value before it is incremented.

Bitwise Operators

Operators like ^, ~, <<, >>, >>>, | and &

These are not as commonly used, so we'll look at them later.

Comparison & Logical Operators

These are the coolest and one of the most frequently used one (unlike Bit-wise operators) as well. So we will dive deep and understand each of them one-by-one.

Let see how they look. Operators like == , ===, != , !==, >, <, >=, <=,!, || and &&.


// Comparison Operators 
const random = Math.random().toFixed(1);

console.log('\n"10" == 10 = ', "10" == 10);
console.log('"10" === 10 = ', "10" === 10);
console.log('"10" != 10 = ', "10" != 10);
console.log('"10" !== 10 = ', "10" !== 10);

console.log('\nrandom = ', random);
console.log('\nrandom > 0.5 = ', random > 0.5);
console.log('random >= 0.5 = ', random >= 0.5);
console.log('random < 0.5 = ', random < 0.5);
console.log('random >= 0.5 = ', random >= 0.5);

// Logical Operators
console.log('!true = ', !true);
console.log('!false = ', !false);

console.log('\ntrue || true = ', true || true);
console.log('true || false = ', true || false);
console.log('false || true = ', false || true);
console.log('false || false = ', false || false);

console.log('\ntrue && true = ', true && true);
console.log('true && false = ', true && false);
console.log('false && true = ', false && true);
console.log('false && false = ', false && false);

Don't they look complicated. Let's look at them one by one.

Extra Cool Stuff

The Nullish Coalescing Operator

The ?? operator returns the first argument if it is not nullish (null or undefined).

Otherwise it returns the second argument.

let name = null;
let text = "missing";
let result = name ?? text;

The Optional Chaining Operator (?.)

The ?. operator returns undefined if an object is undefined or null (instead of throwing an error).

const naruto = {
  clan:"Uzumaki",
  village: "Leaf",
  chakra_nature:["wind"],
};
const sasuke = null;
console.log(naruto?.clan)
console.log(sasuke?.clan)  // <-- Try removing the `?`

Comparison & Logical Operators

The previous page looked complicated because of a phenomena called information overload. And to deal with that we have break the problem down. So, let me do that for you.

  • Logical

    • NOT (!)
    • OR (||)
    • AND (&&)
  • Comparison

    • Equal to (== & ===)
    • Not Equal to (!= & !==)
    • Less than and Less than equal to (< & <=)
    • Greater than and Greater than equal to> & >=

NOTE: There was specific reason why I overloaded you with that much information in the last page. Because in real-life you'll only see code like that, actually even worse than that. The key is not get over-whelmed but go line-by-line. Identify what you know, and predict the unknown.

Logical

If you're aware of the terms like truth table, logical gate. Then next 3 operator will be self explanatory to you. If not, then don't worry they are very simple (and important).

NOT (!)

Let's look only at the NOT(!) operator.

console.log('!true = ', !true);
console.log('!false = ', !false);

Did you get it? If not, try reading it out !true => NOTtrue. Meaning if it is not true, then it must be false. Therefore, If you put ! before true, it makes it false and vice-versa. But that's for boolean, how about numbers? Try guessing the output before running the example.

console.log('!7 = ', !7);
console.log('!false = ', !0);

Did you get it? This is happening because in javascript every value is either Truthy or Falsy. You can either play with code and figure out, or read the mentioned link.

Remember all the Falsy values, all the other value should be Truthy.

Before proceeding with the rest of Logical operators, we'll understand the Comparison operators.

Comparison Operators

They're used to compare 2 operands. Let's look at how they work in JavaScript.

Inequality (!= & !==)

We have seen the NOT(!) operator just now. So, based on that != means NOT-Equal. But why the second operator have 2 equal sign? Let's run the code and understand the difference.

console.log('"10" != 10 = ', "10" != 10);
console.log('"10" !== 10 = ', "10" !== 10);

Lets break down what's happening. So in both the cases, we are comparing "10" which is a string with 10 which is a number.

In the first case, JavaScript converts the number to string. And thus we get false. If you want to know why number got converted to string and not the other way around, then check MDN Docs.

But in the second case, since they are not of the same type, we get true meaning they are not equal.

A general thumb rule, use !==(strict equality) over !=(equality).

With this out of the way, the rest of the example will be self explanatory. Don't forget to try different value in the example.

Equality (== & ===)

Now, this operator is obvious.

NOTE: The single (=) sign is used for Assignment Operator.

console.log('"10" == 10 = ', "10" == 10);
console.log('"10" === 10 = ', "10" === 10);

Less than and Less than or equal (< & <=)

// Comparison Operators
console.log('5 < 5 = ', 5 < 5);
console.log('5 >= 5 = ', 5 <= 5);

Greater than and Greater than or equal > & >=

console.log('5 > 5 = ', 5 > 5);
console.log('5 >= 5 = ', 5 >= 5);

Logical

Now we know the NOT (!) Operator and all the Comparison Operators. These two operators are just logical (pun intended).

OR (||)

const num = 7;
console.log(num < 5 || num > 10);

So, if either of them is true, the output is true. And it's only false when both (all) of them are false.

console.log('true || true = ', true || true);
console.log('true || false = ', true || false);
console.log('false || true = ', false || true);
console.log('false || false = ', false || false);

This is called truth table. Which shows how the OR operator with respond all 4 possible case.

AND (&&)

Now, this is very similar to OR(||).

const num = 7;
console.log(num > 5 && num < 10 && num < 15);

So, it returns true only when both (all) of them are true.

Don't forget to play with example. What will happen if you replace 7 with 11.

Let's all the 4 possible scenarios for this as well. Assuming we have 2 operands.

console.log('true && true = ', true && true);
console.log('true && false = ', true && false);
console.log('false && true = ', false && true);
console.log('false && false = ', false && false);

Function

Functions are one of the fundamental building blocks in JavaScript.

And the purpose of Function is to execute a set of instruction when called.

Let's look at one.

function add(a, b) {
  return a + b;
}
const result = add(2, 5);
console.log(result);

Now there are few things to understand here, lets get it one by one.

  • function: This is the keyword (reserved word) used to define.
  • add: This is name of the function, it can be anything as long as they are valid identifier.
  • (a, b): These can further be divided in 2 types
    • a, b: These are called parameters, here we have 2 of them separated by a ,. These are also know as inputs
    • (): All the parameters are wrapper by them.
  • {}: These represent the body of the function. when the function is called, code withing these brackets will get executed.
  • return: This is the keyword (reserved word) used to return data from the function. These are also known as outputs.
  • add(2, 5): Lets break it down.
    • add: The name of the function which me want to call.
    • 2, 5: These are called arguments, and this denotes that a=2 and b=5.
    • (): All the arguments are wrapper by them.

Try removing the return keyword, and run the example.


In Javascript, functions can also be assigned to a variable. Lets check that out in code.

function add(a, b) {
  return a + b;
}
const alsoAdd = add;
const result = alsoAdd(2, 5);
console.log(result);

There are two things to note in the above code.

  • Just like any other value, functions can also be assigned to a variable. And you call them using this variable name, as well as the old name.
  • Remember just like objects, by assigning functions to a variable we are not copying it, instead just passing its reference.

Flow of Control

An integral part of any programming language are ways to modify control flow: if/else, for, and others.

Conditionals

Conditionals are used to create branches in the flow of your code. JavaScript provides 2 types of conditional they are

  • If/else
    • Ternary
  • switch

If / else

If/else are one most used conditions statement. Let's have a look.

if (7 % 2 === 0) {
  console.log('7 is even')
} else {
  console.log('7 is odd')
}

Let's break it down just like did to functions.

  • if: This is the keyword (reserved word) used to define.
  • (7 % 2 === 0): These can further be divided in 2 types
    • 7 % 2 === 0: These are called parameters, here we have 2 of them separated by a ,. These are also know as inputs
    • (): All the parameters are wrapper by them.
  • else: This is the keyword (reserved word) used to define.
  • {}: These represent the body of the if and else. when the condition is true, code withing if block will get execute or the code with within else block will get executed.
// You can have if without else
if (8 % 4 === 0) {
  console.log('8 is divisible by 4')
}

You don't always have to use else

What if, we want to create more than 2 branches. Well you can use else if

const duck = 'blue';
if (duck === 'yellow') {
  console.log('Rubber ducky')
} else if (duck === 'brown') {
  console.log('Live duck')
} else {
  console.log('Ive never seen a blue duck before.')
}

Here each condition will be checked till atleast anyone of them checks out. And if all of them are fails, then the else section will be executed.

Ternary Operator

Ternary Operator is short hand notation for if/else.

const true_value = true ? "I am True" : "I am False";
const false_value = false ? "I am True" : "I am False";

console.log("true_value = ", true_value);
console.log("false_value = ", false_value);

Switch

Switch statements are conditionals that may have many branches (like if / else if). Switch statements are more performant but less flexible.

// a simple switch statment
const fruit = 'banana'
switch (fruit) {
  case 'blueberry':
    console.log('blue')
    // everything after the true case executes
    // use 'break' if you aren't returning a value
    break;
  case 'banana':
    console.log('yellow')
    break;
  default:
    console.log('not blue, yellow or red')
}
// a simple switch statment
const fruit = 'banana'
switch (fruit) {
  case 'blueberry':
    console.log('blue')
    // everything after the true case executes
    // use 'break' if you aren't returning a value
    break;
  case 'banana':
    console.log('yellow')
    break;
    // multiple cases can resolve to the same branch
  case 'apple':
  case 'raspberry':
    console.log('red')
    break;
  default:
    console.log('not blue, yellow or red')
}

Loops

Loops are used to create loop in your code. JavaScript provides 3 types of loops and they are

  • For
  • While
  • Do while

For

One of most used loops of all time.

// for(declaration; condition; increment)
for(let i=0; i<7; i++) {
  console.log("i = ", i)
}

Let's understand it's syntax.

  • for: This is the keyword (reserved word) used to define.
  • let i=0 or declaration: These can further be divided in 2 types
  • i<7 or condition: This is the keyword (reserved word) used to define.
  • i++ or increment: These represent the body of the if and else. when the condition is true, code withing if block will get execute or the code with within else block will get executed.
// Is it a valid loops
for(let i=0; i<7;) {
  console.log("i = ", i)
}
// Don't run it.

While

The while keyword can be used to run a loop while a condition is true.

let i=0;
while(i<7) {
  console.log("i = ", i)
  i++;
}

Let's understand it's syntax.

  • while: This is the keyword (reserved word) used to define.
  • let i=0 or declaration: These can further be divided in 2 types
  • i<7 or condition: This is the keyword (reserved word) used to define.
  • i++ or increment: These represent the body of the if and else. when the condition is true, code withing if block will get execute or the code with within else block will get executed.

Do while

The do keyword is used to start the body of the loop and while keyword is used at the end to declare the condition.

let i=0;
do {
  console.log("i = ", i)
  i++;
}while(i<7);

Let's understand it's syntax.

  • do: This is the keyword (reserved word) used to define.
  • let i=0 or declaration: These can further be divided in 2 types
  • i<7 or condition: This is the keyword (reserved word) used to define.
  • i++ or increment: These represent the body of the if and else. when the condition is true, code withing if block will get execute or the code with within else block will get executed.
  • while: This is the keyword (reserved word) used to define.

As you can see the condition is checked at the end, the content of the loop will always execute at-least once (even when the condition is false).

JS BY EXAMPLE FOR CODER

Work in Progress

JS BY EXAMPLE FOR WEBDEV

Work in Progress