Learning Web Development? Here's the nitty-gritty of JavaScript you may have skipped/missed!

There is no brainer; you need to learn the fundamentals of any programming language.

Here are the fundamentals of Javascript every developer should know before opting any Javascript Framework.

1. Javascript fundamentals:

1.1 Basic Syntax:

Here is the basic Javascript syntax.

// this means single line comment
// declaring a variable
let a;

// assigning a value to the variable `a`
a = 3;

// A conditional statement
// Is `a` equal to 3?
if (x === 3) {
  x = 123;
}

// Define function `foo` with parameters `a` and `b`
function foo(a, b) {
  return a + b;
}

// calling function `foo` with parameters `a` and `yb`
foo(a, b);
// calling method `bar` of object `obj`
obj.bar(3);

1.1.1 Variable

These are different ways of declaring variables.

let a;
const b;
var c;

To learn more about var, let and const follow this link .

1.1.2 Data types

Data types in Javascript is mainly divided into

  • String
//String in double quotes
let a = "Pratap";
//String in back tick
let a = `Pratap`;
  • Number
let a = 3;
let b = 1.5;
let c = -9;
  • Boolean
let jsIsFun = true;
let sleeping = false;
  • Undefined In javascript, undefined is also a data type 😳.
let name;
let number = 5;

console.log(name); //This will print: undefined
console.log(number); //This will print: 5
  • Null In javascript, null is also a data type 😳.
let name = null;
let number = 5;

console.log(name); //This will print: null
console.log(number); //This will print: 5
  • Object Objects in javascript are one of the data types 😱. The object allows storing collections of data.

    An array can contain any type of elements

let thisIsObject = {};
let author = { name: "Pratp", age: "24" };
  • Arrays An array is mainly used for storing multiple values in a single variable

    An array can contain any type of elements

let dataTpes = [
 "string",
 "number",
 "boolean",
 "null",
 "undefined",
 "object",
 "array",
 "function",
];
let mixTypeOfArray = [1, "pratap", true, null, undefined, { name: "Pratap" }];
let emojiCollection = [😀, 😁, 😂, 🤣, 😃 }];
  • Functions The strange thing about javascript is that function is also a data type 😂 A function is a callable object which executes a block of code
let foo = function () {
  return "Foo!";
};

console.log(foo()); //Prints: foo

1.2 Conditionals:

In javascript, we have two types of conditions if-else and switch.

1.2.1 if/else

The if/else conditional If a specified condition is true then a statement executed else another block of code gets executed.

if (x === 2) {
  console.log("This section will execute");
}

if (name === "Pratap") {
  console.log("My name is Pratap");
} else {
  console.log("My name is not Pratap");
}

if (num === 1) {
  console.log("It is number 1");
} else if (num === 2) {
  console.log("It is number 2");
} else {
  console.log("It is neither 1 nor 2");
}

1.2.2 switch

The value of name decides which case is executed:

let name = "Pratap";
switch (name) {
  case "Pratap":
    console.log("Name is Pratap");
    break;
  case "Prasar":
    console.log("Name is Prasar");
    break;
  default:
    console.log("Name does not match any case");
}

If none of the case matches, then the default block will get executed.

1.3 Loops:

In Javascript or any programming language, we have loops. Loops are used to do any repetition task until a condition is fulfilled each time with a different value.

1.3.1 for loop

The below code will run until the value of i is less than 5. For loop has two parts.

  • Header: It specifies the iteration condition
  • Body: The body is executed once for every iteration
//for loop
for (let i = 0; i < 5; i++) {
  console.log("My current value is ", i);
}

There are also different kind of loops in Javascript:

  • for/in.
  • for/of.

Will explain about them in another tutorial.

1.3.2 while loop

While loop continues to loop over its body while the condition is true:

let a = 0;
while (a < 5) {
  console.log("Print me on the console");
  a++;
}

1.3.3 do while loop

The do-while loop continues to loop over while its condition is true. As the condition follows the body, the body is always executed at least once:

let a = 0;
do {
  console.log("Print me on the console");
  a++;
} while (a < 4);

2. Modules:

Modules in javascript are used to import/export files/piece of code. Without modules, there won't be any framework because it allows everything to be brought together.

3. Classes:

ECMAScript2015, which is commonly knows as ES6, introduced a concept of classes. A class is a program-code-template which is used for creating objects. In order to create a class we need to use the keyword class; Every time a class object is initialized, the constructor method is called.

