Getting started with Core JavaScript
This article is the sixth part of Week of Web(#WOW). If you don’t know what #WOW is here’s a card to it.
In this article, we will learn all the essentials of Core JavaScript which includes data type, strings, arrays, object literals, loops, conditionals, functions.
So if you are completely new to JavaScript, this article is for you!
What is JavaScript?
JavaScript is a high-level programming language. By high level, it means that there is a lot of abstraction, that is a lot of things are done automatically in the background without you knowing about it like memory management which you would do manually on a low-level language like C or C++.
A classic analogy of abstraction is that you don't need to know how an engine works to know how to drive.
Many beginners get confused between Java and JavaScript. Java is a completely different language that has fewer similarities with Javascript.
Comparing Java to JavaScript is like comparing a Car to a Carpet.
Why should you learn JavaScript?
It is the programming language of the browser and if you want to write client-side programming(client-side code runs directly on the browser) for web development you need to know JavaScript. There are other languages like Python, PHP, C# and Java which are all great but they all are made for server-side programming and they can’t generate client-side unless there is a library that converts these codes into JavaScript.
It can create an interactive user interface using Vanilla JavaScript or even by using frameworks like React, React Native and Electron.
It can be used to write server-side code (Backend) using Node.js with frameworks like Express.js.
Now go grab yourself some coffee and let’s jump in to programming with JavaScript
How to run a JavaScript code?
Now open VS Code and create an HTML file called jsTutorial.html with the boilerplate in it. Add the title as JavaScript Tutorial
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Tutorial</title>
</head>
<body>
</body>
</html>
Now add the following in the body element
<h1>JavaScript Tutorial</h1>
<script src="./tutorial.js"></script>
Now create a new file called tutorial.js in the same folder. And type the following in it.
alert("hi");
Now open jsTutorial.html in a browser and check whether you get a window with hi written in it.
And you learnt how to add JavaScript to an HTML document and your first JavaScript function!
alert function is a part of the window object that displays its content in the browser as a pop-up.
But we don't use alert to display values all the time as it blocks the script from running ahead until the user clicks on the OK button.
Instead, we use the console. Every browser has it’s developer tools and there is a JavaScript console where we could display values and also run JavaScript in it directly.
To open developer tools on Google Chrome, go to options (indicated by three vertical dots on the top right side) and click on more tools then developer tools.
A new window will open where you need to select the Console Tab.
To avoid all this hassle just use the shortcut binding Ctrl+Shift+J
Now remove this from tutorial.js
alert(“hi”);
And type this
console.log("hi from console");
And reload the HTML document and check the console
You see the value is displayed here now.
And that is how we run JavaScript in a Browser.
Variables
In JavaScript, we have three methods to create a variable.
var
var is a globally scoped method to create variables.
Let's say if we have a variable defined at the beginning of our code and another variable with the same name defined in function or a condition then it will cause conflicts. Hence we don’t use var anymore.
let and const
let and const were added in the ES6 version of JavaScript in 2015. And with ES6 we had major updates to JavaScript with many more features and functionalities.
The difference between let and const is with let we can reassign a value to a variable whereas with const we can’t.
Consider this code
let age = 20;
age = 25;
console.log(age);
We will get the output correctly.
Whereas if try to change a const variable we will get an error
const age = 20;
age = 25;
console.log(age);
Data Types
There are six types of primitive(directly assigned to memory) data types namely strings, numbers, boolean, null and undefined.
const name = 'Vinayak';
const age = '21';
const weight = '75.5';
const isCool= true;
const problems = null;
let x;
const y = undefined;console.log( typeof name);//string
console.log( typeof age);//number
console.log( typeof weight);//number
console.log( typeof isCool);//boolean
console.log( typeof problems);//object
console.log( typeof x);//undefined
You may notice that the value of problems is null but the typeof operator returns object, this actually a bug in JavaScript and shall be ignored.
Conditionals
Conditionals let us select a set of code for the given conditions. These conditions are defined using logical operators.
Double equals with if-else
const x = "2";
if(x==2){
console.log("x is 2");
}
else
console.log("x is not 2");
Triple equals with if-else
const x = "2";
if(x===2){
console.log("x is 2");
}
else
console.log("x is not 2");
Other logical operators and nested if-else ladder
const x = 200;
if (x === 20) {
console.log("x is 2");
} else if (x > 100) {
console.log("x is 100");
} else if (x < 100) {
console.log("x is not 2");
}
Loops
As the name suggests it keeps executing a set of code until a condition is reached.
For Loop
for(let i =0; i < 10; i++){
console.log(i);
}
While Loop
let i =0;
while(i<10){
console.log(i);
i++;
}
Functions
A function is a block of organized code that could be reused to perform actions based on the arguments(input) passed into it.
Function Definition
function addNumbers(numb1, numb2){
return(numb1+numb2)
}
Function Call
const result = addNumbers(5,10);console.log(result); //15
Arrow Functions
Arrow Function was introduced in ES6 Version for better readability and faster development. The same function can be written as an arrow function.
const addNumbers = (numb1, numb2) => numb1+numb2;console.log(addNumbers(1,3); //4
Strings
A string is a sequence of multiple characters. In JavaScript define strings using double quotes or single quotes.
Template Strings
const name = "Vinayak";
const age = "21";
// Concatenation
console.log("My name is " + name + " and I am " + age + " years old");
// Template String
console.log(`My name is ${name} and I am ${age} years old`);
JavaScript has Template String feature that lets us add variables inside a string.
Methods
All the data types in JavaScript have functions associated with them called methods. A few handy ones for strings are as follows
const greeting = `Hello Everyone!`;
console.log(greeting.length); //15
console.log(greeting.toUpperCase()); //HELLO EVERYONE!
console.log(greeting.toLowerCase()); //hello everyone!
console.log(greeting.substring(0, 8)); //Hello Ev
console.log(greeting.substring(0, 8).toUpperCase()); //HELLO EV
Arrays
An array is a collection of similar data type variables. Unlike other languages, JavaScript gives us the freedom of using different data types and also we don't have to define the length of the array to initialise it. We define arrays using square brackets.
const colors = ['red', 'green', 'blue', 'yellow', 1 , true];
console.log(colors[1]); // 'green'
Arrays always start from zero and hence when index 1 is used we get ‘green’ as output.
The array could be manipulated even though it is defined as a const variable but it cannot be reassigned.
Methods
const colors = ['red', 'green', 'blue', 'yellow'];colors.push('violet'); //adds to end
console.log(colors); // ["red", "green", "blue", "yellow", "violet"]colors.unshift('magenta'); //adds to start
console.log(colors); //["magenta", "red", "green", "blue", "yellow", "violet"]colors.pop(); //removes from end
console.log(colors); //["magenta", "red", "green", "blue", "yellow"]console.log(colors.indexOf("green")); //2
Object Literals
Object Literals are basically key-value pairs. Where we define many key-value pairs under one variable. For example
const person = {
fName: "Sherlock",
lName: "Holmes",
age: 60,
hobbies: ["Music", "Movies", "Games"],
address: {
house: "222B",
street: "Baker street",
city: "London",
}
};console.log(person); //{fName: "Sherlock", lName: "Holmes", age: 60, hobbies: "Music, Movies, Games", address: {…}}
console.log(person.fName); //Sherlock
console.log(person.hobbies[2]); //Games
console.log(person.address.street); //Baker street
JSON files are a strip down version of JavaScript that contains only an Array of Objects and removes all other capabilities of JavaScript.
Higher-Order Array Methods
The forEach Method
The forEach method is used to iterate through all the elements of an array.
const colors = ['red', 'green', 'blue', 'yellow'];colors.forEach((color)=>{
console.log(color);
});
The map Method
The map method is used to iterate through all the elements of an array just like forEach method but it also returns a new array with all the new values.
const colors = ["red", "green", "blue", "yellow"];const upperCaseColors = colors.map((color) => {
return color.toUpperCase();
});console.log(upperCaseColors); //["RED", "GREEN", "BLUE", "YELLOW"]
The filter Method
The filter method as the name suggest is used to return the elements of an array that satisfy a certain condition.
const colors = ["red", "green", "blue", "yellow"];const hasLetterL = colors.filter((color) => {
return color.includes("l")
});console.log(hasLetterL); //["blue", "yellow"]
With this we are done with Essentials of Core JavaScript
In the next article, we learn about the Document Object Model(DOM) of an HTML document and how to use JavaScript to manipulate it. Using these DOM Manipulations we will also make our ToDo list app interactive.
This is Vinayak Tekade from Coder’s Capsule in collaboration with Developer Student Clubs Amrita School of Engineering Bengaluru signing off.
Follow me on LinkedIn and Twitter.
Looking forward to learn, teach and grow together. Check us out on Instagram for more similar content.