JavaScript 101

What is JavaScript? What all you need to know as a beginner.

JavaScript is a programing language that helps us to create a dynamic website easily. It can be considered as a tool that gives up the power to manipulate anything on a website( DOM manipulation) such as changing text, images, etc on certain actions being taken by the user.
HTML and CSS are markup languages that allow us to describe and define elements within a document(static website), but JavaScript is the one according to me which puts life and soul into the website we are creating by allowing us to communicate instructions to a machine.

Note: Javascript is created by Brendan Eich in 1995, while he was working on the Netscape Navigator. Netscape Navigator was one of the Internet’s first web browsers.

Every web browser has a built-in JavaScript engine to run the JavaScript code. The JavaScript console or the web console is something that we can use as a sandbox to play with JavaScript.

Data type and variables

Data and data types are building blocks of any programming language because they help us to organize information and determine how our program will work.
* Numbers
* Strings
* Objects
* Boolean etc…
Comments are something that is used to note down some notes in our code that the machine doesn’t execute. Comments must be often used while we are writing our code for a better understanding of a piece of code. In JavaScript, there are two ways to specify comments

// this is a single-line comment
/*
this is
a multi-line
comment
*/

Variables are used to store data. When you create a variable, you write the name of the variable using camelCase.

var nameVariable = "Aniket";
var ageVariable = 23;

Tip: Escaping a character tells JavaScript to ignore the character’s special meaning and just use the literal value of the character. In JavaScript \ is used for escaping. "Hello, \" My name is Aniket \" " will give us the output as " Hello, "My name is Aniket"

JavaScript is known as a loosely typed language, so we do not need to specify the data type explicitly, the JavaScript Engine will automatically interpret the code and will do the code conversion. We can do a strict comparison by using the === while doing conditional checks.


Conditional Statement

There are many ways by which we can perform conditional actions.

  • If…else statement allows you to execute certain pieces of code based on a condition, or set of conditions, being met.
if (/* this expression is true */) {
  // run this code
} else {
  // run this code
}

In JavaScript, you can represent this secondary check by using an extra if statement called an else if statement.

Logical Operator is something which can be used to implement complex conditional statement by creating a conjunction between expression.

  • The ternary operator provides you with a shortcut alternative for writing lengthy if…else statements.
    conditional ? (if condition is true) : (if condition is false)

  • A switch statement is another way to chain multiple else if statements that are based on the same value without using conditional statements.
    The break statement can be used to terminate a switch statement and transfer control to the code following the terminated statement. By adding a break to each case clause, you fix the issue of the switch statement falling-through to other case clauses.


Loops

There are many different kinds of loops, but they all essentially do the same thing: they repeat an action some number of times.

var start = 0; // when to start
while (start < 10) { // when to stop
  console.log(start);
  start = start + 2; // how to get to the next item
}

The above is an example of what the while loop looks like.
Another type of loop which is most commonly used is the for loop.

for ( start; stop; step ) {
  // do this thing
}
Eg:
for (var i = 0; i < 6; i = i + 1) {
  console.log("Printing out i = " + i);
}

Functions

Often the code gets bigger enough while we are developing a website and there occurs a situation where we write the same piece of code multiple times to get them working in different places. Instead of repeating the same steps multiple times, we can up those processes into reusable chunks of code called functions.

function findAverage(x, y) {
  var answer = (x + y) / 2;
  return answer;
}
var avg = findAverage(5, 9);

In the above sample code, the findAverage is the function name, which takes two parameters (x,y). Parameters are variables that are used to store the data that’s passed into a function for the function to use. findAverage(5, 9); is the function call made with the two arguments(5, 9). Arguments are the actual data that’s passed into a function when it is invoked.
A function may or may not have a return statement, in this case, we have one so the result is passed back after computation and is stored in the variable avg. If you don't explicitly define a return value, the function will return undefined by default.

Note: There are some topics you might want to refer to before you move further such as scopes, shadowing and hoisting.

A function expression is another way in which we can declare a function. So in JavaScript, we can also store functions in variables, making it easier to pass the function to other functions during callbacks and all.

var catSays = function(max) {
  var catMessage = "";
  for (var i = 0; i < max; i++) {
    catMessage += "meow ";
  }
  return catMessage;
};

The above code block shows how we can declare a function expression. The above function can be invoked by calling catSays(3) The function expression can be an anonymous function, a named function expression, or an inline function expression.


Arrays

An array is a data structure that can hold multiple data values. An array is useful because it stores multiple values in a single, organized data structure.
Eg: var donuts = ["glazed", "powdered", "jelly"];Strings aren’t the only type of data you can store in an array. You can also store numbers, booleans… and anything!. Even we can store an array in an array to create a nested array!

Tip: JavaScript provides a large number of built-in methods for modifying arrays and accessing values in an array, or type []. into the JavaScript console for a list of all the available Array methods.