class Bike {
  constructor(brand) {
    this.name = brand;
  }
}

3.1 Object of Class

As we have created a class, now let us create an object. To create an object, we use a keyword new followed by the name of the class.

let suzuki = new Bike("Suzuki");

The constructor of the class is called every time an object is created.

3.2 Methods of Class

3.2.1 Constructor

A constructor of a class is a special type of class method which gets called every time the object of a class is created. All the properties are initialized in the constructor. Even if you don't add a constructor in a class javascript will automatically create and call the constructor.

class Bike {
  constructor(brand) {
    this.name = brand;
  }
}

3.2.1 Methods

You can create any number of method in a class.

class Bike {
  constructor(brand) {
    this.name = brand;
  }
  getBikeName() {
    return "The name of the bike is: " + this.name;
  }
}

let myBike = new Bike("Suzuki");
console.log(myBike.getBikeName()); //Prints: The name of the bike is: Suzuki

3.2.1 Static Methods

The static method of a class is defined by keyword static.

Static methods are not called on instances of the class. Instead, they are called on the class itself.

class Bike {
  constructor(brand) {
    this.name = brand;
  }

  static foo() {
    return "I am a static method";
  }
  getBikeName() {
    return "The name of the bike is: " + this.name;
  }
}

console.log(Bike.foo()); // Prints: I am a static method

3.3 Inherritance

Inheritance is nothing but passing down all features of parent class to a base class.

class Bike {
  constructor(brand) {
    this.name = brand;
  }
  present() {
    return "My brother have " + this.name;
  }
}

Now, let us create another class Model, and we'll extend the class Bike.

class Model extends Bike {
  constructor(brand, mod) {
    super(brand); //Calling constructor of parent class.
    this.model = mod;
  }
  print() {
    return this.present() + ", and model is " + this.model;
  }
}
let myBike = new Model("Suzuki", "Gixxer");

console.log(myBike.print()); //This prints: My brother have Suzuki and model is Gixxer

As we can see inside the constructor of Model class, we are calling super(brand). super here refers to the constructor of the parent class. By calling super in the constructor of class Method we get access to the constructor of Parent class Bike constructor and its methods.

We'll learn more about Javascript Classes in another tutorial.

4. Arrow Function

Another addition of ES6 was Arrow Function. Arrow functions allow us to write the syntax of function in shorter form. It is a concise way of writing function.

Arrow functions are much more compact than the normal function and give advantages when it comes to scope in certain situations.

  • Looks much cleaner with fewer lines of code.
  • The standard way of writing function in modern Javascript.
  • Lexical scoping of this. Eg of Arrow Function: Before
let foo = function () {
  return "I am foo";
};

After

let foo = () => "I am foo";

Another advantage of Arrow Function is that it does not bind it's own this. this in arrow function is lexically scoped.

We'll learn about the arrow function in another tutorial.

5. Promises:

This is one of the javascript concepts which every javascript developers miss out. This requires a deep dive into the concept. For now, let us have a brief about promise.

What is a promise? A promise is an asynchronous object that may give a result some time in the future: either a resolved value or a reason why it got rejected. A promise can have any of the three possible states:

  • fulfilled: The promise was fulfilled
  • rejected: The promise is rejected.
  • pending: The promise is still pending.

A promise can easily be understood with an example: Let's say you are in standard ten and your parent promised you that if you clear your standard ten examinations in 1st div they will buy you a computer.

So from the example above the promise by your parent can have three different states based on your performance in standard 10.

  1. They will fulfil your promise by getting a computer for you.
  2. Unfortunately, you didn't secure 1st div in your standard they will reject their promise.
  3. The third state could be if secured 1st div in your standard. But your parents neither fulfil or reject their promise, so the promise is still pending.

Syntax of creating a promise.

let promise = new Promise(function (resolve, reject) {
  //resolve or reject is done here
});

Resolving a promise

let promise = new Promise(function (resolve, reject) {
  // after 1 second promise is ressolved with the result "resolved"
  setTimeout(() => resolve("resolved"), 1000);
});

Rejecting a promise

let promise = new Promise(function (resolve, reject) {
  setTimeout(() => reject(new Error("I reject you!")), 1000);
});

We can also consume the promise.

let promise = new Promise(function (resolve, reject) {
  setTimeout(() => reject(new Error("I reject you!")), 1000);
});

promise.then(
  (result) => console.log(result), // prints "resolved" after 1 second
  (error) => console.log(error) // This throws an error
);

Chaining of promises using then, catch and finally:

let promise = new Promise(function (resolve, reject) {
  setTimeout(() => reject(new Error("I reject you!")), 1000);
});

promise
  .then(
    (result) => console.log(result) // prints "resolved" after 1 second
  )
  .catch(
    (error) => console.log(error) // This throws an error;
  )
  .finally((_) => {
    //This section of the promise will always get executed regardless of promise gettinf resolved or rejected
  });

The fetch() method in javascript also returns a promise.

We'll learn about asynchronous javascript in-depth in another tutorial.

6. Destructuring

Destructuring is a special javascript syntax that was introduced which that allows us to “unpack” arrays or objects into a variable, as it's more convenient.

Destructuring is widely used in frameworks which makes the code cleaner and more readable.

It “destructured” by copying items of an array into variables, and the original array or object is not modified.

6.1 Array Destructuring

Destructuring an array

let people = ["Pratap", "Prasar"];

let [person1, person2] = people;

console.log(person1); //Prints: Pratap
console.log(person2); // Prints Prasar

6.2 Object Destructuring

Destructuring an object also works the same.

let about = {
  name: "Pratap",
  age: 24,
  hobby: "Writing, coding",
};

let { name, age, hobby } = about;
console.log(name); //Prints: Pratap
console.log(age); // Prints 24
console.log(hobby); // Writing, coding

It is also possible to extract data from nested arrays/objects.

We'll learn about destructuring in-depth in another tutorial.

7. Spread Operator

The feature spread operator in javascript was introduced in ES6.

Spread operator allows an array expression or string to be expanded in places where zero or more arguments(for function) or elements (for array), or an object expression to be expanded in areas with zero or more key-value pairs.

function multiply(a, b, c) {
  return a * b * c;
}

const numbers = [1, 2, 3];

console.log(multiply(...numbers));
// expected output: 6

Any argument in the argument list of a function can use spread syntax, and the spread operator can be used multiple times.

function foo(a, b, c, d, e) {
  //do something
}
const args = [0, 1];
foo(-1, ...args, 2, ...[3]);

In ES2018 the spread properties were also added to object

const obj1 = { foo: "bar", x: 10 };
const obj2 = { foo: "baz", y: 12 };

// The original object is unchanged, a new object is created.
const clonedObj = { ...obj1 };
// Object { foo: "bar", x: 42 }

const mergedObj = { ...obj1, ...obj2 };
// Object { foo: "baz", x: 10, y: 12 }

We'll learn about spread operator in-depth in another tutorial.

8. Higher-Order Array Functions

What is Higher Order Function? Higher-Order Function is a function that takes a function as a parameter. Functions like forEach(), map(), filter(), reduce() are some example of higher-order array function. These higher-order functions are used all the time to iterate and manipulate an array of data. forEach(): This is used for basic iteration/looping. It is same as the normal for loop.

let array = [1, 2, 3, 4];
array.forEach((item) => console.log(item));

map(): This is mainly used for manipulation of data and returns a new array.

let array = [1, 2, 3, 4];
let changedArray = array.map((num) => num * 2);

console.log(changedArray); //[2,4,6,8]

filter(): Used to filter out certain pieces of data.

let array = [1, 2, 3, 4];
let filteredArray = array.filter((num) => num > 2);

console.log(filteredArray); //[3,6]

reduce(): This is mainly used to turn an array to a single value

let array = [1, 2, 3, 4];
let sumOfArray = array.reduce((total, num) => total + num, 0);
// 0 - The second parameter in reduce is the initial value

console.log(sumOfArray); //10

9. Closueres

Closure happens when you have a function declared inside another function. Let's say there's function a and function b, where function b is nested inside function a.

Closure makes sure that function b will be able to access it's own local variables, any global variables and also function a's local variables. But function a would not be able to access any variables inside function b.

example:

function a() {
  var word = "word";

  (function b() {
    var word2 = "word2";
    console.log(word);
  })();

  // console.log(word2) // causes an error
}

We'll learn about Higher-Order Array Functions in-depth in another tutorial.

Conclusion

Learning all these concepts of Javascript before jumping into a framework will not only prepare you, but it will also make it easy to learn new frameworks easily.

💌 If you’d like to receive more tutorials in your inbox, you can sign up for the newsletter here.

Discussions

Up next