The length of the array can be easily obtained the length property. console.log(array.length) returns the length of the array.
The two most common methods for modifying an array are push() and pop(). The push method takes an argument which is the value to be added to the array and the values are added to the end of the array. The pop method removes the last element from the list. Egarray.push("new element");
The push method returns the length of the array whereas the pop method returns the element which was deleted.
While push and pop limits us to add and remove elements from the end of the array, splice() lets us specify the index location to add new elements, as well as the number of elements you’d like to delete (if any).

var donuts = ["glazed", "chocolate frosted", "Boston creme", "glazed cruller"];
donuts.splice(1, 1, "chocolate cruller", "creme de leche"); 
//removes "chocolate frosted" at index 1 and adds "chocolate cruller" and "creme de leche" starting at index 1
Returns: ["chocolate frosted"]
donuts array after calling the splice() method: ["glazed", "chocolate cruller", "creme de leche", "Boston creme", "glazed cruller"]

Arrays have a set of special methods to help you iterate over and perform operations on collections of data. The forEach() and map() methods are two such methods that help us to iterate over each element and perform certain actions.

var donuts = ["jelly donut", "chocolate donut", "glazed donut"];
donuts.forEach(function(donut) {
  donut += " hole";
  donut = donut.toUpperCase();
  console.log(donut);
});

The function that you pass to the forEach() method can take up to three parameters, which are called element, index, and array.
The forEach() method can only be used when we are trying to modify the original array, it always returns undefined. map() is a powerful method that can take an array, perform some operation on each element of the array, and return a new array.

var donuts = ["jelly donut", "chocolate donut", "glazed donut"];
var improvedDonuts = donuts.map(function(donut) {
  donut += " hole";
  donut = donut.toUpperCase();
  return donut;
});

Objects

The objects are a powerful data structure in javascript, they allow us to wrap up pieces of related data and functionality into one single container.

var sister = {
  name: "Sarah",
  age: 23,
  parents: [ "alice", "andy" ],
  siblings: ["julia"],
  favoriteColor: "purple",
  pets: true,
  paintPicture: function() { return "Sarah paints!"; }
};

The above syntax is called the object literal notation. There are some important things you need to remember when you’re structuring an object literal:

  • The “key” (representing a property or method name) and its “value” are separated from each other by a colon

  • The key: value pairs are separated from each other by commas

  • The entire object is wrapped inside curly braces { }.

There are two ways by which we can obtain the values from the keys.

  • Using sister["parents"] is called bracket notation

  • Using sister.parents is called dot notation


let and const are two new ways to define variables in JavaScript which were introduced in ES6. Variables declared with let and const eliminates the specific issue of hoisting because they’re scoped to the block, not to the function. Previously, when we used var, variables were either scoped globally or locally to an entire function scope. If a variable is declared using let or const inside a block of code (denoted by curly braces { }), then the variable is stuck in what is known as the temporal dead zone until the variable’s declaration is processed.

Template literal is another concept that was introduced in ES6. Prior to ES6, the old way to concatenate strings together was by using the string concatenation operator ( + ).

let message = `${student.name} please see ${teacher.name} in ${teacher.room} to pick up your report card.`;

Tip: Embedded expressions inside template literals can do more than just reference variables. You can perform operations, call functions and use loops inside embedded expressions!

Destructuring borrows inspiration from languages like Perl and Python by allowing us to specify the elements we want to extract from an array or object on the left side of an assignment.

const point = [10, 25, -34];

const [x, y, z] = point;

console.log(x, y, z);
Prints: 10 25 -34

The for…of loop is used to loop over any type of data that is iterable. The one advantage of the for…of loop when compared to the for…in loop is that we can stop or break the loop at any time.

const digits = [0, 1, 2, 3];

for (const digit of digits) {
  console.log(digit);
}
Prints:
0
1
2
3

The spread operator, written with three consecutive dots ( ... ), gives us the ability to expand, or spread, iterable objects into multiple elements.

const books = ["Don Quixote", "The Hobbit", "Alice in Wonderland", "Tale of Two Cities"];
console.log(...books);
Prints: Don Quixote The Hobbit Alice in Wonderland Tale of Two Cities

If we can use the spread operator to spread an array into multiple elements, then certainly there should be a way to bundle multiple elements back into an array, rest parameter.

const order = [20.17, 18.67, 1.50, "cheese", "eggs", "milk", "bread"];
const [total, subtotal, tax, ...items] = order;
console.log(total, subtotal, tax, items);
Prints: 20.17 18.67 1.5 ["cheese", "eggs", "milk", "bread"]

So, that’s all with the basics which I could remember sharing with you. I will be back with my next blog sharing in-depth details related to Objects, Functions, Document Object Models, etc…